How can I print the contents of a hash in Perl?

前端 未结 11 1429
借酒劲吻你
借酒劲吻你 2020-12-22 15:52

I keep printing my hash as # of buckets / # allocated. How do I print the contents of my hash?

Without using a while loop would be most preferable (for

相关标签:
11条回答
  • 2020-12-22 16:21

    Looping:

    foreach(keys %my_hash) { print "$_ / $my_hash{$_}\n"; }
    

    Functional

    map {print "$_ / $my_hash{$_}\n"; } keys %my_hash;
    

    But for sheer elegance, I'd have to choose wrang-wrang's. For my own code, I'd choose my foreach. Or tetro's Dumper use.

    0 讨论(0)
  • 2020-12-22 16:29

    If you want to be pedantic and keep it to one line (without use statements and shebang), then I'll sort of piggy back off of tetromino's answer and suggest:

    print Dumper( { 'abc' => 123, 'def' => [4,5,6] } );
    

    Not doing anything special other than using the anonymous hash to skip the temp variable ;)

    0 讨论(0)
  • 2020-12-22 16:31

    The answer depends on what is in your hash. If you have a simple hash a simple

    print map { "$_ $h{$_}\n" } keys %h;
    

    or

    print "$_ $h{$_}\n" for keys %h;
    

    will do, but if you have a hash that is populated with references you will something that can walk those references and produce a sensible output. This walking of the references is normally called serialization. There are many modules that implement different styles, some of the more popular ones are:

    • Data::Dumper
    • Data::Dump::Streamer
    • YAML::XS
    • JSON::XS
    • XML::Dumper

    Due to the fact that Data::Dumper is part of the core Perl library, it is probably the most popular; however, some of the other modules have very good things to offer.

    0 讨论(0)
  • 2020-12-22 16:37

    Data::Dumper is your friend.

    use Data::Dumper;
    my %hash = ('abc' => 123, 'def' => [4,5,6]);
    print Dumper(\%hash);
    

    will output

    $VAR1 = {
              'def' => [
                         4,
                         5,
                         6
                       ],
              'abc' => 123
            };
    
    0 讨论(0)
  • 2020-12-22 16:37

    Easy:

    print "$_ $h{$_}\n" for (keys %h);
    

    Elegant, but actually 30% slower (!):

    while (my ($k,$v)=each %h){print "$k $v\n"}
    
    0 讨论(0)
提交回复
热议问题