[Top][All Lists]

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

Re: associative array assignment from the output of a function

From: Axel
Subject: Re: associative array assignment from the output of a function
Date: Fri, 22 Oct 2010 14:59:37 +0200
User-agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv: Gecko/20101013 Lightning/1.0b2 Thunderbird/3.1.5

Le 22/10/2010 14:42, Greg Wooledge a écrit :
Unreliable at best.  How do you handle elements that have whitespace
in them, for example?  You have to know your data set, choose a delimiter
that can't be in that set, and then write code to parse the output stream
into elements.

At this moment, I "solve" the problem of whitespace with a custom IFS :
    echo "value 1\x1Evalue2"

IFS=$'\x1E' myvar=( $(func) )

Ick.  You're attempting to use the language's internal assignment syntax
in *data*.  Sounds like you're on the road to eval, and we all know
where *that* one ends!

What you appear to be attempting to do is "return an associative array
from a function to the caller".  Bash's functions aren't really
*functions* in the mathematical sense, or even in the sense of most
high-level computing languages.  They are really commands.  User-definable
commands.  They don't return data.  They only return an exit status.

But that's a tangent.  Anyway, if you want to make it so that after the
function has returned, the caller has a brand new associative array, then
what you need to do is:

  1) Pre-declare the associative array in the CALLER, not in the function,
     because it is currently not possible for a function to create an
     associative array in the global namespace.  AAs have to be created
     by using "declare", and if you use "declare" inside a function, it
     makes a local variable.  Chet has said there will be a workaround
     for this in bash 4.2.

  2) Inside the function, put the data into the AA.  No, you can't pass the
     name of the array from the caller to the function either.  You must
     HARD-CODE the array's name in the function.

  3) Make sure you do NOT call the function in a subshell.

Any attempts to return advanced data structures from a function using
the techniques you'd expect in a high-level language just won't work
in bash.  It's a shell.  It's not designed for this kind of task.  Just
use a global variable and be happy.

Even if such needs of complex values built by functions are somewhat unusual (or even just a bad idea), I came to the same conclusion to use a global variable. Thanks a lot for your answer, I ll be happy with a global variable.

Anyway, since this syntax works for assigning indexed arrays (even if it's a "hack"), should it works for associative array assignment ? Maintainers will decide I assume.

reply via email to

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