The Perl String Length() Function

How to Use the String Length() Function

Working on a laptop
Ragip Candan/E+/Getty Images

Perl is a programming language used primarily to develop web applications. Perl is an interpreted, not compiled, language, so its programs take up more CPU time than a compiled language—a problem that becomes less important as the speed of processors increases. Writing in Perl is faster than writing in a compiled language, so the time you save is yours. When you learn Perl, you learn how to work with the language's functions.

One of the most basic is the string length() function.

The Length of Strings

Perl's length() function returns the length of a Perl string in characters. Here is an example showing its basic usage.

#!/usr/bin/perl ​

$orig_string = "This is a Test and ALL CAPS";
$string_len =  length( $orig_string );

print "Length of the String is : $string_len\n";

When this code is executed, it displays the following:

Length of the String is: 27

The number "27" is the total of the characters, including spaces, in the phrase "This is a Test and ALL CAPS".

Note that this function does not count the size of the string in bytes—just the length in characters.

What About the Length of Arrays?

The length() function works only on strings, not on arrays. An array stores an ordered list and is preceded by an @ sign and populated using parentheses. To find out the length of an array, use the scalar function. For example:

my @many_strings = ("one", "two", "three", "four", "hi", "hello world");

say scalar @many_strings;  

The response is "6"—the number of items in the array.

A scalar is a single unit of data. It might be a group of characters, as in the example above, or a single character, string, floating point or integer number.