bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Unset array doesn't work


From: Greg Wooledge
Subject: Re: Unset array doesn't work
Date: Mon, 5 Mar 2018 08:57:08 -0500
User-agent: NeoMutt/20170113 (1.7.2)

On Sat, Mar 03, 2018 at 08:24:06PM +0900, Koichi Murase wrote:
> - Note: ksh seems not support local variables. "typeset" in function
> scopes defines a global variable, and "unset" removes the global
> variable.

"Real ksh" has two different kinds of functions -- ones declared with
"foo()" and ones declared with "function foo".  They have different
treatment of local variables, and the ksh man page does not clearly
(at least to me) describe the difference.

So, although this is slightly off-topic for bug-bash, here's a brief
demonstration:

wooledg:~$ ksh
$ rand() { nameref r="$1"; r=$RANDOM; }
$ rand foo
$ echo "$foo"
16875
$ rand r
ksh: typeset: r: invalid self reference

That much is just like bash.  Bash can do "local -n" to mimic "nameref"
but there is a variable name collision issue that makes it difficult
(or impossible) to use safely.

$ function rand2 { nameref r="$1"; r=$RANDOM; }
$ rand2 foo
$ echo "$foo"
4768
$ rand2 r
$ echo "$r"
28060

But with this kind of function, nameref actually *works* the way one
expects.  The collision issue is gone.  The function is able to receive
variable names as arguments and reference them in the caller's scope to
retrieve or store (send back) values, safely, no matter what variable
name the caller uses.

Bash does not have anything like this, and the attempts to create
something like this were what led to Freddy Vulto's "upvar" trick,
and much of the ensuing discussion.

I have not investigated how unset works in ksh's two different kinds
of functions, but if you only checked one of them, you may wish to
check the other as well.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]