I want to define an array in my BEGIN statement with undefined index number; how can I do this in AWK?
BEGIN {send_packets_0to1 = 0;rcvd_packets_0to1=0;seqno=0;count=0; n_to_n_delay[];};
I have problem with n_to_n_delay[].
info gawk says, in part:
Arrays in 'awk' superficially resemble arrays in other programming languages, but there are fundamental differences. In 'awk', it isn't necessary to specify the size of an array before starting to use it. Additionally, any number or string in 'awk', not just consecutive integers, may be used as an array index.
In most other languages, arrays must be "declared" before use, including a specification of how many elements or components they contain. In such languages, the declaration causes a contiguous block of memory to be allocated for that many elements. Usually, an index in the array must be a positive integer.
However, if you want to "declare" a variable as an array so referencing it later erroneously as a scalar produces an error, you can include this in your BEGIN clause:
split("", n_to_n_delay)
which will create an empty array.
This can also be used to empty an existing array. While gawk has the ability to use delete for this, other versions of AWK do not.
a[length(a) + 1] = ...), and to start you need an empty array. Or else a is by default a scalar, and length() would fail. Another, however awkward, way to declare an empty array is: for (i in a) delete a[i].length to calculate an index definitely needs an empty array since AWK arrays are sparse and length + 1 may point to an existing element in an active array. Also, AWK arrays are really associative arrays and so they can have both numeric (which are really just strings) and string indices at the same time and incrementing indices doesn't make sense in these cases. Some versions of AWK may need a loop to clear an array, but delete a works in some of them.delete a is yet another way to create an empty array in GNU Awk 4.2.1.delete array to delete the whole array, the idiom split("", array) is used and avoids needing a loop. There's no need to declare an array (or to create an empty array) unless you want to ensure that a scalar assignment produces an error since arrays are automatically instantiated on first reference.I don't think you need to define arrays in awk. You just use them as in the example below:
{
if ($1 > max)
max = $1
arr[$1] = $0
}
END {
for (x = 1; x <= max; x++)
print arr[x]
}
Notice how there's no separate definition. The example is taken from The AWK Manual.