MrSnrub has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks. If I use
print Dumper(\%myhash);
...it prints a hash with about 20 key/value pairs. Is there a way I can tell it to only print key-value pairs for one or two or three specific fields?

Replies are listed 'Best First'.
Re: Output only certain fields from a hash using the Data::Dumper
by choroba (Cardinal) on Jan 07, 2015 at 12:16 UTC
    In recent Perl, you can use the new hash slice syntax:
    print Dumper { %hash {qw{ a b c }} };

    In older Perls, you have to use a loop (or disguise it as map):

    print Dumper { map { $_, $hash{$_} } qw( a b c ) };
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      That "older Perls" method worked well for basic hashes. But what if I have a hash of arrays of hashes? Can I filter out the keys in the inner hash?
Re: Output only certain fields from a hash using the Data::Dumper
by Athanasius (Archbishop) on Jan 07, 2015 at 13:09 UTC

    Hello MrSnrub,

    If you want the output sorted as well as filtered, you can set $Data::Dumper::Sortkeys to do both together:

    #! perl use strict; use warnings; use Data::Dumper; my %hash = (Fred => 'Wilma', Barney => 'Betty', Homer => 'Marge'); $Data::Dumper::Sortkeys = sub { [ sort grep { /^Fred|Barney$/ } keys % +{$_[0]} ] }; print Dumper \%hash;

    Output:

    23:01 >perl 1116_SoPW.pl $VAR1 = { 'Barney' => 'Betty', 'Fred' => 'Wilma' }; 23:01 >

    (See “sorting and filtering hash keys” in Data::Dumper#EXAMPLES.) Otherwise, choroba’s approach is clearly superior.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: Output only certain fields from a hash using the Data::Dumper ( different hash, a subroutine)
by Anonymous Monk on Jan 07, 2015 at 22:42 UTC
    Yeah, make a different hash
    RoShamBoDump( \%myhash ); sub RoShamBoDump { my $orig = shift; my @keys = qw/ ro sham bo /; my %new; @new{ @keys } = @{ $orig }{ @keys }; use Data::Dumper; print Data::Dumper->new([\%new])->Useqq(1)->Dump, "\n"; }