# 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

edit

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 }

update

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)


In reply to Re: Parsing an Array of Hashes, Modifying Key/Value Pairs by LanX
in thread Parsing an Array of Hashes, Modifying Key/Value Pairs by librarat

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.