16.5. Filtering Your Own OutputProblemYou want to postprocess your program's output without writing a separate program to do so. Solution
Use the forking form of head(100); while (<>) { print; } sub head { my $lines = shift || 20; return if $pid = open(STDOUT, "|-"); die "cannot fork: $!" unless defined $pid; while (<STDIN>) { print; last unless --$lines ; } exit; } DiscussionIt's easy to add an output filter. Just use the forking open on your own STDOUT, and let the child filter STDIN to STDOUT, performing whatever alterations you care about. Notice that we install the output filter before we generate the output. This makes sense - you can't filter your output if it has already left your program. Any such filters should be applied in LIFO order - the last one inserted is the first one run. Here's an example that uses two output filters. One numbers lines; the other quotes the lines like a mail reply. When run on /etc/motd , you get something like:
If you reversed the order of the two filters, you'd get:
The program is in Example 16.1 . Example 16.1: qnumcat#!/usr/bin/perl # qnumcat - demo additive output filters number(); # push number filter on STDOUT quote(); # push quote filter on STDOUT while (<>) { # act like /bin/cat print; } close STDOUT; # tell kids we're done--politely exit; sub number { my $pid; return if $pid = open(STDOUT, "|-"); die "cannot fork: $!" unless defined $pid; while (<STDIN>) { printf "%d: %s", $., $_ } exit; } sub quote { my $pid; return if $pid = open(STDOUT, "|-"); die "cannot fork: $!" unless defined $pid; while (<STDIN>) { print "> $_" } exit; } As with all process forks, doing this a zillion times has some cost, but it's fine for a couple of processes, or even a couple dozen. If the system was actually designed to be multitasking right from the start, as Unix was, this is far cheaper than you imagine. Virtual memory and copy-on-write makes this efficient. Forking is an elegant and inexpensive solution to many, if not most, multitasking needs. See Also
The
Copyright © 2001 O'Reilly & Associates. All rights reserved. |
|