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

后端 未结 11 705
猫巷女王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:19

    Just use join():

    # assuming @array is your array:
    print join(", ", @array);
    
    0 讨论(0)
  • 2021-01-30 10:22

    Using 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)]);
    

    Generates three different output styles:

    $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 讨论(0)
  • 2021-01-30 10:23

    This might not be what you're looking for, but here's something I did for an assignment:

    $" = ", ";
    print "@ArrayName\n";
    
    0 讨论(0)
  • 2021-01-30 10:25

    I've not tried to run below, though. I think this's a tricky way.

    map{print $_;} @array;
    
    0 讨论(0)
  • 2021-01-30 10:29

    Also, you may want to try Data::Dumper. Example:

    use Data::Dumper;
    
    # simple procedural interface
    print Dumper($foo, $bar);
    
    0 讨论(0)
  • 2021-01-30 10:31
    # better than Dumper --you're ready for the WWW....
    
    use JSON::XS;
    print encode_json \@some_array
    
    0 讨论(0)
提交回复
热议问题