Tweet

How do I determine the length of something?

Introduction

The length() function is used to determine the number of characters in an expression, such as a string or a scalar variable.

Example 1. Characters in an expression

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

Example 2. Number of elements in an array

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

Example 3. Number of elements in a hash

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

See also

    Determining length and size
    perldoc -f length
    perldoc -f scalar
    perldoc bytes
Revision: 1.2 [Top]