Reputation: 103
I created a 2d(mxn) array,@ary_2d, which is used to read different values from different files. Thus, the m and n values keep changing. It is very hard to determine the scalar because each file has different data set, especially for different m values. How can I determine m and n in a simple way? For 1d array, let's say @ary_1d, I can decide it using $#ary_1d. How can I decide the m and n values in the similar way? Any suggestion or easier way would be highly appreciated. Let's see an example below.
my @ary_2d=([12,13,14,15],[67,68,69,70,71]);
# row 1: [12,13,14,15] with 4 elements/columns; row 2: [67,68,69,70,71] with 5 elements/columns
in 1d array, like @ary_1d, we can use
$#ary_id
to get the size of this array. However, how can we get the m value (row value) when we handle 2 or higher dimension arrays? Any simple and clear command would be highly appreciated.
Best, Leon
Upvotes: 1
Views: 636
Reputation: 241828
$#array
gives you the index of the last element, the size is in fact $#array + 1
or scalar @array
(or @array
in scalar context). To get the size of a nested array, use dereference:
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
my @ary_2d=([12,13,14,15],[67,68,69,70,71]);
my $size = @ary_2d;
print "m: $size\n";
print "n: ", scalar @$_, "\n" for @ary_2d;
Upvotes: 1
Reputation: 26121
use List::Util qw( max );
my @ary_2d=([12,13,14,15],[67,68,69,70,71]);
printf "%dx%d\n", 0+@ary_2d, max map 0+@$_, @ary_2d;
Upvotes: 1