Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Multidimensional array help

Status
Not open for further replies.

h0vis

MIS
Oct 6, 2008
1
FR
Hi,

I'm emulating a multidimensional array in awk and getting strange results from the length(arrayname) command.

What am I doing wrong? How do I fix it?

Here's my test code:
BEGIN {
TABLE["cfg",0]="0"
TABLE["cfg",1]="1"
TABLE["cfg",2]="2"
TABLE["cfg",3]="3"
TABLE["cfg",4]="4"
TABLE["cfg",5]="5"
TABLE["tst",0]="0"
TABLE["tst",1]="1"
TABLE["tst",2]="2"
TABLE["tst",3]="3"
TABLE["tst",4]="4"
TABLE["tst",5]="5"
TABLE["tst",6]="6"
TABLE["tst",7]="7"
TABLE["tst",8]="8"
TABLE["tst",9]="9"
TABLE["tst",10]="10"
}

END {
TST="tst"
print "length(TABLE)="length(TABLE)
for( i=0; i<length(TABLE); i++ ) {
print "length(TABLE)="length(TABLE)" TABLE["TST","i"]="TABLE[TST,i]
if ( i>20 ) {print "Terminating because it is broken"; break }
}
}

This produces this:
length(TABLE)=17
length(TABLE)=17 TABLE[tst,1]=1
length(TABLE)=17 TABLE[tst,2]=2
length(TABLE)=17 TABLE[tst,3]=3
length(TABLE)=17 TABLE[tst,4]=4
length(TABLE)=17 TABLE[tst,5]=5
length(TABLE)=17 TABLE[tst,6]=6
length(TABLE)=17 TABLE[tst,7]=7
length(TABLE)=17 TABLE[tst,8]=8
length(TABLE)=17 TABLE[tst,9]=9
length(TABLE)=17 TABLE[tst,10]=10
length(TABLE)=17 TABLE[tst,11]=
length(TABLE)=18 TABLE[tst,12]=
length(TABLE)=19 TABLE[tst,13]=
length(TABLE)=20 TABLE[tst,14]=
length(TABLE)=21 TABLE[tst,15]=
length(TABLE)=22 TABLE[tst,16]=
length(TABLE)=23 TABLE[tst,17]=
length(TABLE)=24 TABLE[tst,18]=
length(TABLE)=25 TABLE[tst,19]=
length(TABLE)=26 TABLE[tst,20]=
length(TABLE)=27 TABLE[tst,21]=
Terminating because it is broken

Notice how the length result starts incrementing after the 11th iteration, this I do not understand!!

Any ideas?

Regards,
Andrew
 
length() is for measuring string lengths, not array lengths. You'll need to keep track of the number or elements in the array yourself, or use the for (index in array) construct (which I realise is not ideal for multi-dimensional arrays).

Annihilannic.
 
Hi

Do as Annihilannic suggested.

Just one thing to mention, although it is not a big help for multidimensional arrays :
man gawk said:
Starting with version 3.1.5, as a non-standard extension, with an array argument, length() returns the number of elements in the array.

Feherke.
 
awk '
{myarray[$1 $3]}
END {
n=asorti(myarray)
for(i=1; i<=n; i++)
print length(myarray), myarray
}'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top