我需要根据正则表达式过滤哈希值,如果正则表达式匹配则从哈希中删除键.
这是我到目前为止,不幸的是它没有做任何事情,我不知道为什么.
所以,我正在构建一个字符串数组的正则表达式,我也需要匹配子字符串,所以如果哈希键是someprefix_somestring我需要匹配somestring或字符串
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 =>因为someprefix_somekey和otherprefix_somekey会匹配$regex,因此会从哈希中删除
我不知道为什么这不起作用,请赐教
感谢hobbs回答我能够使它工作,这就是我现在拥有的:
my $hashref = {someprefix_somekey => 'somevalue',sort { length( $b ) <=> length( $a ) or $a cmp $b } @array_of_strings ); $regex = qr{($regex)}; delete @{$hashref}{grep { m/$regex/ } keys %$hashref };