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

Pipes

A similar method of working allows access to pipes. Suppose we wish to open a pipe to filter data into a command (cmd, say), which is both valid and exists on the current machine, and giving the data stream the filehandle TMP. To do this, use:

open(TMP, "| cmd");

Similarly, to take the output of a command as a stream, simply place the pipe symbol the other side of the command name:

open(TMP, "cmd |");

Worked example

Write a Perl script to take a string as first argument, then read standard input and copy all lines containing that string to standard output.
Solution: This is a job for fgrep. The ARGV array contains the string as its first element. Construct the command fgrep with the string as its argument (note that since the string may contain spaces, you need to enclose the argument in single quotes). Open a pipe into the command, and loop through the lines of standard input, not forgetting to close the file after use. The output of fgrep by default goes to standard output, so a second pipe is unnecessary. Closing the filehandle is required even though no named file is used.

# Set the value of variable string to the first argument
$string=$ARGV[0];

# Create a shell command to search for that string
$command="fgrep '$string'";

# Open a pipe to that command
open(FGREP, "| $command");

# Repeatedly real lines from standard input ...
while (<STDIN>) {
  # ... and send them to the pipe
  printf FGREP $_;
  }

# Finally, close the pipe
close(FGREP);

Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck