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 | |
by kcott (Archbishop) on May 14, 2013 at 04:11 UTC |