I'm executing a system command, and wanting to (1) pre-load STDIN for the system command and (2) capture the STDOUT from the command.
Per here I see I can do this:
open(SPLAT, "stuff") || die "can't open stuff: $!";
open(STDIN, "<&SPLAT") || die "can't dupe SPLAT: $!";
print STDOUT `sort`;
This uses the currently defined STDIN as STDIN for the sort. That's great if I have the data in a file, but I have it in a variable. Is there a way I can load the contents of the variable into STDIN before executing the system command? Something like:
open(STDIN, "<$myvariable"); # I know this syntax is not right, but you get the idea
print STDOUT `sort`;
Can this be done without using a temp file? Also, I'm in Windows, so Open2 is not recommended, I hear.
Thanks.
There's no reason not to use open2
on Windows. That said, open2
and open3
are rather low-level interfaces, so they're usually not the best choice on any platform.
Better alternatives include IPC::Run and IPC::Run3. IPC::Run is a bit more powerful than IPC::Run3, but the latter is a bit simpler to use.
May I recommend
use IPC::Run3 qw( run3 );
my $stdin = ...;
run3([ 'sort' ], \$stdin, \my $stdout);
It even does error checking for you.
But since you mentioned open2
,
use IPC::Open2 qw( open2 );
my $stdin =...;
my $pid = open2(\local *TO_CHILD, \local *FROM_CHILD, 'sort');
print TO_CHILD $stdin;
close TO_CHILD;
my $stdout = '';
$stdout .= $_ while <FROM_CHILD>;
waitpid($pid);
die $? if $?;