Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: Passing array to function
- X-seq: zsh-users 21994
- From: Daniel Shahaf <d.s@xxxxxxxxxxxxxxxxxx>
- To: Ignatius Reilly <turnbuckle@xxxxxxxxx>
- Subject: Re: Passing array to function
- Date: Fri, 30 Sep 2016 07:45:09 +0000
- Cc: zsh-users@xxxxxxx
- Dkim-signature: v=1; a=rsa-sha1; c=relaxed/relaxed; d= daniel.shahaf.name; h=cc:content-transfer-encoding:content-type :date:from:in-reply-to:message-id:mime-version:references :subject:to:x-sasl-enc:x-sasl-enc; s=mesmtp; bh=Y1TMzPBxhJz6W6Of ACngiI/BGhc=; b=saRXnCMnCPYlYOTVqn1/VHM4JghSyWykKWusJsOZgfb0pvGO TRgIWAGurjJ2TXlGbDJl74maGeKLT/LqqGHy50Q+BsavGFL3QhkUi03EKHEJHNOb m0dSO/PhvTSOiUen51W4tNUqpr/BlgVWIoIIQQYMJ2xo1eA5OQ3Iy0ta0l8=
- Dkim-signature: v=1; a=rsa-sha1; c=relaxed/relaxed; d= messagingengine.com; h=cc:content-transfer-encoding:content-type :date:from:in-reply-to:message-id:mime-version:references :subject:to:x-sasl-enc:x-sasl-enc; s=smtpout; bh=Y1TMzPBxhJz6W6O fACngiI/BGhc=; b=fx8uQiP7bGeh8TaXUTUEMwYa2qYuDvJtUS6v9yIgVj3JfHq qlPUEcUq2K7R8LzWilgCkpMOZsh0fmH3z+6ATUwCabAJOZp6yTk6X+Ye3mulAa+Q MperDCRy8v9quAm9Go2DY1YLVSVgocaraixRvnSOgCHAV8DZKn7DqB18Yp9M=
- In-reply-to: <1A643BF6-28C9-483E-9312-D8C856D41F0D__26800.772539764$1475219850$gmane$org@gmail.com>
- List-help: <mailto:zsh-users-help@zsh.org>
- List-id: Zsh Users List <zsh-users.zsh.org>
- List-post: <mailto:zsh-users@zsh.org>
- Mailing-list: contact zsh-users-help@xxxxxxx; run by ezmlm
- References: <1A643BF6-28C9-483E-9312-D8C856D41F0D__26800.772539764$1475219850$gmane$org@gmail.com>
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.
Cheers,
Daniel
> Thanks
>
Messages sorted by:
Reverse Date,
Date,
Thread,
Author