[英]Perl: Grep keys in a hash of hashes
請注意,我對不涉及 grep 的解決方案也持開放態度。
說我有一個像這樣的散列
%HoH =
(
"KeyOne" => { I~Want~This => 1, KeyTwo => 2, I~Also~Want~This => 3},
)
本質上,我想獲取匹配某個模式的嵌套哈希中的每個鍵,並將其放入一個數組中(例如^I.*Want.*This$
)
我嘗試了以下方法,但沒有用:
my $regex = qr/"^I.*Want.*This$"/;
my @keys = grep {defined $HoH {"KeyOne"}{/$regex/} } keys %{$HoH{"KeyOne"}};
謝謝!
您發布的代碼沒有為我編譯。 我在具有~
哈希鍵周圍添加了單引號,並添加了一個;
在哈希定義之后。
解決方案是從正則表達式中刪除雙引號並簡化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);
__END__
$VAR1 = [
'I~Also~Want~This',
'I~Want~This'
];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.