Perl length Function

The length function is used to return the number of bytes/characters in a string.

The length function returns the number of characters of a scalar string. You can’t use this function directly to find out the number of elements of an array or a hash because it expects as argument a scalar and it will force the array/hash into a scalar context.

The Perl length function has two syntax forms:

length EXPR
length
This function has one argument only – the string whose length we need to find. If you omit the argument, the Perl length function will return the length of the string stored in the special variable $_.

You can either omit the parentheses or not, sometimes it is healthy to put it in order to remove any ambiguity.

The length function returns the number of characters of a scalar string. See below a simple example:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
# define a string variable
my $strVar = "A simple example of a string variable";
 
# get the length of the string
my $strLength = length($strVar);
 
# print the length
print "Our string has $strLength characters\n";
# it prints: Our string has 37 characters

Please note that the Perl length function is for characters, so if you use a Unicode expression, it will return the number of characters and not the number of bytes.

However, you can get the length of a string in bytes as you can see in the next snippet code:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
# define a string variable
my $chars = "\x{2603}\x{2602}";
{
  use bytes;
  print "Length in bytes: ", length($chars), "\n";
}
print "Length in characters: ", length($chars), "\n";
In the above example:
  • the $chars string variable contains two Unicode characters: 2603 (which is a snowman) and 2602 (an umbrella) and I used hexadecimal escapes to represent them. A hexadecimal escape begins with \x and it is either followed by two digit hexadecimal number (for example "\x31" is "1") or a hexadecimal of arbitrary length included in curly braces (\x{2603})
  • I used bytes pragma to get the string length in bytes and I included it in a block in order to limit its effect to the scope of the block
  • I printed the length of the string both in bytes and in characters

If you run this code you’ll get the following output:

Length in bytes: 6
Length in characters: 2
 

The following example will show you how to use the length function in connection with arrays and the sort function. We want to sort the words of a string in a descending length order and next print it.

See the code for more details:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
# create and initialize a string
my $str = "Here are a few Perl functions";
 
# split the string in an array
my @array = split(' ',$str);
 
# sort the array by descending value length
@array = sort { length $b cmp length $a } @array;
 
# convert back the array to string
$str = join ' ', @array;
 
# print the string
print "$str\n";
You can rewrite the above code without using an array variable explicitly:
 
$str = join ' ', sort { length $b cmp length $a }
       split(' ',$str);
Output:
 
functions Here Perl are few a
 

In the following example I’ll show you how to loop through the characters of a string using the Perl length and substr functions.

Because in Perl strings are a basic data type, to access the individual characters or a portion of a string you must use functions like substr or unpack.

#!/usr/bin/perl
 
use warnings;
use strict;
 
my $str = 'This is about the Perl language';
 
foreach (0 .. length ($str) - 1) {
  # get the current character
  next unless $_ % 2;
  my $c = substr $str, $_, 1;
 
  # do something with the character
  substr($str, $_, 1) = '--' if $c eq ' ';
}
 
print "$str\n";
To iterate through the characters of the string the foreach loop was used. At each iteration step:
 
  • the position of the character in the string is assigned in turn to $_
  • if the value stored in $_ is even, the next loop control will skip to the next iteration
  • the current character is stored in the $c scalar variable
  • if the value of the $c variable is equal with blank, the correspondent value in the string will be replaced by '--'. To do this an one-line if statement and the substr function are used. The substr function is used as a lvalue, allowing us to modify the value of $str.

The output is as follows:

This is--about the Perl—language
 

You can use the Perl length function to find the string length of the shortest and longest string in an array.

See the following code snippet:

#!/usr/bin/perl
 
use warnings;
use strict;
 
my @array = qw( January February March April May June );
my ( $minStrLength,  $maxStrLength ) = (length $array[0], length $array[0]);
 
foreach (@array){
  $minStrLength = length if $minStrLength > length;
  $maxStrLength = length if $maxStrLength < length;
}
 
print "MinLength = $minStrLength, MaxLength = $maxStrLength \n";
First the array is populated with a few strings (the first sixth months of the year). The $minStrLength  and $maxStrLength scalar variables are initialized with the length of the first element of the array. 

The foreach loop is used to cycle through the elements of the array. At each iteration step:

  • the current element of the array is assigned to the $_ special variable
  • the  $minStrLength variable is initialized with the length of $_ if this length is less than $minStrLength. Please note the using of the one-line if statement. The length function is used without arguments and that means it acts against the $_ special variable.
  • the  $maxStrLength variable is initialized with the length of $_ if this length is greater than $maxStrLength.

Finally, the values of both variables are printed. You’ll get the following output:

MinLength = 3, MaxLength = 8

The length function returns the number of characters of an expression.

The following example shows you a way to find the length in characters of an array, by using the Perl length function in a foreach loop.

See the code:

#!/usr/bin/perl
 
use warnings;
use strict;
 
my @array = qw(one two three four five six seven);
my $count;
 
foreach my $i (@array){
  $count += length($i);
}
 
print "The length of the array is: $count\n";
The output is as follows:
 
The length of the array is: 27
 
As you can see, we don’t need to initialize the $count variable with 0, by default Perl assigns to this variable the undef value. In numeric operations this value is converted in 0.

Or you can use an one-line foreach loop by replacing the above foreach block with the following line of code:

$count += length foreach(@array);
Here the length function is used against the $_ special variable. The foreach loop steps through the elements of the array and at each iteration step stores the current element in $_.

The $count scalar variable will be incremented with the number returned by the length function.