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:
Version 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 ";
}
}
Output:
matched> 3.2
matched> 3.2
Version 2:(with global flag)
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 ";
}
}
Output:
matched> 3.2
As seen from outputs, with global flag matching occurs only once. Can someone explain this behaviour.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…