Main index

Introducing UNIX and Linux


Perl

Overview
Introduction
      Why yet another utility?
      Beginning Perl
      Invoking Perl
      Documentation on perl
      Perl Scripts
Variables
Input and output
      Files and redirection
      Pipes
      The DATA filehandle
Fields
Control structures
Predefined Perl
      Functions
      Modules
Regular expressions
      Single character translation
      String editing
Perl and the Kernel
Quality code
When do I use Perl?
Summary
Exercises

Regular expressions

Regular expressions have been used extensively in the previous chapters, and it will come as no surprise that Perl also uses them. The difference between Perl's approach to regular expressions, and that of other utilities, is that they are central to the use of Awk, Sed and Grep. In Perl, the use of regular expressions is just one of many possibilities available to the programmer. Typical use of regular expressions in Perl involves the comparison or editing of strings.

The operator used to manipulate regular expressions is =~, known as the pattern binding operator. Perl does not use the phrase regular expression, preferring instead pattern, but it is synonymous.

The simplest use of patterns is to match strings. The expression

string =~ /pattern/

evaluates to true if the string is matched by the pattern, and

string !~ /pattern/

evaluates to true if the string is not matched by the pattern.

Worked example

Write a Perl fragment to take the variable $word and enclose its contents in single quotes only if it does not already contain single quotes as both its first and last characters.
Solution: Use a pattern match - the pattern ^'.*'$ matches a single quote at the left (anchored by the ^ ) and at the right (anchored by the $). The pattern .* matched zero or more occurrences of anything.

if ($word !~ /^'.*'$/) {
  $word = "'" . $word . "'";
}


Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck