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

Re: Passing array to function



On Fri, Sep 30, 2016 at 9:45 AM, Daniel Shahaf <d.s@xxxxxxxxxxxxxxxxxx> wrote:
> Ignatius Reilly wrote on Fri, Sep 30, 2016 at 02:15:55 -0500:
>> addtoarray() { [[ -d $1 ]] && myarray=($1 $myarray) }
>>
>> which works as expected, prepending an element to an array only if its an
>> existing directory.  I'd like to rewrite this function so that I can pass
>> the array name as a parameter like so:
>>
>> addtoarray /usr/foo myarray
>
> You could do it with eval:
>
> addtoarray() {
>   [[ -d $1 ]] && eval "${(q)2}[1,0]=${(q)1}"
> }
>
> Explanation:
>
> - The (q) are there to convert the values to command-line-quoted
>   strings, for eval.  $2 probably needs no quoting — if it did, the eval
>   would see a syntax error — but I put the (q) anyway to guard against
>   invalid inputs (bobby tables attacks against the eval).
>
> - After parameter substitution, the resultant string is:
>     myarray[1,0]=/usr/foo
>   which is a slice assignment that prepends an element to the named
>   array.
>
> If there's a solution without eval I'm sure someone will post it.

addtoarray() { [[ -d $1 ]] || return; local p="$2[1,0]"; : ${(P)p::=$1} }
I forgot about [1,0] yesterday when you asked on IRC.

-- 
Mikael Magnusson



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