How to get string length in Perl?

What is the Perl equivalent of strlen() ?

+50
string perl
Oct 21 '08 at 20:31
source share
5 answers
  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.
+73
Oct 21 '08 at 20:32
source share

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

Basically, the trick is to use the return value of the catch-all transliteration operator:

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

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

+43
Oct 22 '08 at 14:19
source share
 length($string) 
+34
Oct 22 '08 at 0:12
source share

length() function:

 $string ='String Name'; $size=length($string); 
0
Feb 26 '18 at 7:00
source share

You should not use this since length ($ string) is simpler and more readable, but in case someone comes across this, they also get the length of the string:

 my $length = map $_, $str =~ /(.)/gs; my $length = () = $str =~ /(.)/gs; my $length = split '', $str; 
0
Jul 11 '19 at 14:34
source share



All Articles