Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

perl

What is the Perl equivalent of strlen()?

like image 753
Kip Avatar asked Oct 21 '08 20:10

Kip


People also ask

How do you check the length of a string?

As you know, the best way to find the length of a string is by using the strlen() function.

How do I print a string in Perl?

print 'this is \n', "\n"; In a single quoted string the only characters that must be escaped are single quotes and a backslash that occurs immediately before the end of the string (i.e. 'foo\\' ). print 'foo is $foo', "\n"; Will not print the contents of $foo .

How do I find the length of an array in Perl?

Note: In Perl arrays, the size of an array is always equal to (maximum_index + 1) i.e. And you can find the maximum index of array by using $#array. So @array and scalar @array is always used to find the size of an array.


2 Answers

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.
like image 171
Paul Tomblin Avatar answered Sep 28 '22 01:09

Paul Tomblin


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

like image 24
Yanick Avatar answered Sep 28 '22 01:09

Yanick