Perl length Function

These sites are FOR SALE:,!
If you are interested, please use my Contact page.

The Perl length function returns the number of characters of a 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.

See Perl Arrays Size or Perl Arrays Length for more details about the size or the length of an array.

But I anticipated a bit, for this function two syntax forms are available:

length EXPR

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

You can either omit the parentheses or not, sometimes it is healthy to put them in order to remove any ambiguity. In the below code sample we’ll show you how to use it.

Example 1.

# 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

Click Below to See the Best

Perl How-to Snippet Collection

and Save Hours of Surfing on Internet!

Example 2.

Please note that 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 use the Perl length function to get the length of a string in bytes as you can see in the next code snippet:

# 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 string variable $chars 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 we run this code we get the following output:

Length in bytes: 6
Length in characters: 2

Example 3.

I’ll show you next a short code sample that reads some lines of text from STDIN. We use the Perl length function to find the shortest and the longest string line:

my $minStrLength = "";
my $maxStrLength = "";
  if($minStrLength eq "")
    $minStrLength = $maxStrLength = $_;    
  if(length $_ < length $minStrLength)
    $minStrLength = $_; 
  if(length $_ > length $maxStrLength)
    $maxStrLength = $_; 

print "Str min: $minStrLength\n";
print "Str max: $maxStrLength\n";

We read the string lines from STDIN and we chomp off each line because the trailing newlines are also included in the length calculation. We store the shortest string line in the $minStrLength variable and the longest one in $maxStrLength variable. We don’t use any variable for the while loop, so the lines from STDIN will be stored in the special variable $_, which we use for comparisons. Finally, we print the wanted strings. See the code, copy and test it if you want.

Example 4.

The last example will show you how to use the Perl length function in connection with arrays and 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:

# 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";

The above code will produce the following result:

functions Here Perl are few a

Please click here to download the Perl length script with all the above examples included.


Through these exercises you have the opportunity to try yourself to write some script code where you can use the Perl length function. These exercises are completely covered in my Perl "Perl Scalar and String Functions - How To Tutorial" where I show you how to play with this important function in detail.
1. Write a few lines of code where to show how to process a string one character at a time, using the length and substr functions.
2. Initialize an array with a few strings. Find the length of the shortest and longest string in this array.
3. You have an array whose elements are strings of characters. Find the length in characters of this array (the sum of all the strings length of the array).
4. Let’s populate an array with a few strings:
my @names = qw(Minie Nona Ashley Ashlie Milly Belynda 
               Sheena Bernice Shania Sparrow Kris);
Sort the array ordered ascending after the length of the strings. Print the strings grouped 5 on a line. The output must be:
	Kris    Nona    Milly   Minie   Ashley
	Ashlie  Shania  Sheena  Belynda Bernice
5. The same exercise as before, but you have to sort the elements of a hash by the length of the values. Here is the hash declaration:
my %names = qw(m1 Minie n1 Nona a1 Ashley a2 Ashlie 
               		m2 Milly b1 Belynda s1 Sheena b2 Bernice 
              		s2 Shania s3 Sparrow k1 Kris);
Next, sort the elements of a hash by the length of keys. Use the following initialization for the hash:
my %hash = (if => 1, until => 1, foreach =>1, else => 1);
6. Find the length of an array of arrays(the sum of all the strings length of the array) for the following array of arrays:
my @AOA = (["blue", "red", "green"],
      ["lightgreen", "lightblue"]);
7. Find the length in bytes of all the hash values (which are not references) for the following hash of hashes:
my %HOH = (
      item1 => { color => 'red',    shape => 'round' },
      item2 => { color => 'yellow', shape => 'rectangle' },
      item3 => { color => 'blu',    shape => 'square' });

A-N-Y-O-N-E Can Learn and Master Perl!
And That Includes YOU!

Check these how-to tutorial eBooks (PDF format):

Table of Contents:

A Perl Script
Install Perl
Running Perl
Perl Data Types
Perl Variables
Perl Operators
Perl Lists
Perl Arrays
    Array Size
    Array Length
Perl Hashes
Perl Statements
    Perl if
    Perl unless
    Perl switch
    Perl while
    Perl do-while
    Perl until
    Perl do-until
    Perl for
    Perl foreach
Built-in Perl Functions
    Functions by Category
        String Functions
        Regular Expressions and Pattern Matching
        List Functions
        Array Functions
        Hash Functions
        Miscellaneous Functions
    Functions in alphabetical order
        length (more)

return from Perl length Function to Perl Basics

Would you like to create your own website like this one?
Hit the Alarm Clock!

Site Build It!