![](/img/trans.png)
[英]How can I tell if a set of parens in Perl code will act as grouping parens or form a list?
[英]perl how to capture STDOUT of list form system call as a filehandle
下面的原型演示如何能夠捕捉STDOUT
一個“工人”劇本,由“老板”腳本調用,為FILEHANDLE
,把內容FILEHANDLE
到一個數組中,人們可以在“老大”腳本操作。 boss腳本junk.pl
:
#!/usr/bin/perl
use strict; use warnings;
my $boppin;
my $worker = "junk2.pl";
open(FILEHANDLE, "$worker |");
my @scriptSTDOUT=<FILEHANDLE>;
close FILEHANDLE;
my $count=0;
foreach my $item ( @scriptSTDOUT ) {
$count++;
chomp $item;
print "$count\t$item\n";
}
if ( @scriptSTDOUT ) {
$boppin = pop @scriptSTDOUT; print "boppin=$boppin\n";
} else {
print STDERR "nothing returned by $worker\n";
}
my @array = ( '. . . \x09 wow\x21' , 5 );
system $worker, @array;
和“工人” junk2.pl
:
#!/usr/bin/perl
use strict; use warnings; use 5.18.2;
print "$0";
如果$worker
不需要其元素包含空格的數組作為參數,則使用open
和定義FILEHANDLE
是可以的。 但是,如果需要如此復雜的參數,則必須以列表形式調用“worker”腳本,如“boss”腳本的底部。 對於“列表形式”,請參閱使用多個參數調用 shell 命令。
在這種情況下,如何將STDOUT
捕獲為FILEHANDLE
? 如何修改“老板”腳本的底線來實現這一點?
有一種更簡單的方法,它是使用IPC::Run
使用像這樣的簡單代碼
use strict;
use warnings;
use IPC::Run qw(run);
my $in = ""; # some data you want to send to the sub-script, keep it empty if there is none
# the data will be received from the STDIN filehandle in the called program
my $out = ""; # variable that will hold data writed to STDOUT
my $err;
run ["perl", "junk2.pl"], \$in, \$out, \$err;
可以繼續使用open
如下:
open(my $child, "-|", $prog, @args)
or die("Can't launch \"$prog\": $!\n");
my @lines = <$child>;
close($child);
die("$prog killed by signal ".( $? & 0x7F )."\n") if $? & 0x7F;
die("$prog exited with error ".( $? >> 8 )."\n") if $ ?>> 8;
警告:如果@args
為空,上面將把$prog
的值視為一個 shell 命令。
通用IPC::Run也可以在這里使用。
use IPC::Run qw( run );
run [ $prog, @args ],
'>', \my $out;
die("$prog killed by signal ".( $? & 0x7F )."\n") if $? & 0x7F;
die("$prog exited with error ".( $? >> 8 )."\n") if $ ?>> 8;
my @lines = split(/^/m, $out);
還有Capture::Tiny ,它提供了一個用於捕獲 STDOUT 和 STDERR 的極簡界面。
請注意,您可以使用String::ShellQuote的shell_quote
為sh
構建命令。
use String::ShellQuote qw( shell_quote );
my $cmd = shell_quote("junk2.pl", @array);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.