Rhandom has asked for the wisdom of the Perl Monks concerning the following question:

Without going into details, I would like to munge reading from STDIN and writing to STDOUT into one handle. I have tried writing my own IO::Handle sub class but haven't been able to get it to deal with <$handle> and print $handle "blah\n" simultaneously. Preferably I would like to avoid forking (I know that I can fork and get it to work with some effort). I would essentially like to do something like the following:
use MyIO::Handle (); my $io = MyIO::Handle->new(); # ISA IO::Handle $io->fdopen(fileno(STDIN), 'r'); $io->fdopen(fileno(STDOUT),'w'); # don't block over STDIN my $line = <$io>; print $io "You said $line";
Any ideas, or is it really even feasible?

Replies are listed 'Best First'.
Re: Munging STDIN and STDOUT into one handle
by japhy (Canon) on Feb 13, 2001 at 22:51 UTC
    You can do things like:
    package TwoWayHandle; sub TIEHANDLE { my ($class, $in, $out) = @_; bless [ \$in, \$out ], $class; } sub PRINT { my $self = shift; local *FH = ${ $self->[1] }; print FH @_; } sub READLINE { my $self = shift; local *FH = ${ $self->[0] }; <FH>; } 1;
    And then use it as:
    use TwoWayHandle; tie *ACDC, TwoWayHandle => ( *STDIN, *STDOUT, ) or die "can't tie *ACDC: $!"; print ACDC "What's your name? "; $name = <ACDC>; chomp $name; print ACDC "Hello, $name.\n";
    Not sure why, but I can't call chomp() at the same time I read from the filehandle.

    japhy -- Perl and Regex Hacker
Re: Munging STDIN and STDOUT into one handle
by chromatic (Archbishop) on Feb 13, 2001 at 22:53 UTC
    You could tie a handle, providing a READ method that reads from STDIN and a PRINT method that writes to STDOUT.

    That's about the simplest approach I can think of, especially if you subclass Tie::Handle.