gpt4 book ai didi

regex - 为什么 $1 在 hashref 赋值中指向与多个正则表达式匹配的相同值?

转载 作者:行者123 更新时间:2023-12-02 05:33:31 27 4
gpt4 key购买 nike

对于没有故事的问题,请跳到该行之后。

我正在胡闹,将一些字母和数字的字符串(这两种情况都可能出现)分成哈希引用中的两个字段。它们应该只在该字段存在时出现。字符串可能如下所示:/^\D*\d*$/,例如 ZR17R15-19 22

我不想像这样简单地将它放入两个变量中,因为实际的 hashref 有点长,我想把东西放在一起。

my $asdf = "ZR17";
my ($x, $y) = $asdf =~ m/^(\D*)(\d*)$/;
my $foo = {
foo => $x,
bar => $y
};

如果我不想在字符串 17 的情况下使用键 foo,我可以说:

my $foo = {
( $x ? ( foo => $x ) : () ),
( $y ? ( bar => $y ) : () ),
};

我想出了像这样把它全部放在 hashref 赋值中:

my $asdf = "ZR17";

my $foo = {
( $asdf =~ m/(\d+)/ ? ( foo => $1 ) : () ),
( $asdf =~ m/(\D+)/ ? ( bar => $1 ) : () ),
};

print Dumper $foo;

这会产生以下结果:

$VAR1 = {
'bar' => 'ZR',
'foo' => 'ZR'
};

这里看起来好像只有一个 $1,而且弄混了。如果我注释掉第二行,foo 将是 17

有人可以解释这里发生了什么吗? $1 在哪里迷路/混淆了?

最佳答案

根据 perldoc ( http://perldoc.perl.org/perlre.html ):

These special variables, like ... the numbered match variables ($1 , $2 , $3 
, etc.) are dynamically scoped until the end of the enclosing block or until
the next successful match, whichever comes first.

因此,$1 在 $asdf =~ m/(\d+)/之后被覆盖为 17,因为它找到了一个匹配但还没有遇到封闭 block 的结尾。

但是,

my $foo = {
( eval{$asdf =~ m/(\D+)/ ? ( bar => $1 ) : ()} ),
( eval{$asdf =~ m/(\d+)/ ? ( foo => $1 ) : ()} ),
};

将给出预期的结果,因为范围是分开的。

关于regex - 为什么 $1 在 hashref 赋值中指向与多个正则表达式匹配的相同值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16896781/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com