1. Perl
  2. builtin functions
  3. here

length function - get the length of a string

You can use the length function to get the length of string.

$ret = length $str;

For example, the string "abcde" has a length of 5.

# String length is 5
my $length = length'abcde';

Get the correct length of a Japanese string

The length function returns the length of a string, but there is one thing to remember in order to get the correct length of a Japanese string.

That is, you need to use the length function on the decoded string. The decoded string is the string decoded by the decode function of the Encode module.

For the decoded string, refer to the following article.

Below is an example program.

For multibyte characters such as Japanese, convert them to decoded strings with the Encode module's decode function and then use the length function to get the correct results. The same idea applies when processing full-width Japanese.

use strict;
use warnings;

use Encode 'decode';

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

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

length cannot get the length of the array

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

To get the length of the array, you need to evaluate the array in scalar context. For example:

# Number of arrays
my $count = @nums;

For a detailed explanation of the scalar context, see the following articles.

length less than Perl 5.10 raises a warning when passing an undefined value

Lengths less than Perl 5.10 will warn you when you pass an undefined value. So, if you want to write length in a general-purpose module, write as follows and the warning will not appear.

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

Make sure it is defined before passing it to the length function.

On the other hand, if it is Perl 5.12 or higher, it means that it is defined and has a length, so it can be multiplied by one length function.

my $has_length = length $foo;

If you're using the latest Perl in your business application, it's simple to write as above.

Example program

This is an example to get the length of a string using the length function.

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

Related Informatrion