Perl:将哈希键与正则表达式匹配 [英] Perl: Matching hash keys to a regular expression
本文介绍了Perl:将哈希键与正则表达式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道 Perl 是否有一种内置方法来检查哈希元素是否存在,其键与特定正则表达式匹配.例如:
I'm wondering if Perl has a built-in way to check for the existence of a hash element with a key matching a particular regex. For example:
my %h = ( 'twelve' => 12, 'thirteen' => 13, 'fourteen' => 14 );
我想知道是否有任何方法可以做到这一点:
I'm wondering if there is any way to do this:
print "We have 12
" if exists $h{twelve};
print "We have some teens
" if exists $h{/.*teen$/};
推荐答案
智能匹配运算符 执行此操作(自 Perl v5.10 起可用).
The smart match operator does this (available since 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
" if /.*teen$/ ~~ %h;
这篇关于Perl:将哈希键与正则表达式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文