XML technologies / Regular expressions / Perl / The substitution operator
(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)
The substitution operator in Perl, s/.../.../ extends pattern matching into searching and replacing. Its general form is:
SuchtextOperand =~ s/Regex/Ersatztext/Modifikatoren
Briefly, text matched by the regex is replaced with the replacement operand’s value. With the /g modifier, matching repeats and replaces every match.
As with matching, the subject operand and connecting =~ may be omitted to substitute within the default subject $_. The leading s is always required, unlike m.
Matching is complicated: behavior and return values depend on context, pos, and modifiers. Substitution is simple by comparison: it always returns how many replacements occurred, and its modifiers are straightforward.
The five general modifiers apply (see Regex modifiers), plus two more: the familiar /g modifier and /e, discussed two sections below.
The replacement operand
In the usual form s/.../.../, replacement follows the regex operand and ends at a third delimiter. Paired regex delimiters, such as <...>, require separate replacement delimiters, four in total. Examples include s{...}{...} and s[...]/.../ or s<...>'...'. The operands may then be separated by whitespace or comment lines. With /x or /e , braces are common:
$text =~ s{
... Große Regex mit eingestreuten Kommentaren ...
} {
... Perl-Code, der evaluiert wird; das Resultat wird als Ersatztext verwendet ...
}ex;Distinguish the regex from replacement text. The regex operand follows specialized regex parsing rules (see Regex operand delimiters). The replacement is parsed and evaluated like a double-quoted string after matching succeeds, or with /g after every success. It can thus use variables such as $1 referring to the current match.
Only two cases do not treat replacement text as a double-quoted string:
A single-quoted replacement is parsed like a single-quoted string, without variable interpolation.
The modifier
/e, discussed next, parses replacement as Perl code instead of a double-quoted string. The code executes and its return value becomes the replacement.
The /e modifier
With the /e modifier, replacement is Perl code, as though in eval {...}. Syntax is checked when compiling the script, but evaluation occurs after every match, in scalar context. Its result becomes the replacement. A simple example:
$text =~ s/-time-/localtime/ge;Each occurrence of ˹-time-˼ is replaced by the result of localtime, which in scalar context returns local time as a string, for example “Mon Sep 25 18:36:51 2006”.
Since code is reevaluated after each match, it can use that match’s side effects, such as $1. For example, special URL characters can be encoded as two hexadecimal digits prefixed by %. This substitution encodes all nonalphanumeric characters that way:
$url =~ s/([^a-zA-Z0-9])/sprintf('%%%02x', ord($1))/ge;
This substitution restores the original string:
$url =~ s/%([0-9a-f][0-9a-f])/pack("C", hex($1))/ige;
sprintf('%%%02x', ord(Zeichen)) converts a character to its numeric URL form, while pack("C", Code) does the reverse. See Perl’s documentation for details.
Repeating /e
Repeating most modifiers changes nothing except possibly confusing readers. The /e modifier differs: normally Perl evaluates the code and inserts the result. A second ›e‹ causes the result itself to be evaluated again as Perl code. This supports as many eval cycles as specified ›e‹s. Mostly this is useful for the Obfuscated Perl Contest, a competition for unreadable code, modeled on the longstanding C contest. This explanation is a German translator’s note.
It occasionally has ordinary uses. How would you manually interpolate variables into strings read from a configuration file? Given ›... $var ...‹, the substring ›$var‹ should become the value of $var.
A simple approach:
$data =~ s/(\$[a-zA-Z_]\w*)/$1/eeg;Without any /e, the matched string ›$var‹ simply replaces itself, which is useless. With one /e , code in $1 executes, yielding ›$var‹, again replacing the string with itself. The second /e, however, evaluates ›$var ‹ again as Perl code, yielding the variable’s value to replace its name. This emulates interpolation.
Context and return value
Matching return values depend on context and the /g modifier. Substitution is simpler: it always returns the number of replacements, or an empty string if none occurred.
In Boolean context, such as an if condition, it conveniently means true if replacements occurred, and false otherwise.
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