XML technologies / Regular expressions / Perl / The match operator / The match operator and its surroundings

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

The following sections summarize how the match operator affects its surroundings and is affected by them.

 

Side effects of the match operator

A match’s side effects are often more important than its actual result. Indeed, a match operator quite often stands alone in void context without its result being checked or assigned to a variable. It is used only for its side effects (and behaves as in scalar context). The following side effects arise from a successful match:

Again, these side effects occur only after a successful match and remain untouched on failure. The following, however, happen on every match, successful or not:

 

External influences on the match operator

Matching with the match operator depends on more than its operands and modifiers. The following list summarizes the other factors:

context

The context in which the match operator is used—scalar, list, or void—strongly affects how matching proceeds, its return value, and its side effects.

Current position

The current position in the subject string, set explicitly with pos(...) or by a previous match, determines where the next search using /g begins. It is also the position matched by ˹\G˼.

Default regex

An empty regex operand uses the default regex (see Default for an empty regex operand).

study

This affects neither the matches found nor the return value, only matching speed. Preprocessing the subject string with study may make matching faster or slower. See The function study.

m?...? and reset

The invisible matched/not-matched state of the m?...? operator changes after a successful m?...? search or a call to reset (see Special match-once-only behavior with ?...?).

 

What context is this?

To close the section on the match operator, here is an exercise. In particular, with while, if and foreach control structures, you must be especially careful about the context being used. What does the following program fragment print?

while ("Eene Meene Muh" =~ m/\w+/g) {
   print "WHILE raus ist $&.\n";
}
print "\n";
if ("Eene Meene Muh" =~ m/\w+/g) {
   print "IF raus ist $&.\n";
}
print "\n";
foreach ("Eene Meene Muh" =~ m/\w+/g) {
   print "FOREACH raus ist $&.\n";
}

The question is a little tricky. For the explanation, see Solution 14.

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top