views:

922

answers:

3

What is the Perl equivalent of strlen()?

+26  A: 
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.
Paul Tomblin
Thanks! Easy rep for you! :)
Kip
Just call me "Quick Draw".
Paul Tomblin
+4  A: 
length($string)
JDrago
+6  A: 

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

Yanick
Oh, that's lovely. Horrible, but lovely.
Paul Tomblin
y's counting modes don't actually modify the string, so they will work fine even on readonly values.
ysth
This is awesome in a terrible way.
Chris Lutz