What is the Perl equivalent of strlen()
?
views:
922answers:
3
+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
2008-10-21 20:32:52
Thanks! Easy rep for you! :)
Kip
2008-10-21 20:43:12
Just call me "Quick Draw".
Paul Tomblin
2008-10-21 20:43:50
+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
2008-10-22 14:19:45
y's counting modes don't actually modify the string, so they will work fine even on readonly values.
ysth
2008-10-24 05:49:02