Easy way to print Perl array? (with a little formatting)

后端 未结 11 706
猫巷女王i
猫巷女王i 2021-01-30 10:13

Is there an easy way to print out a Perl array with commas in between each element?

Writing a for loop to do it is pretty easy but not quite elegant....

相关标签:
11条回答
  • 2021-01-30 10:31

    Map can also be used, but sometimes hard to read when you have lots of things going on.

    map{ print "element $_\n" }   @array; 
    
    0 讨论(0)
  • You can use Data::Dump:

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

    Produces:

    "(1, [2, 3], { 4 => 5 })"
    
    0 讨论(0)
  • 2021-01-30 10:40

    You can simply print it.

    @a = qw(abc def hij);
    
    print "@a";
    

    You will got:

    abc def hij
    
    0 讨论(0)
  • 2021-01-30 10:45

    If you're coding for the kind of clarity that would be understood by someone who is just starting out with Perl, the traditional this construct says what it means, with a high degree of clarity and legibility:

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

    This construct is documented in perldoc -fjoin.

    However, I've always liked how simple $, makes it. The special variable $" is for interpolation, and the special variable $, is for lists. Combine either one with dynamic scope-constraining 'local' to avoid having ripple effects throughout the script:

    use 5.012_002;
    use strict;
    use warnings;
    
    my @array = qw/ 1 2 3 4 5 /;
    
    {
        local $" = ', ';
        print "@array\n"; # Interpolation.
    }
    

    OR with $,:

    use feature q(say);
    use strict;
    use warnings;
    
    my @array = qw/ 1 2 3 4 5 /;
    {
        local $, = ', ';
        say @array; # List
    }
    

    The special variables $, and $" are documented in perlvar. The local keyword, and how it can be used to constrain the effects of altering a global punctuation variable's value is probably best described in perlsub.

    Enjoy!

    0 讨论(0)
  • 2021-01-30 10:45

    For inspection/debugging check the Data::Printer module. It is meant to do one thing and one thing only:

    display Perl variables and objects on screen, properly formatted (to be inspected by a human)

    Example usage:

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

    The code above might output something like this (with colors!):

       [
           [0] "a",
           [1] "b",
           [2] undef,
           [3] "c",
       ]
    
    0 讨论(0)
提交回复
热议问题