Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
A way to apply function to each element of an array
- X-seq: zsh-users 24190
- From: Sebastian Gniazdowski <sgniazdowski@xxxxxxxxx>
- To: Zsh Users <zsh-users@xxxxxxx>
- Subject: A way to apply function to each element of an array
- Date: Thu, 29 Aug 2019 02:49:10 +0200
- Dkim-signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=mime-version:from:date:message-id:subject:to; bh=nkVKR10WHJ2ld8mcGAk9jaIHhw56Fs/cahsskKWG+w0=; b=XH2jPUkFiC8D0Gq+Z5L3wspn+Oc5a475iOUpgiEw6BbXFrhXpwCnkqsyyWoLOQNHEa nO9Ly/F48hXUF2RPSgdleZsVC9BlQ5eg74YUnktY9zzAREQS1P1AIcvIF7ETUxDYHJE9 PoPSN5mFAhptnhka9ICINxWCVpW6oGctK7JsVHWTOoEWqor0ugr2OiqOyqFHR4jUnLMk DXPewaHPM/H516aqgHtyQBA4/sbuOIrw63k+XcVo3PpohgyKPSbTtfdjNCiYSHchu1ep ZnQ/bvWXEidzZPDJhxR7N6kPIWemu24WFc7jJAkbH3k9DGXvmDfFfS+extyWcajCH87j +glQ==
- List-help: <mailto:zsh-users-help@zsh.org>
- List-id: Zsh Users List <zsh-users.zsh.org>
- List-post: <mailto:zsh-users@zsh.org>
- List-unsubscribe: <mailto:zsh-users-unsubscribe@zsh.org>
- Mailing-list: contact zsh-users-help@xxxxxxx; run by ezmlm
Hello,
I thought that I share a method of applying of function to each
element of an array. I think that it's obvious for someone interested
in // substitution and (#m) and (#b) flags, but not necessarily for
others. Also, it would be much more beautiful if zsh would support
mksh's substitution ${|func;} which is replaced by the value that func
assigns to REPLY, assuming that func can take some arguments (i.e. the
$MATCH in the use case):
msfunc() { REPLY="${(Q)1} $RANDOM"; return 0; }
functions -Ms msfunc 1 1 msfunc
myarr=( value1 value2 abc1 abc2 )
myarr=( "${(@)${myarr[@]/(#m)*/$(( msfunc(${(q)MATCH}) ))$REPLY}/(#s)0/}" )
print -rl $myarr
Output:
value1 21720
value2 18920
abc1 3318
abc2 14483
The (#s) matches the start of the string and is just for to ensure
correctness and not actually needed. It however might save some time
when debugging code, when some 0s start to disappear from the strings
because of an specific, not always matching pattern (with (#b) flag,
for example). The 0 can be also changed to some random number in such
case.
--
Sebastian Gniazdowski
News: https://twitter.com/ZdharmaI
IRC: https://kiwiirc.com/client/chat.freenode.net:+6697/#zplugin
blog: http://zdharma.org
Messages sorted by:
Reverse Date,
Date,
Thread,
Author