In the zshexpn manual page (zsh version 5.1.1) we have:

Parameter Expansion Flags

(P): This forces the value of the parameter name to be interpreted as a further parameter name, whose value will be used where appropriate. Note that flags set with one of the typeset family of commands (in particular case transformations) are not applied to the value of name used in this fashion.

So, if I have a regular array parameter, I can do this:

typeset -a array
array=(x y)

echo ${${(P)ptr}[1]}

and this will output x. I presume this is because the -a typeset flag is not necessary to mark the parameter as an array.

But if I do the same with an associative array:

typeset -A assoc
assoc=(foo x bar y)

echo ${${(P)ptr}[foo]}

nothing is printed to the screen. This appears consistent with the man page message above because if we run:

echo ${(P)ptr}
# returns: x y
echo ${${(P)ptr}[1]}
# returns: x
echo ${${(P)ptr}[2]}
# returns: y

we get behaviour as if the the -A flag to typeset was discarded, and we have a normal array.

But if I run the following:

echo ${(Pk)ptr}
# returns: foo bar
echo ${(Pv)ptr}
# returns: x y
echo ${(Pkv)ptr}
# returns: foo x bar y

then it seems as if in some sense the associative array status is not always lost. So I don't really understand why it was designed so that typeset flags are discarded, when it looks like they don't always do this anyway.

And, mainly, my question is this: is there some way to make this:

echo ${${(P)ptr}[foo]}

return x (the value associated to the key foo) as if the typeset -A flag were not discarded, and I can treat it like any other associative array. I would like to not resort to using evals: is there some zsh parameter trickery that I can use instead?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.