in reply to Parsing an Array of Hashes, Modifying Key/Value Pairs
# If your $key is *not* what we're looking for, remove i +t from the hash if ( !grep ($key, @keysToKeep) )
well what you want something like Python's in operator, but the Perl way to check inclusion within a set is to use hashes.
so if ($keysToKeep{$key}) would do it most efficiently.
There is a new smart-match operator ~~ for in, but thats still somehow experimental
DB<137> 1 ~~ [1,2,3] => 1 DB<138> "a" ~~ [1,2,3] => "" DB<139> "4" ~~ [1,2,3] => "" DB<140> "2" ~~ [1,2,3] => 1
Anyway using a hash-slice is the fastest way to filter keys:
DB<145> %h=(a=>1,b=>2,c=>3) => ("a", 1, "b", 2, "c", 3) DB<146> @keysToDelete=qw/b c d/ => ("b", "c", "d") DB<147> delete @h{@keysToDelete} => (2, 3, undef) DB<148> \%h => { a => 1 }
or
DB<153> %h=(a=>1,b=>2,c=>3) => ("a", 1, "b", 2, "c", 3) DB<154> @keysToKeep=qw/a e/ => ("a", "e") DB<155> %h2=() DB<156> @h2{@keysToKeep}=@h{@keysToKeep} => (1, undef) DB<157> \%h2 => { a => 1, e => undef }
but please notice how key "e" jumped into existence now, which is no problem if you use a guarantied subset.
Cheers Rolf
( addicted to the Perl Programming Language)
|
|---|