[英]Perl IO::Pipe does not work within arrays
我嘗試以下內容:
我想分叉多個進程並同時使用多個管道(子->父)。 我的方法是使用IO :: Pipe。
#!/usr/bin/perl
use strict;
use IO::Pipe;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my @ua_processes = (0..9);
my $url = "http://<some-sample-textfile>";
my @ua_pipe;
my @ua_process;
$ua_pipe[0] = IO::Pipe->new();
$ua_process[0] = fork();
if( $ua_process[0] == 0 ) {
my $response = $ua->get($url);
$ua_pipe[0]->writer();
print $ua_pipe[0] $response->decoded_content;
exit 0;
}
$ua_pipe[0]->reader();
while (<$ua_pipe[0]>) {
print $_;
}
將來我想在數組中使用多個“ $ ua_process”。
執行后,出現以下錯誤:
Scalar found where operator expected at ./forked.pl line 18, near "] $response"
(Missing operator before $response?)
syntax error at ./forked.pl line 18, near "] $response"
BEGIN not safe after errors--compilation aborted at ./forked.pl line 23.
如果我不使用數組,則相同的代碼會完美地工作。 似乎只有$ ua_pipe [0]不能按預期工作(與數組一起使用)。
我真的不知道為什么。 有人知道解決方案嗎? 幫助將不勝感激!
您的問題在這里:
print $ua_pipe[0] $response->decoded_content;
print
和say
buildins使用間接語法指定文件句柄。 這僅允許單個標量變量或裸字:
print STDOUT "foo";
要么
print $file "foo";
如果要通過更復雜的表達式指定文件句柄,則必須將該表達式用curl括起來。 這稱為導語塊 :
print { $ua_pipe[0] } $response-decoded_content;
現在應該可以正常工作了。
我忽略了<$ua_pipe[0]>
。 readline運算符<>
也是glob
運算符的兩倍(即對*.txt
類的模式進行shell擴展)。 在這里,應用與say
和print
相同的規則:僅當它是裸字或簡單的標量變量時,才使用文件句柄。 否則,它將被解釋為全局模式(暗含參數的字符串化)。 消除歧義:
對於readline <>
,我們必須求助於內置的readline
:
while (readline $ua_pipe[0]) { ... }
要強制使用<>
,請向其傳遞一個字符串: <"some*.pattern">
,或者最好使用內置的glob
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.