2
Why do I get only "cat" when I run
awk 'BEGIN {
animal[three] = "hen"
animal[two] = "dog"
animal[one] = "cat"
for (var in animal) {
print animal[var]
}
}
??
Shouldn't it print "hen", "dog" and "cat"?
2
Why do I get only "cat" when I run
awk 'BEGIN {
animal[three] = "hen"
animal[two] = "dog"
animal[one] = "cat"
for (var in animal) {
print animal[var]
}
}
??
Shouldn't it print "hen", "dog" and "cat"?
4
Indices to awk arrays can either be numeric (as in a traditional array) or strings (an associative array). So you can either do
animal[1] = "cat"
or
animal["one"] = cat
However, if you do
animal[one] = cat
awk will try to find a variable called 'one', fail, and effectively do this:
animal[""] = cat
So in your program, all three animals are assigned to animal[""]
, so you end up with only one element in your array.
If you put one
, two
and three
in quotes, your code will work as you expect.
1Good one! You can also indicate by printing print animal[var], "-"var"-"
. var
is empty, -
to show where it starts and where it ends. – fedorqui – 2014-04-10T08:29:27.893
Missing a
'
at the end of the code. – fedorqui – 2014-04-10T08:28:16.380