| Prev | Perl Notes |
Next |
To store the length of an array in a scalar variable:
$elements = @array;
print "There are $elements in the array.\n";
foreach $item (@array) {
print "$item\n";
}
$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 Code | Output |
|---|---|
|
@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 |
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);