Kip
Kip

Reputation: 109413

How do I get the length of a string in Perl?

What is the Perl equivalent of strlen()?

Upvotes: 58

Views: 75433

Answers (5)

Paul Tomblin
Paul Tomblin

Reputation: 182792

length($string)

perldoc -f length

   length EXPR
   length  Returns the length in characters of the value of EXPR.  If EXPR is
           omitted, returns length of $_.  Note that this cannot be used on an
           entire array or hash to find out how many elements these have.  For
           that, use "scalar @array" and "scalar keys %hash" respectively.

           Note the characters: if the EXPR is in Unicode, you will get the num-
           ber of characters, not the number of bytes.  To get the length in
           bytes, use "do { use bytes; length(EXPR) }", see bytes.

Upvotes: 83

pslessard
pslessard

Reputation: 71

You shouldn't use this, since length($string) is simpler and more readable, but I came across some of these while looking through code and was confused, so in case anyone else does, these also get the length of a string:

my $length = map $_, $str =~ /(.)/gs;
my $length = () = $str =~ /(.)/gs;
my $length = split '', $str;

The first two work by using the global flag to match each character in the string, then using the returned list of matches in a scalar context to get the number of characters. The third works similarly by splitting on each character instead of regex-matching and using the resulting list in scalar context

Upvotes: 0

RANA DINESH
RANA DINESH

Reputation: 139

The length() function:

$string ='String Name';
$size=length($string);

Upvotes: 1

Yanick
Yanick

Reputation: 1280

Although 'length()' is the correct answer that should be used in any sane code, Abigail's length horror should be mentioned, if only for the sake of Perl lore.

Basically, the trick consists of using the return value of the catch-all transliteration operator:

print "foo" =~ y===c;   # prints 3

y///c replaces all characters with themselves (thanks to the complement option 'c'), and returns the number of character replaced (so, effectively, the length of the string).

Upvotes: 47

JDrago
JDrago

Reputation: 2099

length($string)

Upvotes: 41

Related Questions