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

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).


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.

Tags:

String

Perl