[perl] 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

This question is related to perl

The answer is


To use the second way, add 1:

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

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

The “Perl variable types” section of the perlintro documentation contains

The special variable $#array tells you the index of the last element of an array:

print $mixed[$#mixed];       # last element, prints 1.23

You might be tempted to use $#array + 1 to tell you how many items there are in an array. Don’t bother. As it happens, using @array where Perl expects to find a scalar value (“in scalar context”) will give you the number of elements in the array:

if (@animals < 5) { ... }

The perldata documentation also covers this in the “Scalar values” section.

If you evaluate an array in scalar context, it returns the length of the array. (Note that this is not true of lists, which return the last value, like the C comma operator, nor of built-in functions, which return whatever they feel like returning.) The following is always true:

scalar(@whatever) == $#whatever + 1;

Some programmers choose to use an explicit conversion so as to leave nothing to doubt:

$element_count = scalar(@whatever);

Earlier in the same section documents how to obtain the index of the last element of an array.

The length of an array is a scalar value. You may find the length of array @days by evaluating $#days, as in csh. However, this isn’t the length of the array; it’s the subscript of the last element, which is a different value since there is ordinarily a 0th element.


From perldoc perldata, which should be safe to quote:

The following is always true:

scalar(@whatever) == $#whatever + 1;

Just so long as you don't $#whatever++ and mysteriously increase the size or your array.

The array indices start with 0.

and

You can truncate an array down to nothing by assigning the null list () to it. The following are equivalent:

    @whatever = ();
    $#whatever = -1;

Which brings me to what I was looking for which is how to detect the array is empty. I found it if $#empty == -1;


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.


All three give the same result if we modify the second one a bit:

my @arr = (2, 4, 8, 10);

print "First result:\n";
print scalar @arr; 

print "\n\nSecond result:\n";
print $#arr + 1; # Shift numeration with +1 as it shows last index that starts with 0.

print "\n\nThird result:\n";
my $arrSize = @arr;
print $arrSize;

Use int(@array) as it threats the argument as scalar.


To find the size of an array use the scalar keyword:

print scalar @array;

To find out the last index of an array there is $# (Perl default variable). It gives the last index of an array. As an array starts from 0, we get the size of array by adding one to $#:

print "$#array+1";

Example:

my @a = qw(1 3 5);
print scalar @a, "\n";
print $#a+1, "\n";

Output:

3

3

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.


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...


Example:

my @a = (undef, undef);
my $size = @a;

warn "Size: " . $#a;   # Size: 1. It's not the size
warn "Size: " . $size; # Size: 2