in reply to Parsing an Array of Hashes, Modifying Key/Value Pairs

G'day librarat,

"My goal is to iterate through the loaded hash and remove key/value pairs from each hash within the array where key names are listed in a pre-defined array."

I'd probably tackle that like this:

perl -Mstrict -Mwarnings -e ' use Data::Dumper; my @keeps = qw{a b}; my %to_keep = map { $_ => 1 } @keeps; my $data = { count => 5509, sms => [{a => 1, b => 2, c => 3, d=>4}, {b => 2, c => 3, e => +5}] }; print Dumper $data; for my $sms_ref (@{$data->{sms}}) { delete @$sms_ref{ grep { ! $to_keep{$_} } keys %$sms_ref }; } print Dumper $data; ' $VAR1 = { 'count' => 5509, 'sms' => [ { 'c' => 3, 'a' => 1, 'b' => 2, 'd' => 4 }, { 'e' => 5, 'c' => 3, 'b' => 2 } ] }; $VAR1 = { 'count' => 5509, 'sms' => [ { 'a' => 1, 'b' => 2 }, { 'b' => 2 } ] };

Update: Removed the exists from ... grep { ! exists $to_keep{$_} } .... It was redundant - see discussion below. Thanks ++LanX.

-- Ken

Replies are listed 'Best First'.
Re^2: Parsing an Array of Hashes, Modifying Key/Value Pairs
by LanX (Saint) on May 13, 2013 at 09:42 UTC
    G'day kcott,

    just wondering:

    my @keeps = qw{a b}; my %to_keep = map { $_ => 1 } @keeps; ... delete @$sms_ref{ grep { ! exists $to_keep{$_} } keys %$sms_re +f };
    using exists is a bit redundant if you already intialize the hash with true values...

    so either dropping the exists

    ... delete @$sms_ref{ grep { ! $to_keep{$_} } keys %$sms_ref };
    or initializing with undef
    my %to_keep; @to_keep{ qw{a b} } = (); ...

    should have the same effect.

    Or am I missing something?

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      Thanks for picking that up - I've updated my node. I suspect my intent, with including the exists, was to avoid autovivification; however, no autovivification occurs there anyway — I think it might have done long ago (Perl3/4?).

      -- Ken