A friend set me a pretty puzzle. Or at least, I enjoyed wrapping my
brain around it. He wanted to set up a pipeline of commands. For
various design constraint reasons, he didn't know in advance what
the commands were nor how many of them there were --- the whole
pipeline is constructed from external data. Further, he didn't want
to let a shell lay its fingers on the text of the args, he wanted to
do it directly. And lastly he's enjoying using the object-oriented
file I/O components.

There's surely More Than One Way To Do It, but here's what I came up
with.

        use IO::Pipe;

        my @cmds = (
            [ 'perl', '-le', 'print for 1..10' ],
            [ 'sort', '-r' ],
            [ 'sed', 's/^/-> /' ],
        );

        while (@cmds) {
            my $cmd = shift @cmds;
            my $pipe = IO::Pipe->new;
            my $pid = fork;
            die "I'm forked\n" unless defined $pid;
            if ($pid == 0) {
                STDOUT->fdopen($pipe->writer->fileno, "w");
                exec @{$cmd};
                die;
            }
            STDIN->fdopen($pipe->reader->fileno, "r");
        }
        print STDIN->getlines;

-Bennett

Attachment: pgp00000.pgp
Description: PGP signature

Reply via email to