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

PerlHashPrinting

Perl Problem Overview


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 example, a one-liner would be best).

Perl Solutions


Solution 1 - Perl

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
        };

Solution 2 - Perl

Easy:

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

Elegant, but actually 30% slower (!):

while (my ($k,$v)=each %h){print "$k $v\n"}

Solution 3 - Perl

Here how you can print without using Data::Dumper

print "@{[%hash]}";

Solution 4 - Perl

For debugging purposes I will often use YAML.

use strict;
use warnings;

use YAML;

my %variable = ('abc' => 123, 'def' => [4,5,6]);

print "# %variable\n", Dump \%variable;

Results in:

# %variable
---
abc: 123
def:
  - 4
  - 5
  - 6

Other times I will use Data::Dump. You don't need to set as many variables to get it to output it in a nice format than you do for Data::Dumper.

use Data::Dump = 'dump';

print dump(\%variable), "\n";

{ abc => 123, def => [4, 5, 6] }

More recently I have been using Data::Printer for debugging.

use Data::Printer;
p %variable;

{
    abc   123,
    def   [
        [0] 4,
        [1] 5,
        [2] 6
    ]
}

( Result can be much more colorful on a terminal )

Unlike the other examples I have shown here, this one is designed explicitly to be for display purposes only. Which shows up more easily if you dump out the structure of a tied variable or that of an object.

use strict;
use warnings;

use MTie::Hash;
use Data::Printer;

my $h = tie my %h, "Tie::StdHash";
@h{'a'..'d'}='A'..'D';
p %h;
print "\n";
p $h;

{
    a   "A",
    b   "B",
    c   "C",
    d   "D"
} (tied to Tie::StdHash)

Tie::StdHash  {
    public methods (9) : CLEAR, DELETE, EXISTS, FETCH, FIRSTKEY, NEXTKEY, SCALAR, STORE, TIEHASH
    private methods (0)
    internals: {
        a   "A",
        b   "B",
        c   "C",
        d   "D"
    }
}

Solution 5 - Perl

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:

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.

Solution 6 - Perl

My favorite: Smart::Comments

use Smart::Comments;
# ...

### %hash

That's it.

Solution 7 - Perl

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.

Solution 8 - Perl

The easiest way in my experiences is to just use Dumpvalue.

use Dumpvalue;
...
my %hash = { key => "value", foo => "bar" };
my $dumper = new DumpValue();
$dumper->dumpValue(\%hash);

Works like a charm and you don't have to worry about formatting the hash, as it outputs it like the Perl debugger does (great for debugging). Plus, Dumpvalue is included with the stock set of Perl modules, so you don't have to mess with CPAN if you're behind some kind of draconian proxy (like I am at work).

Solution 9 - Perl

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

Solution 10 - Perl

I append one space for every element of the hash to see it well:

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

Solution 11 - Perl

I really like to sort the keys in one liner code:

print "$_ => $my_hash{$_}\n" for (sort keys %my_hash);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKysView Question on Stackoverflow
Solution 1 - PerltetrominoView Answer on Stackoverflow
Solution 2 - PerlJonathan GraehlView Answer on Stackoverflow
Solution 3 - Perluser966588View Answer on Stackoverflow
Solution 4 - PerlBrad GilbertView Answer on Stackoverflow
Solution 5 - PerlChas. OwensView Answer on Stackoverflow
Solution 6 - PerlAxemanView Answer on Stackoverflow
Solution 7 - PerlPaul NathanView Answer on Stackoverflow
Solution 8 - PerlWeegeeView Answer on Stackoverflow
Solution 9 - PerlKyle WalshView Answer on Stackoverflow
Solution 10 - Perlcarlos_lmView Answer on Stackoverflow
Solution 11 - PerllabistView Answer on Stackoverflow