XML technologies / Regular expressions / Perl / The match operator / The input-string operand

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

The usual way to specify the text to search is =~, as in $text =~ m/.../. This =~ is not an assignment operator or comparison operator. It is simply an unusual combination of characters connecting the input string and regex, with notation inspired by awk .

Since the entire construct “Ausdruck =~ m/.../” is itself an expression, it can be used wherever an expression is allowed. For example:

$text =~ m/.../;   # Simples Matching, wahrscheinlich wegen der Nebeneffekte.

if ($text =~ m/.../) {
  # Wird ausgeführt, wenn ein Treffer gefunden wird.
  .
  . 
  .
 

$ok = ( $text   =~ m/.../ ); # $ok erhält das Resultat des Matchings.
$ok =   $text   =~ m/.../  ; # Wie oben; =~ bindet stärker als = .

$resultat =   $text;            # Kopiere $text in $resultat ...
$resultat             =~ m/.../ ; # ... wende Regex auf $resultat an.
( $resultat = $text ) =~ m/.../ ; # Beides in einem Ausdruck.

The default input string $_

When the input-string operand is variable $_, you can omit “$_ =~” entirely: $_ is the default input string, the predefined input-string operand.

An expression such as

$text =~ m/Regex/;

means “apply Regex to the text in $text, ignore the result, but still set the side effects.” Omitting ›~‹ makes the resulting

$text = m/Regex/;

mean “apply Regex to the text in $_ and store the true-or-false result in $text”. In other words, these lines are equivalent:

$text =        m/regex/;
$text = ($_ =~ m/regex/);

The default input string is particularly convenient when other language constructs use the same default variable $_, as many do. This construct is common:

while (<>)
{
   if (m/.../) {
     .
     . 
     .
   } elsif (m/.../) {
     .
     . 
     .

In general, however, excessive reliance on defaults makes programs obscure to less experienced programmers.

Negating the match result

Using !~ instead of =~ negates the return value. We will shortly discuss return values and other side effects; with !~, it is simply true or false. These three forms are equivalent:

if ($text !~ m/.../)

if (not $text =~ m/.../)

unless ($text =~ m/.../)

I prefer the middle version. All three have the same side effects as $1 and so on. !~ is merely syntactic convenience when something should not match.

  

 

 

 

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