Where You Left Off: The \G Assertion
Whenever you start thinking in terms of the pos function, it’s tempting to start carving
your string up with substr, but this
is rarely the right thing to do. More often, if you started with pattern
matching, you should continue with pattern matching. However, if you’re
looking for a positional assertion, you’re probably looking for \G.
The \G assertion represents
within the pattern the same point that pos represents outside of it. When you’re
progressively matching a string with the /g modifier (or you’ve used the pos function to directly select the starting
point), you can use \G to specify the
position just after the previous match. That is, it matches the location
immediately before whatever character would be identified by pos. This allows you to remember where you
left off:
($recipe = <<'DISH') =~ s/^\s+//gm;
Preheat oven to 451 deg. Fahrenheit.
Mix 1 ml. dilithium with 3 oz. NaCl and
stir in 4 anchovies. Glaze with 1 g.
mercury. Heat for 4 hours and let cool
for 3 seconds. Serves 10 aliens.
DISH
$recipe =~ /\d+ /g;
$recipe =~ /\G(\w+)/; # $1 is now "deg"
$recipe =~ /\d+ /g;
$recipe =~ /\G(\w+)/; # $1 is now "ml"
$recipe =~ /\d+ /g;
$recipe =~ /\G(\w+)/; # $1 is now "oz"The \G metasymbol is often used
in a loop, as we demonstrate in our next example. We “pause” after every
digit sequence, and, at that position, we test whether there’s an
abbreviation. If so, we grab the next two words. Otherwise, we just grab
the next word:
pos($recipe) = ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access