in reply to How to grep for values & see the keys?

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

Replies are listed 'Best First'.
Re^2: How to grep for values & see the keys?
by kcott (Archbishop) on May 14, 2022 at 02:25 UTC

        I was aware that 1.xx referred to module versions. I wasn't aware that the version number was displayed in Perldoc: good to know; thanks for enlightening me.

        — Ken

Re^2: How to grep for values & see the keys?
by misterperl (Friar) on May 13, 2022 at 14:18 UTC
    Rolf as the song goes- YOU ARE SIMPLY THE BEST.. Whenever I see your name in a reply, I rejoice!

    Curiously, I was on the right track because I was looking at List::Util qq(pairs) to solve this but it only seemed to work on arrays. I didn't see pairgrep , looks very useful. I'll try that today after studying your example.