bug-bash
[Top][All Lists]
Advanced

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

Re: Passing variables by reference conflicts with local


From: Bill Gradwohl
Subject: Re: Passing variables by reference conflicts with local
Date: Thu, 26 Apr 2012 13:37:57 -0600

On Thu, Apr 26, 2012 at 12:49 PM, Greg Wooledge <wooledg@eeg.ccf.org> wrote:

> I don't see this as a surprise.  It's how you return values from functions
> in bash.  Pick a global variable (r, ret, whatever you want) and stuff the
> return value into that.  You can even declare your "r" locally somewhere
> so that the value never propagates up higher than that point in the call
> chain.
>
> For example:
>
> # Return random number from 0 to ($1-1) in variable "r"
> rand() {
>  local max=$((32768 / $1 * $1));
>  while (( (r=$RANDOM) >= max )); do :; done
>  r=$((r % $1))
> }
>
> foo() {
>  local r
>  rand 42
>  ... use $r ...
> }
>
> foo
> ... we don't see "r" here because it was scoped only within foo & its kids
> ...
>


Your example is what I always do. I create a variable (local or global -
its non of the called functions business which) and then I call a function
and allow it to use that variable to return an answer. When the function
ends it hasn't altered the global name space.

In the example I presented, the opposite is occurring. The function being
called creates the return variable and necessarily does it in the global
name space. When the function quits, the global it created lives on. It
just never occurred to me to try that and was surprised that the tail could
wag the dog.

If I'm several levels deep into function calls when I create a local
variable and then call a function that I allow to use that variable, that
has a semblance of control. The parent is supplying something the child may
use. When the child creates a global to pass back information, and then
terminates, the parent had no control over that variables creation and is
now stuck with something in the global name space that via the hierarchy of
calls, it doesn't properly own. I would never purposely write code that did
that, and was surprised that bash allows it.

-- 
Bill Gradwohl


reply via email to

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