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

I am trying to execute a small c utility (like sort, which is used in this example) from my perl script. I want to send data to it upfront. Then the utility will return the results.

The cookbook indicates that "Open2" will work for this type of "synchronous" usage. (I am using Win2000)

But my Perl script blocks w/o displaying anything...

Here is the Perl code I am using:
my ($reader, $writer) = (IO::Handle->new(), IO::Handle->new()); my $command = "sort /reverse"; eval { open2($reader, $writer, $command); }; if ($@) { warn "CRAP $! $@ \n"; } foreach (@data) { print $writer $_ ."\n"; } close ($writer); while ($_ = $reader->getline()) {print $_;} close ($reader); }
For debugging, I tried:
my $command = 'type test.dat | sort /reverse';
***This works***

What doesn't work is the Open2..$reader..$writer code...

I just can't figure out what is different...Does the shell handle this differently than Perl or is it EOF or CRLF or ???

Any HELP is REALLY appreciated, as I am probably missing a BIG "thing"

thanks!!!

Replies are listed 'Best First'.
Re: confused (and frustrated) about stdin/out
by kwoff (Friar) on Dec 03, 2001 at 03:51 UTC
    open2() is from the module IPC::Open2.
    From `perldoc IPC::Open2`:
    This whole affair is quite dangerous, as you may block forever. It assumes it's going to talk to something like bc, both writing to it and reading from it. This is pre­sumably safe because you "know" that commands like bc will read a line at a time and output a line at a time. Pro­grams like sort that read their entire input stream first, however, are quite apt to cause deadlock.
      We'll that's embarassing ;)

      Know of a command or module that would allow me to emulate the way sort works?

      -thanks
        You mean besides sort?
        # With each line in @unsorted @sorted = sort @unsorted; # With all lines in $unsorted, maybe use IO::String my $S = new IO::String \$unsorted; @sorted = sort <$S>; # Or just split on newlines, maybe reversed too: @sorted = reverse sort split $/, $unsorted;
        Consider File::Sort for anything more complex.