Perl g Modifier
The global modifier (g) is used to perform the same search on the same string repeatedly.
In the list context, it will make an array of each parenthesized pattern. For example, our word search example from the last
($a, $b, $c) = /(\S*)\s*(\S*)\s*(\S*)/;
could be rewritten like this:
@array = /(\S+)\s*/g;
That will create an array with one element for each word in the string.
In fact, without parenthesis it will make the array of each match to the whole pattern. So the search can be even more abbreviated:
@array = /\S+/g;
In a scalar context, it will return 1 (true) for every successful match. For example, this loop will print each word on a line:
print "[$&] "
The special variable
$& always has the last matched pattern.
In a scalar context, the /g modifier performs a progressive match. For each execution of the match, Perl starts searching from the point in the search string just past the last match. You can use this to progress through an array searching for the same string
without having to remove or manually set the starting position of the search.
The position of the last match can be used within a regular expression using the \G assertion.
When /g fails to match, the position is reset to the start of the string.