我尝试进行正则表达式匹配:
$address =~ s/$re_region//;
$new_address_h->{ region } = $1 //'';
# $1 = undef; # ERROR: Modification of a read-only value attempted at ...
$address =~ s/$re_city//;
$new_address_h->{ city } = $1;
当城市不匹配时,我希望它用undef
填充。但是当 city
不匹配时,$1
具有之前匹配的值。为什么?我希望当匹配失败时,它的输出没有值,甚至没有特殊变量。像 eval
刷新 $@
没有额外的 if
是否可行?
最佳答案
记录在案的行为 ( perlvar ):
Perl sets these variables when it has a successful match, so you should check the match result before using them.
您可以使用 do使用三元运算符填充哈希:
$new_address_h->{region} = do { $address =~ s/$re_region// ? $1 : undef };
$new_address_h->{city} = do { $address =~ s/$re_city// ? $1 : undef };
或者,用 undefs 填充散列,然后在匹配时用值替换它们:
my $new_address_h = { region => undef, city => undef };
$address =~ s/$re_region// and $new_address_h->{region} = $1;
$address =~ s/$re_city// and $new_address_h->{city} = $1;
常见的方式是在列表赋值中只匹配,而不是替换和填充:
($new_address_h->{region}) = $address =~ /$re_region/;
($new_address_h->{city}) = $address =~ /$re_city/;
关于regex - 如何重置 $1 perl 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60712087/