Perl global matching
last modified November 25, 2026 Perl 5.44
Without modifiers, a match operation finds only the first match in a string.
The /g modifier makes the match global. What that means depends
on the context. In list context, the match returns all matches at once. In
scalar context, it finds one match at a time and remembers where it stopped,
so a loop can walk through the string. Together with the \G
anchor and the /c modifier, this is enough to write small
tokenizers.
Finding all matches
In list context, a match with /g returns a list of all the
strings that the pattern matches.
#!/usr/bin/perl use warnings; use v5.34.0; my $text = 'Orders: 12 boxes, 7 crates and 150 bags.'; my ($first) = $text =~ /(\d+)/; say "first number: $first"; my @numbers = $text =~ /\d+/g; say "all numbers: @numbers";
Without /g, the match stops at the first number. The capture
group is needed in that case: a match without groups returns only 1 for
success in list context, not the matched text. With /g and no
groups, the match returns every matched string.
$ perl all_matches.pl first number: 12 all numbers: 12 7 150
Global matching with captures
When the pattern has capture groups, a global match returns the captured values of every match, one after another, in a single flat list.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my $text = 'width=640 height=480 depth=24';
my @pairs = $text =~ /(\w+)=(\d+)/g;
say "flat list: @pairs";
my %size = $text =~ /(\w+)=(\d+)/g;
for my $key (sort keys %size) {
say "$key: $size{$key}";
}
Each match contributes two values, the name and the number. A flat list of names and values is exactly what a hash assignment expects, so a single line turns the text into a lookup table.
$ perl captures.pl flat list: width 640 height 480 depth 24 depth: 24 height: 480 width: 640
Counting matches
To count matches, the global match must run in list context, but the result we want is a number. The usual idiom assigns the match to an empty list and then assigns that to a scalar.
#!/usr/bin/perl use warnings; use v5.34.0; my $dna = 'AGCTTAGCTAAGCTAGCT'; my $count = () = $dna =~ /AGC/g; say "AGC occurs $count times"; my $wrong = $dna =~ /AGC/g; say "without the empty list: $wrong"; my $gc = () = $dna =~ /[GC]/g; printf "GC content: %.1f%%\n", 100 * $gc / length $dna;
A list assignment in scalar context returns the number of elements on its right side, which is the number of matches. Assigning the match directly to a scalar puts it in scalar context, where it finds only the next match and returns true. The same idiom counts the G and C bases to compute their share.
$ perl count.pl AGC occurs 4 times without the empty list: 1 GC content: 33.3%
Iterating over matches
In scalar context, each global match continues where the previous one on the
same variable ended. A while loop then visits the matches one by
one, and each iteration has its own capture variables. The pos
function returns the offset where the next search starts.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my $text = 'cat bat rat';
while ($text =~ /(\w)at/g) {
my $end = pos $text;
say "found $1-at, next search starts at $end";
}
my $after = pos $text;
say "after the loop: ", $after // 'undef';
The loop runs once for every word ending in at. After each match,
pos points just behind the matched text. When no further match
exists, the condition is false and the position is reset to
undef. The next global match on the variable will start at the
beginning again. More on the function in Perl pos.
$ perl iterate.pl found c-at, next search starts at 3 found b-at, next search starts at 7 found r-at, next search starts at 11 after the loop: undef
A stale position
The position belongs to the variable, not to the pattern. A global match in scalar context that is not part of a loop leaves the position set, and a later global match on the same variable silently starts there.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my $text = 'apple banana apple cherry';
if ($text =~ /banana/g) {
say "banana found, pos is ", pos $text;
}
if ($text =~ /apple/g) {
say "apple found at ", pos($text) - 5;
}
pos($text) = undef;
if ($text =~ /apple/g) {
say "after reset, apple found at ", pos($text) - 5;
}
The first condition finds banana and leaves the position at 12.
The second match looks for apple only from there on and finds
the second occurrence at offset 13, not the first one at 0. Assigning
undef to pos resets the position. A plain match
without /g is usually the better choice for a simple test.
$ perl stale_pos.pl banana found, pos is 12 apple found at 13 after reset, apple found at 0
The \G anchor
A global match skips any text that does not match until it finds the next
match. The \G anchor forbids this. It matches only at the
position where the previous global match ended, so the matches must follow
each other without gaps.
#!/usr/bin/perl use warnings; use v5.34.0; my $s = '12 34 56 x 78 90'; my @without = $s =~ /(\d+)\s*/g; say "without \\G: @without"; my @with = $s =~ /\G(\d+)\s*/g; say "with \\G: @with"; $s =~ /x/g; my @after = $s =~ /\G\s*(\d+)/g; say "after x: @after";
Without \G, the match jumps over the x and finds
all five numbers. With \G, the chain of matches breaks at the
x, and only the first three numbers are returned. The last part
first moves the position behind the x with a scalar global
match. The \G pattern then continues from there.
$ perl anchor_g.pl without \G: 12 34 56 78 90 with \G: 12 34 56 after x: 78 90
A tokenizer with \G and /gc
A tokenizer splits source text into tokens such as numbers, names and
operators. It tries several patterns at the current position until one of
them matches. Normally, a failed global match resets the position, which
would lose our place. The /c modifier keeps the position after a
failure.
#!/usr/bin/perl
use warnings;
use v5.34.0;
my $src = 'total = 3 + 42 * rate';
my @tokens;
for ($src) {
while (1) {
if (/\G\s+/gc) { next }
elsif (/\G(\d+)/gc) { push @tokens, "NUM($1)" }
elsif (/\G([A-Za-z_]\w*)/gc) { push @tokens, "ID($1)" }
elsif (/\G([=+*\/-])/gc) { push @tokens, "OP($1)" }
elsif (/\G\z/gc) { last }
else { die "unexpected input\n" }
}
}
say join ' ', @tokens;
The for ($src) loop aliases the string to $_, so
the patterns need no binding operator. Every pattern starts with
\G and uses /gc. When a pattern fails, the next one
is tried at the same position. Whitespace is skipped, numbers, identifiers
and operators become tokens, and \z detects the end of the
input.
$ perl tokenizer.pl ID(total) OP(=) NUM(3) OP(+) NUM(42) OP(*) ID(rate)
Reporting tokenizer errors
A tokenizer should tell the user where the input went wrong. Because the position survives failed matches, it points exactly at the character that no pattern accepts.
#!/usr/bin/perl
use warnings;
use v5.34.0;
sub tokenize {
my ($src) = @_;
my @tokens;
for ($src) {
while (1) {
if (/\G\s+/gc) { next }
elsif (/\G(\d+)/gc) { push @tokens, "NUM($1)" }
elsif (/\G([A-Za-z_]\w*)/gc) { push @tokens, "ID($1)" }
elsif (/\G([=+*\/-])/gc) { push @tokens, "OP($1)" }
elsif (/\G\z/gc) { last }
else {
my $pos = pos // 0;
die "unexpected '", substr($_, $pos, 1), "' at $pos\n";
}
}
}
return @tokens;
}
for my $src ('x = 5 * y', 'x = 5 $ 2') {
my @tokens = eval { tokenize($src) };
if ($@) {
print "$src: error: $@";
} else {
say "$src: @tokens";
}
}
The tokenizer is now a subroutine that returns the tokens. When nothing
matches, it reads the current position and dies with the offending character
and its offset. At the very beginning of the input, no match has happened
yet and pos is undefined, hence the // 0. The caller
catches the error with eval.
$ perl tokenizer2.pl x = 5 * y: ID(x) OP(=) NUM(5) OP(*) ID(y) x = 5 $ 2: error: unexpected '$' at 6
Empty matches
A pattern that can match the empty string, such as x*, matches
at every position in the string. Perl prevents an endless loop by not
allowing two empty matches at the same position.
#!/usr/bin/perl use warnings; use v5.34.0; my $s = 'abc'; my $n = () = $s =~ /x*/g; say "empty matches in '$s': $n"; (my $dashed = $s) =~ s/x*/-/g; say "s/x*/-/g: $dashed"; (my $between = $s) =~ s/(?<=.)(?=.)/-/g; say "between only: $between";
A string of three characters has four positions: before each character and
at the end. The pattern x* matches the empty string at each of
them, so the substitution inserts a dash at both ends too. The version with
lookbehind and lookahead assertions matches only the positions between two
characters. See Perl lookaround.
$ perl empty.pl empty matches in 'abc': 4 s/x*/-/g: -a-b-c- between only: a-b-c
Best practices
These recommendations help to use global matching safely and clearly.
- Choose the context deliberately: list context collects all matches, scalar context iterates.
- Do not use /g for a simple test: a scalar global match leaves a position that affects the next one.
- Reset the position when needed: assign
undeftopos. - Use \G with /gc for tokenizers: failed matches keep the position and errors can be reported exactly.
- Beware of empty matches: patterns that can match nothing produce extra matches.
Source
perlop: Regexp Quote-Like Operators · perlrebackslash · pos
In this article we have collected matches in list context, counted them,
iterated over them in scalar context, dealt with a stale position, used the
\G anchor, built a tokenizer with /gc and looked at
empty matches. See also Perl pos and
Perl parsing with regex.
Author
List all Perl tutorials.