I have a variable VARNAME which contains a name of another variable. I'd like to assign to this another variable without using eval. How can I do that?
Th reason I don't want to use eval is the following. Assume first a function for prepending foo variable:
% prepend_foo() { foo=("$@" $foo) }
% foo=(1 2)
% print -l $foo
1
2
% prepend_foo x 'a b c' y
% print -l $foo
x
a b c
y
1
2
%
Now consider a generalized function for appending to any variable:
% prepend() { var=$1; shift; eval "$var=($@ ${(P)var})" }
% foo=(1 2)
% print -l $foo
1
2
% prepend foo x 'a b c' y
% print -l $foo
x
a
b
c
y
1
2
%
As you can see, variables with spaces are split into several array items. I couldn't properly combine quote to achieve desired thing.
On IRC, someone suggested using ${name::=word}, but that doesn't work well with arrays:
21:23 < someone> > b=(bar baz); a=b; : ${(P)a::=(foo ${(P)a})}; typeset -p b
21:23 < machabot> someone: typeset b='(foo bar baz)'
21:23 < someone> dammit that's a string