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

A way to apply function to each element of an array

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

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

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