[Top][All Lists]

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

Re: Q: what is a fast way to see if an 'item' is present in an array?

From: Martijn Dekker
Subject: Re: Q: what is a fast way to see if an 'item' is present in an array?
Date: Wed, 17 Feb 2016 07:25:46 +0100
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:31.0) Gecko/20100101 Thunderbird/31.2.0

Linda Walsh schreef op 16-02-16 om 04:59:
> w/the slow func  being killed by a $() sub process, likely:

Yes, subshells are fatal for performance, particularly on bash.

> my fn2='() {        my t="${2:?}[*]"
>    my arRE="^($(IFS="|"; echo "${!t}"))$"
>    [[ $1 =~ $arRE ]]
> }
> '

(What's "my"? An alias for "local"?)

Try this:

appears_in() {
        local IFS="|" val="$1"
        [[ "$IFS$*$IFS" == *"$IFS$val$IFS"* ]]
if appears_in "somevalue" "address@hidden"; then do stuff; fi

For anyone reading who may not know, the trick is that "$*" expands to a
single string containing all the positional parameters separated by the
first character of $IFS (or with no separator if IFS is empty, but
that's not useful here).

Of course this function is dependent on none of the elements containing
"|". But this lets you set any separator you want, so you could use a
really unlikely character such as IFS=$'\1'.

- M.

reply via email to

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