[Top][All Lists]

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

Re: Passing variables by reference conflicts with local

From: Greg Wooledge
Subject: Re: Passing variables by reference conflicts with local
Date: Thu, 26 Apr 2012 14:49:08 -0400
User-agent: Mutt/

On Thu, Apr 26, 2012 at 12:02:20PM -0600, Bill Gradwohl wrote:
> bar_unset() {
>     unset var
>     echo address@hidden: $var
>     displayVar
>     displayVarbar_unset() {
>        echo address@hidden: $var
>     }
>     displayVarbar_unset
>     echo
>     newVar=bar_unset
> }

> When newVar is created in bar_unset, it is created at the main level.
> bar_unset is long gone and the variable it created lives on in Main. The
> tail wagging the dog comes to mind.

All variables are global unless declared local.  Since you don't have
newVar defined in any local scope, the final assignment in bar_unset
creates it at the global scope.

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

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 ...

... we don't see "r" here because it was scoped only within foo & its kids ...

reply via email to

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