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"}};
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'
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With