我想知道Perl是否有内置的方法来检查哈希元素是否存在与匹配特定正则表达式的键。例如:
my %h = ( 'twelve' => 12,'thirteen' => 13,'fourteen' => 14 );
我想知道有没有办法做到这一点:
print "We have 12\n" if exists $h{twelve}; print "We have some teens\n" if exists $h{/.*teen$/};
解决方法
smart match operator这样做(从Perl v5.10开始可用)。
$a $b Type of Match Implied Matching Code ====== ===== ===================== ============= ... Regex Hash hash key grep grep /$a/,keys %$b ...
样品用量:
# print if any key in %h ends in "teen" print "We have some teens\n" if /.*teen$/ ~~ %h;