¿Una forma fácil de imprimir Perl array? (con un poco de formato)


¿Existe una manera fácil de imprimir un array Perl con comas entre cada elemento?

Escribir un bucle for para hacerlo es bastante fácil, pero no del todo elegante....si eso tiene sentido.

 91
Author: codeforester, 2011-04-21

11 answers

Solo use join():

# assuming @array is your array:
print join(", ", @array);
 139
Author: Alex,
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
2011-04-21 07:52:28

Puede utilizar Data::Dump:

use Data::Dump qw(dump);
my @a = (1, [2, 3], {4 => 5});
dump(@a);

Produce:

"(1, [2, 3], { 4 => 5 })"
 28
Author: Eugene Yarmash,
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
2011-04-21 08:24:55

Si estás codificando para el tipo de claridad que entendería alguien que está empezando con Perl, la construcción tradicional this dice lo que significa, con un alto grado de claridad y legibilidad:{[13]]}

$string = join ', ', @array;
print "$string\n";

Esta construcción está documentada en perldoc -fjoin.

Sin embargo, siempre me ha gustado lo simple que es $,. La variable especial $" es para interpolación, y la variable especial $, es para listas. Combine uno con dinámico alcance-restringir 'local ' para evitar tener efectos dominó a lo largo del script:

use 5.012_002;
use strict;
use warnings;

my @array = qw/ 1 2 3 4 5 /;

{
    local $" = ', ';
    print "@array\n"; # Interpolation.
}

O con $,:

use feature q(say);
use strict;
use warnings;

my @array = qw/ 1 2 3 4 5 /;
{
    local $, = ', ';
    say @array; # List
}

Las variables especiales $, y $" están documentadas en perlvar. La palabra clave local, y cómo se puede usar para limitar los efectos de alterar el valor de una variable de puntuación global, probablemente se describe mejor en perlsub.

Disfrute!

 19
Author: DavidO,
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
2016-10-07 21:19:15

También, es posible que desee probar Data::Dumper. Ejemplo:

use Data::Dumper;

# simple procedural interface
print Dumper($foo, $bar);
 9
Author: Andreas,
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
2017-08-14 01:32:57

Para la inspección/la depuración compruebe el Data::Printer módulo. Está destinado a hacer una cosa y solo una cosa:

Mostrar las variables y objetos de Perl en la pantalla, con el formato adecuado (para ser inspeccionado por un humano)

Ejemplo de uso:

use Data::Printer;  
p @array;  # no need to pass references

El código anterior podría generar algo como esto (¡con colores!):

   [
       [0] "a",
       [1] "b",
       [2] undef,
       [3] "c",
   ]
 6
Author: Eugene Yarmash,
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
2013-06-18 15:15:41

Puedes simplemente print.

@a = qw(abc def hij);

print "@a";

Tendrás:

abc def hij
 2
Author: Yi Zhao,
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
2011-04-21 10:08:19
# better than Dumper --you're ready for the WWW....

use JSON::XS;
print encode_json \@some_array
 2
Author: gleeco,
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
2013-02-26 07:43:30

Usando Data::Dumper:

use strict;
use Data::Dumper;

my $GRANTstr = 'SELECT, INSERT, UPDATE, DELETE, LOCK TABLES, EXECUTE, TRIGGER';
$GRANTstr    =~ s/, /,/g;
my @GRANTs   = split /,/ , $GRANTstr;

print Dumper(@GRANTs) . "===\n\n";

print Dumper(\@GRANTs) . "===\n\n";

print Data::Dumper->Dump([\@GRANTs], [qw(GRANTs)]);

Genera tres estilos de salida diferentes:

$VAR1 = 'SELECT';
$VAR2 = 'INSERT';
$VAR3 = 'UPDATE';
$VAR4 = 'DELETE';
$VAR5 = 'LOCK TABLES';
$VAR6 = 'EXECUTE';
$VAR7 = 'TRIGGER';
===

$VAR1 = [
          'SELECT',
          'INSERT',
          'UPDATE',
          'DELETE',
          'LOCK TABLES',
          'EXECUTE',
          'TRIGGER'
        ];
===

$GRANTs = [
            'SELECT',
            'INSERT',
            'UPDATE',
            'DELETE',
            'LOCK TABLES',
            'EXECUTE',
            'TRIGGER'
          ];
 0
Author: TVNshack,
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
2016-03-25 13:47:55

Esto podría no ser lo que estás buscando, pero aquí hay algo que hice para una tarea:

$" = ", ";
print "@ArrayName\n";
 0
Author: 009,
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
2016-07-22 18:19:48

El mapa también se puede usar, pero a veces es difícil de leer cuando hay muchas cosas que están sucediendo.

map{ print "element $_\n" }   @array; 
 0
Author: PodTech.io,
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
2017-06-22 10:10:46

No he intentado correr por debajo, sin embargo. Creo que esta es una manera difícil.

map{print $_;} @array;
 0
Author: K.Minoda,
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
2017-10-28 07:58:51