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

Single character translation

We start by considering character-by-character translation. You will recall the use of the shell command tr, and there is an almost identical facility available in Perl. The syntax is almost identical, except that

  • the arguments are separated and enclosed by three slashes, and
  • the options (such as d) appear at the end.

The string which appears between the first two slashes is called the search string, and the string between the last two slashes is the replace string. For example, the following command lowercases each letter in $word:

$word =~ tr/A-Z/a-z/;

The following command replaces each vowel in $word by an @ symbol:

$word =~ tr/AEIOUaeiou/@/;

The option d to delete characters is supported, and causes all characters in the search string which do not have replacements in the replacement string to be deleted. This behaviour is slightly more complex than the shell command tr. For example, to delete all vowels in $word we could type:

$word =~ tr/AEIOUaeiou//d;

Worked example

Write a Perl script to copy standard input to standard output with all digits deleted and the symbol @ replaced by #.
Solution: Use a while loop to iterate through the lines of standard input; for each line, the variable $_ contains the line, and we can then use tr with option d search string @0-9 to delete the digits, and raplacement string # to replace the first character of the search string (the @):

while (<STDIN>) {
  $_ =~ tr/@0-9/#/d;
  print $_;
}

Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck