in reply to How to grep for values & see the keys?
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>
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>
°) 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 | |
by LanX (Saint) on May 15, 2022 at 23:08 UTC | |
by kcott (Archbishop) on May 16, 2022 at 03:53 UTC | |
|
Re^2: How to grep for values & see the keys?
by misterperl (Friar) on May 13, 2022 at 14:18 UTC |