3

我需要根据正则表达式过滤哈希,如果正则表达式匹配,则从哈希中删除键。

这是我到目前为止得到的,不幸的是它没有做任何事情,我不知道为什么。

所以,我正在从字符串数组中构建正则表达式,我也需要匹配子字符串,所以如果哈希键是我someprefix_somestring需要匹配它somestringstring

my $hashref = {someprefix_somekey => 'somevalue', otherprefix_otherkey => 23, otherprefix_somekey => 'someothervalue'};
my @array_of_strings = ('somekey', 'strings', 'bits', 'bobs');

my $regex = join( '|', sort { length( $b ) <=> length( $a ) or $a cmp $b } @array_of_strings );
$regex    = qr{($regex)};

delete $hashref->{ grep { !m/$regex/ } keys %$hashref };

我希望$hashref之后看起来像这样:{otherprefix_otherkey => 23}因为someprefix_somekeyotherprefix_somekey会匹配$regex,因此会从哈希中删除

我不知道为什么这不起作用,请赐教

感谢霍布斯的回答,我能够让它工作,这就是我现在所拥有的:

my $hashref = {someprefix_somekey => 'somevalue', otherprefix_otherkey => 23, otherprefix_somekey => 'someothervalue'};
my @array_of_strings = ('somekey', 'strings', 'bits', 'bobs');

my $regex = join( '|', sort { length( $b ) <=> length( $a ) or $a cmp $b } @array_of_strings );
$regex    = qr{($regex)};

delete @{$hashref}{grep { m/$regex/ } keys %$hashref };
4

1 回答 1

7

delete不太正确,因为您使用符号来访问单个键,因此grep在标量上下文中运行。这意味着最终你会尝试做一些事情,比如delete $hashref->{'3'}如果有三个键与你的正则表达式不匹配。

如果您将最后一行更改为此它应该可以工作:

delete @{$hashref}{grep /$regex/, keys %$hashref };

它使用哈希片。如果你觉得语法太难看,你也可以

delete $hashref->{$_} for grep /$regex/, keys %$hashref;

这可能读起来更自然一些。

于 2013-07-07T20:07:45.597 回答