Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: array prepend



On Jan 15, 12:18am, rahul wrote:
}
} I was hoping to assign lists (arrays) to an associative array, and got the
} error which is well documented on the internet. But no one has given any
} workaround or alternative to this.
} 
}    FOO[a]=("a command" "some text" "etc etc")
} 
} zsh: FOO: attempt to set slice of associative array

Right, that syntax means to take the element at [a] and splice the
words inside the parens into the array at that position, replacing
the value at [a].  You can't splice an associative array.

} Is the only alternative to do the following:
} 
} FOO_a=( a list)
} FOO_b=(another list)

It took me a while but I think I finally understand what you are asking
about here.  You want to implement a two-dimensional array.  This is not
directly supported in most shells (I don't know whether recent ksh has
come up with some kind of syntax for it).

The best you can do is to simulate the 2D array by placing a value at
the position in the "outer" array which represents the name of another
array that holds the "inner" array.

E.g. to assign an array to FOO[a] you need something like

    typeset -i _x=0
    typeset -A FOO

    set -A ${FOO[a]::=FOO$[++_x]} "a command" "some text" "etc etc"

Then ${(P)FOO[a]} will retrieve the array.  Of course, you also end up
needing to fiddle with a few other conventions as well, e.g., you must
do both

    unset $FOO[a]
    unset "FOO[a]"

to delete the "outer" element and its value.

This trick does not extend 2D associative arrays because ${(P)...}
cannot be told how to retrieve a named element of the "inner" hash;
it retrieves all the elements (in this case all the values in random
order) and returns them as an ordinary array with positional index.
I.e., ${(P)FOO[x][y]} is interpreted as ${${(@P)FOO[x]}[y]}.



Messages sorted by: Reverse Date, Date, Thread, Author