帮助理解 perl 中的全局标志 [英] Help understanding global flag in perl
问题描述
据我所知,在 perl 全局 '/g' 标志意味着搜索将替换/返回整个字符串中的所有匹配项.但是我无法理解它在匹配时对全局变量的反应方式,有人可以解释为什么这两个示例程序的输出之间存在差异:
As far as I know in perl global '/g' flag means that search will replace/return all the matches throughout the string. But I am not able to understand the way it reacts to global variables while matching, can somebody explain the why there is difference between output of these two sample programs:
版本 1:
my $text = 'This is sample float value 3.2 ';
getFloat();
getFloat();
sub getFloat(){
if ($text =~ /([0-9]+?)(.?)([0-9]+?)/is){
print "matched> $1$2$3 ";
}
}
输出:匹配> 3.2匹配> 3.2
Output: matched> 3.2 matched> 3.2
版本 2:(带全局标志)
my $text = 'This is sample float value 3.2 ';
getFloat();
getFloat();
sub getFloat(){
if ($text =~ /([0-9]+?)(.?)([0-9]+?)/gis){
print "matched> $1$2$3 ";
}
}
输出:匹配> 3.2
从输出中可以看出,全局标志匹配只发生一次.有人可以解释这种行为吗.
推荐答案
使用 g
修饰符,字符串会记住上次匹配的位置,因此您可以使用 请求匹配g
在 while 循环中查找所有匹配项.
With the g
modifier, the string remembers the place of its last match, so you can request a match with a g
in a while loop and find all the matches.
如果没有 g
,您每次都从头开始,并始终找到第一个匹配项.
Without the g
you start over each time and always find the first match.
在您的情况下,使用 g
,您第一次匹配 3.2,但第二次尝试匹配时,没有更多匹配.
In your case, with the g
, you matched 3.2 the first time, but the second time you tried to match, there were no more matches.
如果没有 g
,你可以调用 getFloat()
无数次,你总会找到第一个匹配项.
Without the g
you can call getFloat()
a zillion times and you will always find the first match.
这篇关于帮助理解 perl 中的全局标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!