As numerous answers pointed out, the first and third way are the correct methods to get the array size, and the second way is not.
Here I expand on these answers with some usage examples.
@array_name
evaluates to the length of the array = the size of the array = the number of elements in the array, when used in a scalar context.
Below are some examples of a scalar context, such as @array_name
by itself inside if
or unless
, of in arithmetic comparisons such as ==
or !=
.
All of these examples will work if you change @array_name
to scalar(@array_name)
. This would make the code more explicit, but also longer and slightly less readable. Therefore, more idiomatic usage omitting scalar()
is preferred here.
my @a = (undef, q{}, 0, 1);
# All of these test whether 'array' has four elements:
print q{array has four elements} if @a == 4;
print q{array has four elements} unless @a != 4;
@a == 4 and print q{array has four elements};
!(@a != 4) and print q{array has four elements};
# All of the above print:
# array has four elements
# All of these test whether array is not empty:
print q{array is not empty} if @a;
print q{array is not empty} unless !@a;
@a and print q{array is not empty};
!(!@a) and print q{array is not empty};
# All of the above print:
# array is not empty