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

Re: [PATCH 1/3]: Add named references



2023-02-10 23:45:36 -0800, Bart Schaefer:
[...]
> A named parameter declared with the '-n' option to any of the 'typeset'
> commands becomes a reference to a parameter in scope at the time of
> assignment to the named reference, which may be at a different call
> level than the declaring function.  For this reason, it is good practice
> to declare a named reference as soon as the referent parameter is in
> scope, and as early as possible in the function if the reference is to a
> parameter in a calling scope.
[...]

One difference with ksh93: if the target variable was not set at
the time of the "typeset -n ref=target", then when ref is
assigned it may end up refering to a local target:

$ ./Src/zsh -c 'function f { typeset -n ref=$1; typeset var=foo; ref=X; echo "$ref ${(!)ref} $var"; }; f var; echo "$var"'
X var X

$ ./Src/zsh --emulate ksh -c 'function f { typeset -n ref=$1; typeset var=foo; ref=X; echo "$ref ${!ref} $var"; }; f var; echo "$var"'
X var X

$

Compare with ksh:

$ ksh -c 'function f { typeset -n ref=$1; typeset var=foo; ref=X; echo "$ref ${!ref} $var"; }; f var; echo "$var"'
X var foo
X

That's a common use case like for the zslurp function discussed
on zsh-users where one would do:

cmd | zslurp var

To get the output of cmd verbatim into $var with $var potentially undeclared
beforehand, which wouldn't work if var was used locally by zslurp.

It can be worked around with a typeset -g $1 before the typeset -n var=$1

$ ./Src/zsh --emulate ksh -c 'function f { typeset -g $1; typeset -n ref=$1; typeset var=foo; ref=X; echo "$ref ${!ref} $var"; }; f var; echo "$var"'
X var foo
X

But it seems to me it would be better to align with ksh's
behaviour in this instance.

-- 
Stephane




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