bug-bash
[Top][All Lists]
Advanced

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

Re: associative array assignment from the output of a function


From: Greg Wooledge
Subject: Re: associative array assignment from the output of a function
Date: Fri, 22 Oct 2010 08:42:08 -0400
User-agent: Mutt/1.4.2.3i

On Fri, Oct 22, 2010 at 10:26:27AM +0200, Axel wrote:
> I try to assign an array from the output of a function.

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.

> As this works 
> for indexed arrays, it does not for associative arrays.

???  Huh?  How on earth...?

> # Does not work
> assocarray()
> {
>     echo "[a]=5 [b]=6"
> }
> declare -A t1=( $(assocarray) ) # The error occurs here

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.



reply via email to

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