我需要基于正则表达式过滤哈希,如果正则表达式匹配,则从哈希中删除键。
这是我目前得到的代码,不幸的是它什么也没做,我不知道为什么。
因此,我正在使用字符串数组构建正则表达式,我还需要匹配子字符串,因此如果哈希键是
我期望
这是我目前得到的代码,不幸的是它什么也没做,我不知道为什么。
因此,我正在使用字符串数组构建正则表达式,我还需要匹配子字符串,因此如果哈希键是
someprefix_somestring
,我需要将其与somestring
或string
进行匹配。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_somekey
和otherprefix_somekey
会匹配$regex
并从哈希表中删除。
我不知道为什么它没有起作用,请给我指点
感谢hobbs的答案,我现在能够解决它了,这就是我现在拥有的:
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 };