Global matching
The g modifier finds every match instead of stopping at the first.
In this page:
Global matching
In list context, //g returns all matches, or all captures of all matches when the pattern has groups. In scalar context, for example in a while loop, each match continues from where the previous one stopped, and pos() reports that position. This is the standard way to walk through all the matches in a string.
Note:
Assigning to a scalar with = () = /g counts matches without keeping them.
Example: Global matching
use strict;
use warnings;
my $text = "cat bat rat mat";
my @all = $text =~ /(\w)at/g;
print "first letters: @all\n";
my $count = () = $text =~ /at/g;
print "count: $count\n";
while ($text =~ /(\w+)at/g) {
printf "found '%s' ending at position %d\n", $1, pos($text);
}
my %pairs = "a=1,b=2,c=3" =~ /(\w)=(\d)/g;
print join(", ", map { "$_ -> $pairs{$_}" } sort keys %pairs), "\n";
# Output:
# first letters: c b r m
# count: 4
# found 'c' ending at position 3
# found 'b' ending at position 7
# found 'r' ending at position 11
# found 'm' ending at position 15
# a -> 1, b -> 2, c -> 3
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting /g and getting only the first match
- Using //g in scalar context outside a loop and getting only one match per call
- Assuming the loop restarts automatically after it finishes
Chapter Summary
- List-context //g returns all matches
- Scalar //g in a while loop iterates over matches
- pos() gives the current position
- Captures with //g return a flat list
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: