Can anyone explain me the following results:
krivenok@olimpico ~ $ cat global_match.pl
use strict;
my $str = "aaa noSuchName sadsad asdsa dsa dsad";
while(<>)
{
# NOTE: ig
if($str =~ /noSuchName/ig)
{
print "YES\n";
}
else
{
print "NO\n";
}}
krivenok@olimpico ~ $ perl global_match.pl
YES
NO
YES
NO
YES
Thank you beforehand!
The /g modifier starts a "progressive match". That is, it will search
for the first match it can find in the string. If it finds a match,
it returns true, and then *remembers* where it found that match. The
next time the same pattern is executed, the pattern match starts
searching from the point at which it left off. If it finds another
match, it again returns true and remembers where it left off again.
And so on. When it finally cannot find any more matches, it returns
false, and resets the position pointer to the beginning of the string.
So in your example, it found noSuchName starting at position 4 in the
string. It returned true, and kept the position pointer at position
14 - immediately after the successful match. Then the next time
through your while loop, it starts searching the string at position
14, and of course does not find another match. So it returns false,
and resets the position pointer back to the beginning of the string.
The third time through, it once again finds noSuchName at position 4,
so returns true, and updates the position pointer to 14. Etc etc etc.
For more information:
perldoc -f pos
perldoc perlre
Hope this helps,
Paul Lalli