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

Finding the last row / element in a 2D array 1

Status
Not open for further replies.

parkers

Vendor
Oct 21, 2002
157
GB
Hi,

In a single dimension array it is easy to find the last element of the array:
i.e.
$#array or $array[$#array]

however does anyone know of a neat way to find the last "row" in a 2 Dimensional Array?

e.g. say I want to find:

$array[last_row][0..whatever]

Any help would again be appreciated

Thanks
 
Yeah, I think you are screwed without recording/using another variable to keep track of either dimensions' size.

The reason being that a 2D array is stored as a 1D array.

Sorry dude. But take this with a grain of salt as I am new to Perl, though I've spent many lifetimes in C/C++;
 
Try

$#{$array[$#array]}

This gets the last element of the first array and then de-references it to get the last element of the second array.

Seemed to work on my system.

$array[0][0]="a";
$array[0][1]='b';
$array[0][2]='c';
$array[0][3]='d';
$array[1][0]='e';
$array[1][1]='f';
$array[1][2]='g';
$array[1][3]='h';
$array[1][4]='i';

print "It is $#array\n" ;
print "it is $#{$array[$#array]}\n" ;

$ perl array.pl
It is 1
it is 4

Obviously zero based so 1 is 2 and 4 is 5 and so on :)
 
Sorry, if you want the lengths its obviously +1 to the value you get back.

If you just want the last item

$array[$#array][$#{$array[$#array]}]

so

first max index is $#array
second max index is $#{$array[$#array]}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top