Arrays

Create an array

% local -a buffer
% buffer=(a b c)

Create an array with each words of a string

% string="Welcome to the real world, Neo"
% buffer=(${=string})

Create an array of lines from a file

% buffer=("${(f)$(< /etc/hosts)}")
% echo $buffer[1]
127.0.0.1       eva-O1.linagora.com     eva-01

Find element position in array

arr=(a b cv de)
echo ${(k)arr[(r)a]}   #this will print "1"
echo ${(k)arr[(r)imnothere]} #this will print 5, that is n+1.
echo ${arr[(r)imnothere]} #this will print nothing. that is, you can do if [[ -n to check if an element belongs to an array

Associative variant

If you are using associative arrays,

echo ${arr[(r)imnothere]}

is not fine, because you could have a key whose value is in fact an empty string. Luckily,

echo ${(k)arr[(r)imnothere]}

WILL return an empty string, so the change is easy

 
scripting/array.txt · Last modified: 2011/08/18 09:41 by jessew