给出以下匿名哈希数组:
$fields_dump = [
{
'DEFAULT_FIELD_LABEL' => 'telco_hier_building',
'APPROVER_ORDER' => '0',
'IS_READONLY' => '0',
'FORM_ID' => '3913',
'REFERENCE' => 'building',
},
{
'DEFAULT_FIELD_LABEL' => 'Request Type',
'APPROVER_ORDER' => '0',
'IS_READONLY' => '0',
'FORM_ID' => '3913',
'REFERENCE' => 'request_type',
},
{
'DEFAULT_FIELD_LABEL' => 'Request Completion Date',
'APPROVER_ORDER' => '0',
'IS_READONLY' => '0',
'FORM_ID' => '3913',
'REFERENCE' => 'request_completion_date',
},
我希望DEFAULT_FIELD_LABEL
为telco_hier_building
或telco_imac_building
的值有条件地对数组进行grep。当它成功时,我需要提取到匹配值的第二个下划线。
我使用以下代码:
if ( grep { $_->{DEFAULT_FIELD_LABEL} =~ m/(telco_hier_|telco_imac_)building/ } @$fields_dump ) {
my $telco_prefix = $1;
...
}
条件触发正确,但正则表达式$1
分配为空,在此示例中,它应为telco_hier_
。
我做错了什么?
答案 0 :(得分:6)
匹配范围限定为grep {}
代码块。您可以改为使用for
循环:
use warnings;
use strict;
my $fields_dump = [
{
'DEFAULT_FIELD_LABEL' => 'telco_hier_building',
'APPROVER_ORDER' => '0',
'IS_READONLY' => '0',
'FORM_ID' => '3913',
'REFERENCE' => 'building',
},
{
'DEFAULT_FIELD_LABEL' => 'Request Type',
'APPROVER_ORDER' => '0',
'IS_READONLY' => '0',
'FORM_ID' => '3913',
'REFERENCE' => 'request_type',
},
{
'DEFAULT_FIELD_LABEL' => 'Request Completion Date',
'APPROVER_ORDER' => '0',
'IS_READONLY' => '0',
'FORM_ID' => '3913',
'REFERENCE' => 'request_completion_date',
},
];
for (@{ $fields_dump }) {
if ($_->{DEFAULT_FIELD_LABEL} =~ m/(telco_hier_|telco_imac_)building/) {
my $telco_prefix = $1;
print "$telco_prefix\n";
}
}
输出是:
telco_hier_
perldoc perlvar中的进一步说明。