正则表达式 $1 进入变量会干扰另一个变量 [英] Regex $1 into variable interferes with another variable
问题描述
我一直在努力处理我的一段代码,现在无法弄清楚.似乎与 $1 的处理方式有关,但我找不到任何相关内容.
I have been struggling with a section of my code for a while now and can't figure it out. Seems to have something to do with how $1 is handled but I cannot find anything relevant.
正则表达式找到 16640021 并将其分配给数组中的一个位置.
The regex finds the 16640021 and assigns it to a position in the arrays.
my @one;
my @two;
my $articleregex = qr/\s*\d*\/\s*\d*\|\s*(.*?)\|/p; # $1 = article number
my $row = " 7/ 1| 16640021|Taats 3 IP10 |14-03-03| | | 1,0000|st | | 01| | N| 0|";
if ($row =~ /$articleregex/g) {
$one[0] = $1;
}
if ($row =~ /$articleregex/g) {
$two[0] = $1;
}
print $one[0];
print $two[0];
哪些输出
Use of uninitialized value in print at perltest3.pl line 13.
16640021
$one[0] 的指定似乎在某种程度上干扰了 $two[0] 的指定.这对我来说似乎很奇怪,因为这两个变量及其名称不应以任何方式相互作用
It appears that the designation of $one[0] somehow interferes with that of $two[0]. This seems strange to me as the two variables and their designations should not be interacting in any way
推荐答案
这是因为你使用了 if (//g)
而不是 if (//)
.
It's because you used if (//g)
instead of if (//)
.
//g
在标量上下文中将pos($_)
[1] 设置为匹配停止的位置,或取消设置pos($_)
[1] 如果匹配不成功[2].//g
在标量上下文中从位置pos($_)
[1] 开始匹配.
//g
in scalar context setspos($_)
[1] to where the match left off, or unsetspos($_)
[1] if the match was unsuccessful[2].//g
in scalar context starts matching at positionpos($_)
[1].
例如
$_ = "ab";
say /(.)/g ? $1 : "no match"; # a
say /(.)/g ? $1 : "no match"; # b
say /(.)/g ? $1 : "no match"; # no match
say /(.)/g ? $1 : "no match"; # a
这允许以下内容遍历匹配项:
This allows the following to iterate through the matches:
while (/(.)/g) {
say $1;
}
不要使用if (//g)
[3]!
$_
用于表示匹配的变量.- 除非还使用了
/c
. - 除非您正在展开
while (//g)
,或者除非您使用if (//gc)
进行标记化.
$_
is being used to represent the variable being matched against.- Unless
/c
is also used. - Unless you're unrolling a
while (//g)
, or unless you're usingif (//gc)
to tokenize.
这篇关于正则表达式 $1 进入变量会干扰另一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!