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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Two-dimensional array/While statement not exiting - very strange 1

Status
Not open for further replies.

sloppyhack

Technical User
Apr 17, 2001
111
US
I am trying to cycle through all of the "rows" of a two dimensional array. I can cycle through and access/print the elements I want, but the loop does not exit? Here's an example of the code.

while (@aliasdata) {
++$aliasrow;
print TEMP $aliasdata[$aliasrow][1],"\n";
}

@aliasdata remains true and I get an infinite loop which prints the elements of the file but continues to print "\n" indefintely. Works without using the $aliasrow variable? Anyone know why this is happening?

Thanks
Bryant
Boulder CO
 
The statement 'while (@aliasdata)' is true as long as @aliasdata is defined. Since the while loop does not modify the array @aliasdata, the while statement will always be true. A 'for' loop would work better in this situation.

for ($aliasrow=0; $i<=$#aliasdata; $aliasrow++) {
print TEMP $aliasdata[$aliasrow][1],&quot;\n&quot;;
}
 
Thanks. I am still getting the same result. The loop is not exiting. Prints the correct elements of the file but continues to print &quot;\n&quot; indefinitely? Does it have something to do with the fact that it's a two-dimensional array?

Bryant
 
Here's something else that's strange. $alisedata is null? I would expect it to be equal to the number of elements in that array. The fact that this is a two-dimensional array must be screwing things up.
 
Sorry about that. The problem is that I put the index that I usually use '$i' where $aliasrow should have been. The following should work:

for ($aliasrow=0; $aliasrow<=$#aliasdata; $aliasrow++) {
print TEMP $aliasdata[$aliasrow][1],&quot;\n&quot;;
}

 
Nice!!! Yep that worked. Not used to using &quot;$#&quot; to define the number of elements in an array. Works though.

Thank you so much!

Bryant
 
Another - more perlish - way is:

foreach (@aliasdata) {
print TEMP $_->[1];
}

This make no use of temporary variables.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top