The Perl String Length Function

String Length Returns the Length of a Perl String in Characters

Desk with two screens and two smart phones.

Tranmautritam/Pexels

Perl is a programming language used primarily to develop web applications. Perl is an interpreted, not compiled, language. This means its programs take up more CPU time than a compiled language — a problem that becomes less important as the speed of processors increases. Writing code 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.

How to Find Length of a String in Perl

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.

Format
mla apa chicago
Your Citation
Brown, Kirk. "The Perl String Length Function." ThoughtCo, Aug. 28, 2020, thoughtco.com/perl-string-length-function-quick-tutorial-2641189. Brown, Kirk. (2020, August 28). The Perl String Length Function. Retrieved from https://www.thoughtco.com/perl-string-length-function-quick-tutorial-2641189 Brown, Kirk. "The Perl String Length Function." ThoughtCo. https://www.thoughtco.com/perl-string-length-function-quick-tutorial-2641189 (accessed March 28, 2024).