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

Re: (P) param expansion with assoc-arrays



On Mar 23,  9:39am, Shawn Halpenny wrote:
} 
} typeset -A hash
} hash=( a 1 b 2 c 3 )
} 
} blah="hash"
} 
} echo ${${(P)blah}[b]}
} 
} How can I get that expression to return '2'?

${(P)blah} expands to the value of the variable whose name is the value
of blah -- NOT to the variable whose name is the value of blah.  Note
the not-so-subtle difference.  Thus the following outputs "2":

blah="hash[b]"
echo ${(P)blah}

So you first have to paste together the value of blah with the [b] and
then apply (P) to the result.  This can be done in a non-obvious way:

echo $((P)${:-${blah}[b]}}

The :- is "substitute the string to my right if the variable to my left
has no value."  As there is no variable name to the left, there is no
value, and hence the string consisting of the expansion of ${blah} and
the so-far-meaningless [b] is substituted.  Then (P) applies, and the
substituted string is given the meaning you wanted.



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