Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Grep keys in a hash of hashes

Note that I'm open to solutions not involving grep as well.

Say I have a hash of hashes like so

%HoH = 
(
    "KeyOne" => { I~Want~This => 1, KeyTwo => 2, I~Also~Want~This => 3},
)

Essentially, I want to get every key in the nested hash that matches some pattern, and place it in an array (e.g. ^I.*Want.*This$)

I tried the following, which did not work:

my $regex = qr/"^I.*Want.*This$"/;
my @keys = grep {defined $HoH {"KeyOne"}{/$regex/} } keys %{$HoH{"KeyOne"}};
like image 870
Ken H. Avatar asked Jan 17 '26 05:01

Ken H.


1 Answers

Your posted code did not compile for me. I added single quotes around your hash keys that have ~, and I added a ; after the hash definition.

The solution is to remove the double quotes from the regex and to simplify the grep:

use warnings;
use strict;

my %HoH = 
(
    "KeyOne" => { 'I~Want~This' => 1, KeyTwo => 2, 'I~Also~Want~This' => 3},
);

my $regex = qr/^I.*Want.*This$/;
my @keys = grep { /$regex/ } keys %{$HoH{"KeyOne"}};

use Data::Dumper;
print Dumper(\@keys);

Output:

$VAR1 = [
          'I~Also~Want~This',
          'I~Want~This'
        ];
like image 129
toolic Avatar answered Jan 19 '26 19:01

toolic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!