locally declared arrays do not act as arrays

2006-05-21 Thread Andrew Stitt
Configuration Information [Automatically generated, do not change]:
Machine: i686
OS: linux-gnu
Compiler: gcc
Compilation CFLAGS:  -DPROGRAM='bash' -DCONF_HOSTTYPE='i686' 
-DCONF_OSTYPE='linux-gnu' -DCONF_MACHTYPE='i686-pc-linux-gnu' 
-DCONF_VENDOR='pc' -DLOCALEDIR='/usr/share/locale' -DPACKAGE='bash' -DSHELL 
-DHAVE_CONFIG_H  -I.  -I. -I./include -I./lib   -O -march=pentium-m -mmmx 
-mfpmath=sse -msse2 -pipe -ffast-math -funroll-loops -O3
uname output: Linux courier 2.6.11 #6 Sun May 8 23:59:20 PDT 2005 i686 unknown 
unknown GNU/Linux
Machine Type: i686-pc-linux-gnu

Bash Version: 3.0
Patch Level: 16
Release Status: release

Description:
when I declare a local variable as an array it still acts as a scalar,
not as an array.

I discovered that if I seperate the local declaration from the
initialization, the variable properly acts as an array.

Repeat-By:

f() {
  local B=("a" "b")
  echo $B
  C=("a" "b")
  echo $C
}
A=("a" "b")
echo $A
f

Produces:
a
(a b)
a

Workaround:
split the declaration and initialization:
local B
B=("a" "b")



___
Bug-bash mailing list
Bug-bash@gnu.org
http://lists.gnu.org/mailman/listinfo/bug-bash


Re: NOT changing global variables

2006-12-29 Thread Andrew Stitt
On Fri, Dec 29, 2006 at 11:43:14PM +0100, Frans de Boer wrote:
> Yes, I did expected such an answer of using a subshell, and yes I can
> get the return value, but I don need it. I need the output fed into
> another (maybe local) variable. I was under the impression that BASH was
> modeled after 'C', so I started using the functions as such. My mistake.
> I have the confirmation that it's not so strait forward as I expected.
> Never mind, I now know better, so thanks for the comment anyway.

One technique I use instead of output capturing is to use a variable
"reference". In the function allow the caller to specify a variable _name_
as a parameter. Then use eval to store the results in that variable
instead of sending it to stdout. This is similar to tcl's "upvar".

function foo() {
  local data=
  eval $1=\$data
}

a=1
echo $a
foo a
echo $a

If you didn't actually need a subshell to begin with then this eliminates
it. Removing extra subshells can help speed up your program, if thats
somethig that matters to you (it does to me, fwiw). Or if nothing else,
you limit the subshell's scope.

Goes without saying, that you should pick a naming convention for
variable names you intend to pass. Otherwise local function variables
may collide. "data" in place of "a" would be a bad choice in the above
example :-)

There may also be technical limitations to using eval like this. If
there are, Im eager to hear them.

-Andrew



___
Bug-bash mailing list
Bug-bash@gnu.org
http://lists.gnu.org/mailman/listinfo/bug-bash