Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define dynamic array in Begin Statement with AWK

Tags:

awk

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[].

like image 841
Am1rr3zA Avatar asked Dec 04 '10 10:12

Am1rr3zA


People also ask

How do you declare a dynamic array?

Dynamic arrays in C++ are declared using the new keyword. We use square brackets to specify the number of items to be stored in the dynamic array. Once done with the array, we can free up the memory using the delete operator. Use the delete operator with [] to free the memory of all array elements.

How do you create an array in awk?

In awk , you don't need to specify the size of an array before you start to use it. Additionally, any number or string in awk may be used as an array index, not just consecutive integers. In most other languages, you have to declare an array and specify how many elements or components it contains.

How arrays are processed using awk?

AWK has associative arrays and one of the best thing about it is – the indexes need not to be continuous set of number; you can use either string or number as an array index. Also, there is no need to declare the size of an array in advance – arrays can expand/shrink at runtime.

What is the syntax of dynamic array dynamic?

Syntax: ReDim {Preserve] array_name(subscripts)


1 Answers

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.

like image 182
Dennis Williamson Avatar answered Sep 22 '22 12:09

Dennis Williamson