PERL / CHAPTER 08

Global matching and parser progress

Advanced

Track repeated matches without confusing extraction and validation.

By the end of this chapter

  • Use global matching in list and scalar contexts
  • Explain the role of match position
  • Reject unconsumed text in a strict parser

The idea

The global match modifier supports repeated extraction. In list context, a global match can collect captures; in scalar context, successive successful matches advance the string’s match position. This state belongs to the target string and matters when loops or helper routines reuse it. A failed ordinary global match resets the position unless the keep-position behavior is requested.

Extracting every valid token does not prove that the whole input is valid: unmatched gaps can still be ignored. A strict parser should require progress from the previous position and verify that all input was consumed. Choose patterns that cannot repeatedly succeed without useful progress, and copy captured values immediately when later matches could overwrite the capture variables.

Perl example
use strict; use warnings;
my $text="a12 b7";
my @numbers=($text =~ /([0-9]+)/g);
print join(",",@numbers),"\n";
Result
12,7

List-context global matching collects the numeric captures, but this alone does not validate the spaces or letter prefixes.

Try it yourself

Parse a comma-separated integer list while rejecting leading, trailing, or internal junk.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

A tokenizer finds two valid numbers in an otherwise malformed string. What still needs validation?