Home > Shell, Sysadmin > ZSH: Create dynamically associatives array in a function

ZSH: Create dynamically associatives array in a function

I’m currently working on some scripts to create CSV files (to import into iTop, I’ll post about it in few weeks) from data received via snmp. To make things propers, I want to reuse my code as far as possible, so I was looking for a way to create some associatives array in a function, where the array name is give as argument.

Thanks to the ZSH IRC channel (special thanks to ft) here a way to achieve that:


mytest() {
typeset -A -g $1
buffer="$1[$2]"
: ${(P)buffer::=$3}
}

so, the following sample code:


mytest() {
typeset -A -g $1
buffer="$1[$2]"
: ${(P)buffer::=$3}
}

mytest toto 3 42
mytest tutu 4 43

print -l $toto[3]
print -l $tutu[4]

will display 42, and then 43!

One final word: zsh is magic.

Categories: Shell, Sysadmin Tags:
  1. No comments yet.
  1. No trackbacks yet.