本文介绍了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\n" if exists $h{twelve};
print "We have some teens\n" 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
...

示例用法:

Sample usage:

# print if any key in %h ends in "teen"
print "We have some teens\n" if /.*teen$/ ~~ %h;

这篇关于Perl:将散列键匹配到正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:51