TIMTOWTDI!

But instead of reinventing the wheel, there is a pairgrep and pairmap in (newer°) List::Util, which is core

debugger-demo (via perl -de0 )

DB<10> @h{1..26} = a..z DB<11> use List::Util qw/pairgrep/ DB<12> x pairgrep { $b =~ /[aeiou]/ } %h 0 15 1 'o' 2 21 3 'u' 4 9 5 'i' 6 5 7 'e' 8 1 9 'a' DB<13> use List::Util qw/pairmap/ DB<14> x pairmap { $b =~ /[aeiou]/ ? [$a => $b] : () } %h 0 ARRAY(0x349eed8) 0 15 1 'o' 1 ARRAY(0x349ef20) 0 21 1 'u' 2 ARRAY(0x349ef80) 0 9 1 'i' 3 ARRAY(0x349efe0) 0 5 1 'e' 4 ARRAY(0x349f040) 0 1 1 'a' DB<15>

update

Perl doesn't have datatype for pairs, but you could use a second hash for shorter syntax :)

DB<15> %h2 = pairgrep { $b =~ /[aeiou]/ } %h DB<16> x \%h2 0 HASH(0x349ee60) 1 => 'a' 15 => 'o' 21 => 'u' 5 => 'e' 9 => 'i' DB<17>

update

°) came into core with 5.20.0 i.e. since May 27, 2014. So only new for oldies like me ;-)

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery


In reply to Re: How to grep for values & see the keys? by LanX
in thread How to grep for values & see the keys? by misterperl

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.