문제

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 $?;

다른 팁

Maybe IPC::Open2 didn't work so well on Windows 15 years ago, but I wouldn't expect you to have any trouble with it now.

use IPC::Open2;
my $pid = open2( \*SORT_OUT, \*SORT_IN, 'sort' );
print SORT_IN $sort_input;  # or  @sort_input
close SORT_IN;
print "The sorted output is: ", <SORT_OUT>;
close SORT_OUT;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top