Find size of an array in Perl

I seem to have come across several different ways to find the size of an array. What is the difference between these three methods?

my @arr = (2);
print scalar @arr; # First way to print array size

print $#arr; # Second way to print array size

my $arrSize = @arr;
print $arrSize; # Third way to print array size

Solution 1:

The first and third ways are the same: they evaluate an array in scalar context. I would consider this to be the standard way to get an array's size.

The second way actually returns the last index of the array, which is not (usually) the same as the array size.

Solution 2:

First, the second is not equivalent to the other two. $#array returns the last index of the array, which is one less than the size of the array.

The other two are virtually the same. You are simply using two different means to create scalar context. It comes down to a question of readability.

I personally prefer the following:

say 0+@array;          # Represent @array as a number

I find it clearer than

say scalar(@array);    # Represent @array as a scalar

and

my $size = @array;
say $size;

The latter looks quite clear alone like this, but I find that the extra line takes away from clarity when part of other code. It's useful for teaching what @array does in scalar context, and maybe if you want to use $size more than once.

Solution 3:

This gets the size by forcing the array into a scalar context, in which it is evaluated as its size:

print scalar @arr;

This is another way of forcing the array into a scalar context, since it's being assigned to a scalar variable:

my $arrSize = @arr;

This gets the index of the last element in the array, so it's actually the size minus 1 (assuming indexes start at 0, which is adjustable in Perl although doing so is usually a bad idea):

print $#arr;

This last one isn't really good to use for getting the array size. It would be useful if you just want to get the last element of the array:

my $lastElement = $arr[$#arr];

Also, as you can see here on Stack Overflow, this construct isn't handled correctly by most syntax highlighters...