Perl Newbies

  1. Perl
  2. Functions
  3. here

length function - Get string length

length function returns the length of a string.

$ret = length $str;

For example, the length of the string “abcde” is 5.

# The string length is 5
my $length = length 'abcde';

Get the correct length of mulitibyte string such as Japanese

The length function returns the length of the string, but you should remember a one thing to get the correct length of multibyte string such as Japanese.

You need to use length function to a decoded string. A decoded string means a string decoded by decode function of Encode module.

See also the following article to know decoded strings.

The following example is using decode function of Encode module.

For multibyte characters such as Japanese, use the encode function's decode function to convert it to an decoded string, and then use length function to obtain the correct result. The same concept applies when processing full-width Japanese.

use strict;
use warnings;

use Encode 'decode';

# Get UTF-8 encoded string from argument
my $bytes = shift;

# Get string length
my $string = decode('UTF-8', $bytes);
my $length = length $string;

length function don't return the length of a array

Note that Perl's length function is not a function that gets the length of a array.

To get the length of an array, the array must be evaluated in scalar context.

# The length of a array
my $count = @nums;

See also the following article to know scalar context.

length function in Perl less than 5.10 print warnings when an undefined value is passed

length function in Perl less than 5.10 print warnings when an undefined value is passed.

If you want to write length function in more general-purpose module, you should write the following.

my $has_length = defined $foo && length $foo;

Make sure that the string must be defined before passing it to length function.

On the other hand, if it is Perl 5.12 or higher, length function don't print warnings when an undefined value is passed.

my $has_length = length $foo;

If you are using the latest Perl in a business application, it is good to write the above.

length function programing example

The following is a programing example to get the length of a string using length function.

# Get string length
my $message = "I like peace";
my $length = length $message;
Menu