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

Fields

In previous chapters we have frequently considered text files as being divided into records (usually lines) and fields (usually columns separated by whitespace or colons).

In Perl, we can take a string and decompose it into fields using the Perl operator split. This takes two arguments, a pattern enclosed in forward slashes, and the string, and returns an array whose values are the fields of the string using the pattern to describe what separates the fields. For example, suppose string $play is set to the string "Much Ado About Nothing", then the following will create an array @words containing four elements (indexed from 0 to 3) containing strings "Much", "Ado", "About" and "Nothing" respectively:

@words = split / /, $play;

If the second argument is omitted, $_ is assumed; if the first argument is also omitted, the split is performed on whitespace.

Worked example

The file /etc/passwd contains colon-separated fields specifying the users of the machine. The first field is always the username. Write a Perl script to read the password file and display, one per line, all the usernames.
Solution: use split to extract the fields into an array, using pattern : to describe the field separator, and print out the first element of the array (index 0).

open(PASSWORDS, "/etc/passwd");
while (<PASSWORDS>) {
  @cols = split /:/;
  print "@cols[0]\n";
}
close(PASSWORDS);

Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck