Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: Passing array to function
- X-seq: zsh-users 21996
- From: Mikael Magnusson <mikachu@xxxxxxxxx>
- To: Daniel Shahaf <d.s@xxxxxxxxxxxxxxxxxx>
- Subject: Re: Passing array to function
- Date: Fri, 30 Sep 2016 10:28:19 +0200
- Cc: Ignatius Reilly <turnbuckle@xxxxxxxxx>, Zsh Users <zsh-users@xxxxxxx>
- Dkim-signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20120113; h=mime-version:in-reply-to:references:from:date:message-id:subject:to :cc:content-transfer-encoding; bh=IWn6anGrqfLV4ZUu+6uk2+hyq69bcr/16rLorLuLvBo=; b=yKCq9S4W/4QQze6t+c3yr6dAX0hNStJxoqNezYZnNNXaq/7OARfdWMg+xfCwrG21FA +p0px6HCNqwsSciHGNM4PEM0nSVKdClVq19LwAJznzv/oZw3usoLRXcp/ffm6vXVdW0K /ZsNa6c5QYkccyCT0f11UL8JTepnjgiNZa5FvRyeRtm+L61TeR8iMOewX+dYGSG1Fj2z Ms8BrMoLUK+4xMQEr4qMNNUzBPSgPYng9fxAejHyEsLXTMmXqQMzAjt4uyq1xwVWL3q6 ynR/e1wtSwLCDguq2MKE2/tKAB4i37ppa+BmGkZe9b+qNEjTCWJrXTEHnKxpFr0+8f58 JbIQ==
- In-reply-to: <20160930074509.GA2554@fujitsu.shahaf.local2>
- 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> <20160930074509.GA2554@fujitsu.shahaf.local2>
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