How to load STDIN for backtick in perl (without writing to temp file)

I execute a system command and want to (1) preload STDIN for the system command and (2) grab STDOUT from the command.

Per here. I see that I can do this:

open(SPLAT, "stuff")   || die "can't open stuff: $!";
open(STDIN, "<&SPLAT") || die "can't dupe SPLAT: $!";
print STDOUT `sort`;

In this case, STDIN is currently used as STDIN for sorting. This is great if I have data in a file, but I have it in a variable. Is there a way to load the contents of a variable into STDIN before executing a system command? Sort of:

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 temporary file? Also, I'm on Windows, so Open2 is not recommended, I hear.

Thank.

+3
source share
2 answers

open2 Windows. , open2 open3 , .

IPC::Run IPC::Run3. IPC:: Run , IPC:: Run3, .

use IPC::Run3 qw( run3 );
my $stdin = ...;
run3([ 'sort' ], \$stdin, \my $stdout);

.


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

, IPC::Open2 Windows 15 , , .

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;
+2

All Articles