Perl: Delete keys in hash that don't exist as elements in array -
i have array of key names , need remove keys not in list hash.
i gather deleting keys in hash bad thing while iterating on it, seem work:
use strict; use warnings; use data::dumper; @array=('item1', 'item3'); %hash=(item1 => 'test 1', item2 => 'test 2', items3 => 'test 3', item4 => 'test 4'); print(dumper(\%hash)); foreach (keys %hash) { delete $hash{$_} unless $_ ~~ @array; } print(dumper(\%hash));
gives output:
$var1 = { 'item3' => 'test 3', 'item1' => 'test 1', 'item2' => 'test 2', 'item4' => 'test 4' }; $var1 = { 'item3' => 'test 3', 'item1' => 'test 1' };
can explain me better/cleaner/safer way of doing this?
many thanks.
don't use smartmatch ~~
, it's fundamentally broken , removed or substantially changed in upcoming releases of perl.
the easiest solution build new hash containing elements you're interested in:
my %old_hash = ( item1 => 'test 1', item2 => 'test 2', item3 => 'test 3', item4 => 'test 4', ); @keys = qw/item1 item3/; %new_hash; @new_hash{@keys} = @old_hash{@keys}; # uses "hash slice"
if want update original hash, %old_hash = %new_hash
afterwards. if don't want use hash, might use list::moreutils qw/zip/
:
# unfortunately, "zip" uses idiotic "prototype", override # calling "&zip(...)" %hash = &zip(\@keys, [@hash{@keys}]);
which has same effect.
Comments
Post a Comment