用子串测试密钥是否存在

时间:2012-02-09 17:07:56

标签: regex perl hash

我有一个使用datadumper看起来像这样的多维哈希/数组;

{
          'Customer' => {'123abc' => 
                         {'status' => 
                                     {'New' => 
                                              {'email'=>['user@xxx.com' ], 
                                               'template' => 'XYZ' }
                                                                       }
                                                           },
                        '234' => 
                        {'status' => 
                                    {'New' => 
                                            {'email' => ['user@xxx.com' ],
                                            'template' => 'XYZ' }
                                                                            }
                                                                }

$customers = ("123abc", "234abc", "adb234");

我需要根据数组值的完整或部分匹配来测试客户是否存在。

我用于完整匹配的代码工作正常;

foreach (@customers) {
if ($config->{Customer}->{$customers[0]}) {
do something
} }

这将返回“123abc”

的匹配

但是当$ customers [0]中存在字符串234或者只是在没有数组$ customers且仅使用字符串的情况下进行测试时,我无法匹配它。

我试过了;

if (/.234*$/ ~~ %config->{Customer})

基于此网站上的智能匹配示例“打印”我们有一些青少年\ n“if /.*teen$/~~%h;”。

if (exists $config->{Customer}->{/234/}

以及在正则表达式的开头使用m。 {M / 234 /}

乔恩

这是用perl编写的。

1 个答案:

答案 0 :(得分:1)

看起来你想要翻看所有的密钥。

my @keys = grep { /234/ } keys %{$config->{Customer}};
if (@keys) {
  # do something, but check for multiple matches...
}

Grep返回块计算结果为true的所有元素,每个元素由$ 表示。正则表达式匹配(//)默认为与$ 匹配。上述陈述可以改写为

my @keys = grep { $_ =~ /234/ } keys %{$config->{Customer}};
if (@keys) {
  # do something, but check for multiple matches...
}

但只要你熟悉perl,这就是多余的。

相关问题