| Search perlmeme.org | |
| Home » Faqs » Perl variables » Length |
The length() function is used to determine the number of characters in an expression, such as a string or a scalar variable.
To determine the number of characters in an expression use the length() function:
#!/usr/bin/perl
use strict;
use warnings;
my $name = 'Bob';
my $size = length($name);
print "$size\n";
exit 0;
This example prints the number of characters in the string $name:
3
The Perl scalar() function forces an array into scalar context, giving you the length:
#!/usr/bin/perl
use strict;
use warnings;
my @planets = qw(mercury venus earth mars jupiter);
my $size = scalar(@planets);
print "$size\n";
exit 0;
This example shows us the number of elements in the array @planents:
5
Sometimes you will also want to know the number of elements in a hash. This is easily done using the keys() function to return the keys as an list, and the scalar() function to return how many keys there are:
#!/usr/bin/perl
use strict;
use warnings;
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);
print "$size\n";
exit 0;
The output of this program is:
5
Determining length and size
perldoc -f length
perldoc -f scalar
perldoc bytes