How many items in Perl array

Task. In the code of the Perl program has an array @arr (the first three letters from the word "array"). In this array has some values. Need to know how many in this array contains elements.

There are several ways to solve this problem.

Use scalar context

If you use the array in scalar context, then this value will be the number of elements in the array:

my $number_of_elements = scalar(@arr);

Example program:

▶ Run
#!/usr/bin/perl

my @arr = ('one', 'two', 'three');

print scalar(@arr);

The program displays the number 3.

Scalar context can be obtained not only by using scalar(), but with the help of some arithmetic operations, which does not change the number, for example, to add/subtract zero or multiply/divide unit:

my $number1 = @arr + 0;
my $number2 = @arr - 0;
my $number3 = @arr * 1;
my $number4 = @arr / 1;

To use a variable with the index of the last element

Another way to find out the length of the array is to use a variable associated with the array and which contains the number of the last element. If the array is called @arr, such a variable will be called $#arr. The first element in a Perl array has number 0, so to get the number of items you need to add this variable to 1.

my $number_of_elements = $#arr + 1;

How to count different elements and undef

It does not matter what values are contained in the array. There can be simple strings and numbers and complex structures.

If the array contains the value undef, then they too are. Here is an example of an array which contains 4 elements:

my @arr = (1, undef, 3, undef);

Wrong way of counting is to use length()

Here is a sample program. The program displays the number 1 and can wrongly assume that length() applied to an array returns the number of elements in it.

▶ Run
#!/usr/bin/perl

my @arr = ('one');

print length(@arr);

But this is an incorrect assumption. In order to verify this you can check that for an array my @arr = ('one', 'two', 'three') length()will return 1.

length() applied to the array return the number of elements and the number of digits in the number of elements. If the array contains 9 or fewer items, then length(@arr) will return 1 if the array contains from 10 to 99 elements, length(@arr) will return 2, and so on.

Related topics

Other articles

Comments