There are various ways to print size of an array. Here are the meanings of all:
Let’s say our array is my @arr = (3,4);
Method 1: scalar
This is the right way to get the size of arrays.
print scalar @arr; # Prints size, here 2
Method 2: Index number
$#arr
gives the last index of an array. So if array is of size 10 then its last index would be 9.
print $#arr; # Prints 1, as last index is 1
print $#arr + 1; # Adds 1 to the last index to get the array size
We are adding 1 here, considering the array as 0-indexed. But, if it's not zero-based then, this logic will fail.
perl -le 'local $[ = 4; my @arr = (3, 4); print $#arr + 1;' # prints 6
The above example prints 6, because we have set its initial index to 4. Now the index would be 5 and 6, with elements 3 and 4 respectively.
Method 3:
When an array is used in a scalar context, then it returns the size of the array
my $size = @arr;
print $size; # Prints size, here 2
Actually, method 3 and method 1 are same.
print 0+@arr
,print "".@arr
,print ~~@arr
– Waugh"".@arr
as"@arr"
does something quite different. – Haines