Introducing UNIX and Linux |
PerlOverview |
PipesA similar method of working allows access to pipes. Suppose we
wish to open a pipe to filter data into a command
( 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 exampleWrite a Perl script to take a string as first argument, then
read standard input and copy all lines containing that string to
standard output.
# 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