[San-Diego-pm] Module idea for input/output multiplexing

Chris Grau chris at chrisgrau.com
Wed Dec 13 00:42:44 PST 2006

On Mon, Dec 11, 2006 at 10:48:36PM -0800, Emile Aben wrote:
> Module idea from discussion at the meeting tonight:
> A module that hooks up stdout from one process with the stdin of
> several other processes, or maybe more generic: Something that reads
> from a filehandle and writes that output to several other filehandles.

I like the tee(1) example in shell, but I was itching to write it in
Perl.  So here's what I came up with in the last half hour or so.

--[ print.pl ]----------------------------------------------------------

print "$ARGV[0]: $_" while <STDIN>;
--[ __END__ ]-----------------------------------------------------------

I only wrote print.pl because cat(1) buffers its output and so didn't
serve my example very well.

--[ multi.pl ]----------------------------------------------------------

use strict;
use warnings;

my $proc = Proc::Multiplex->new;

$proc->add('./print.pl one');
$proc->add('./print.pl two');

# sleep between writes to prove I/O isn't being buffered
sleep 1;
sleep 1;

package Proc::Multiplex;

sub new {
    bless { fh => [] };

sub add {
    my ( $self, $cmd ) = @_;

    open my $fh, '|-', $cmd or die "$cmd: $!";
    my $oldfh = select $fh; $| = 1; select $oldfh;
    push @{ $self->{fh} }, $fh;

sub write {
    my ( $self, $data ) = @_;

    print {$_} $data for @{ $self->{fh} };
--[ __END__ ]-----------------------------------------------------------

[cgrau at quendor ~]$ perl multi.pl 
two: foo
one: foo
one: bar
two: bar
one: baz
two: baz

Now it just needs a pinch of syntactic sugar and a dash of robustness.
Though, odds are something like this already exists on the CPAN.

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: not available
Url : http://mail.pm.org/pipermail/san-diego-pm/attachments/20061213/8e78da18/attachment.bin 

More information about the San-Diego-pm mailing list