¿Cómo obtengo la longitud de una cadena en Perl?


¿Cuál es el equivalente en Perl de strlen()?

 46
Author: brian d foy, 2008-10-22

4 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.
 71
Author: Paul Tomblin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-09 15:43:08

Aunque 'length()' es la respuesta correcta que debería ser usada en cualquier código cuerdo, El length horror de Abigail debería ser mencionado, aunque solo sea por el bien de la tradición de Perl.

Básicamente, el truco consiste en usar el valor de retorno del operador de transliteración catch-all:

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

Y///c reemplaza todos los caracteres con ellos mismos (gracias a la opción de complemento 'c'), y devuelve el número de caracteres reemplazados (por lo tanto, efectivamente, la longitud de la cadena).

 42
Author: Yanick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-13 00:26:46
length($string)
 28
Author: JDrago,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-22 00:12:38

La función length():

$string ='String Name';
$size=length($string);
 -2
Author: RANA DINESH,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-26 14:42:27