while (/\G,?(\d+)/g) {
print "Found number $1\n";
}
By default, when your match fails (when we run out of numbers in the
examples, for instance) the remembered position is reset to the
start. If you don't want this to happen, perhaps because you want to
continue matching from that position but with a different pattern,
use the modifier /c with /g:
$_ = "The year 1752 lost 10 days on the 3rd of September";
while (/(\d+)/gc) {
print "Found number $1\n";
}
# the /c above left pos at end of final match
if (/\G(\S+)/g) {
print "Found $1 right after the last number.\n";
}
Found number 1752
Found number 10
Found number 3
Found rd after the last number.
Successive patterns can use /g on a string, which
remembers the ending position of the last successful match. That
position is associated with the scalar matched against, not with the
pattern. It's reset if the string is modified.
$a = "Didst thou think that the eyes of the White Tower were blind?";
$a =~ /(\w{5,})/g;
print "Got $1, position in \$a is ", pos($a), "\n";
Got Didst, position in $a is 5
pos($a) = 30;
$a =~ /(\w{5,})/g;
print "Got $1, position in \$a now ", pos($a), "\n";
Got White, position in $a now 43
Without an argument, pos operates on
$_:
$_ = "Nay, I have seen more than thou knowest, Grey Fool.";
/(\w{5,})/g;
print "Got $1, position in \$_ is ", pos, "\n";
pos = 42;
/\b(\w+)/g;
print "Next full word after position 42 is $1\n";
Got knowest, position in $_ is 39
Next full word after position 42 is Fool