← Back to Perl Course | Chapter 4: Regular Expressions | Lesson 5 of 7

Global matching

The g modifier finds every match instead of stopping at the first.

In this page:

  1. Global matching

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

perl
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
Common Mistakes
  1. Forgetting /g and getting only the first match
  2. Using //g in scalar context outside a loop and getting only one match per call
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.