Prev

Perl Notes

Next

Finding the length of an array

It is often usefull to know how many elements an array contains. There are three ways to get the length of an array.

To store the length of an array in a scalar variable:

  1. Type $scalar, where scalar is the name of the variable that will contain the length of the array.
  2. Type = (the equals sign).
  3. Type @array, where array is the name of the array whose length you want.

$elements = @array;
print "There are $elements in the array.\n";

foreach $item (@array) {
  print "$item\n";
}

The scalar() function

  1. Type scalar. (That's NOT a variable. You really have to type the word "scalar".)
  2. Type (@array), where array is the name of the array whose length you're interested in. The result of this expression is the length of the array.

$elements = scalar(@array);

$#

An array name prefaced with $# returns the index number of the last item in the array. You can add 1 to this to get the number of elements in an array.

$elements = $#array+1;

The following sample code and output demonstrates the three methods discussed above:

Sample CodeOutput
@planets = qw(mercury venus earth mars jupiter);

$a=@planets;
$b=scalar(@planets);
$c=$#planets+1;
$d=$#planets;

print "a = $a\n";
print "b = $b\n";
print "c = $c\n";
print "d = $d\n";
a = 5
b = 5
c = 5
d = 4

Finding the length of a hash

To determine the number of elements in a hash, use the keys() function to return the keys as a list, and then the scalara() fucntion to return how many keys there are:

my %planet_mass_compared_to_earth = (
    mercury => 0.055,
    venus   => 0.86,
    earth   => 1.0,
    mars    => 0.11,
    jupiter => 318,
);

my $size = scalar(keys %planet_mass_compared_to_earth);