Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

associative array questions



Experimenting with associative arrays:

typeset -Ag aa IN

test1 ()
{
    aa[first]=1
    aa[second]=two
    aa[third]='three blind mice'
}

test2 ()
{
    set -A IN ${(Pkv)${1}}
    IN[second]='tea for two'
    set -A "$1" ${(kv)IN}
}

test3 ()
{
    aarray="$1"
    print "aa[second] is: ${${(P)aarray}[second]}"
# BAD:
#    ${(P)aarray}[second]='tea for two'
# GOOD:
    eval "${aarray}[second]='tea for two'"

    print "\naa changed:\n"
    printf "%-10s %s\n" ${(kv)aa}
}

... test2 works fine and it's how my existing code does it. test2 and test3 might have to chew on one of several possible arrays so the use of '$1' is necessary.  However, C-brained as I am, I'm wanting to link to the input array directly via a pointer sort of operation so in test3 I'm trying to grab the name of the target array and modify it (the array) directly. The 'print' works fine.  So I think to myself: strip off the outer '${}' and now we have the name of the element, not it's expansion, so an assignment should be possible, but it doesn't work.  '${(P)aarray'} should expand to 'aa' remembering that it's a variable -- so I think. However doing it via 'eval' works.   In practice test2 has the more streamlined code but I'm still curious that the BAD attempt at an assignment doesn't work.  I know I'm thinking too visually. BTW, it's also unexpected that the array prints upside down:

$ . test1; test1; test3 aa
aa[second] is: two

aa changed:

third        three blind mice
second    tea for two
first        1

... are associative arrays appended at the top?  I know that with associative arrays the element order isn't the primary thing but still.






Messages sorted by: Reverse Date, Date, Thread, Author