【问题标题】:Perl IO::Pipe does not work within arraysPerl IO::Pipe 在数组中不起作用
【发布时间】:2013-06-27 19:34:35
【问题描述】:

我正在尝试以下方法:

我想分叉多个进程并同时使用多个管道(子 -> 父)。 我的方法是使用 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] 没有按预期工作(与数组一起)。

我真的不知道为什么。有人知道解决方案吗?非常感谢您的帮助!

【问题讨论】:

    标签: arrays perl fork pipe


    【解决方案1】:

    你的问题在这里:

    print $ua_pipe[0] $response->decoded_content;
    

    printsay 内置函数使用间接语法 来指定文件句柄。这仅允许单个标量变量或裸字:

    print STDOUT "foo";
    

    print $file "foo";
    

    如果您想通过更复杂的表达式指定文件句柄,则必须将该表达式括在花括号中;这被称为与格

    print { $ua_pipe[0] } $response-decoded_content;
    

    现在应该可以正常工作了。


    编辑

    我忽略了&lt;$ua_pipe[0]&gt;。 readline 运算符&lt;&gt; 也兼作glob 运算符(即对*.txt 等模式进行shell 扩展)。在这里,与sayprint 相同的规则适用:如果文件句柄是裸字或简单的标量变量,它只会使用文件句柄。否则,它将被解释为 glob 模式(暗示参数的字符串化)。消除歧义:

    • 对于 readline &lt;&gt;,我们必须求助于 readline 内置:

      while (readline $ua_pipe[0]) { ... }
      
    • 要强制通配&lt;&gt;,传递一个字符串:&lt;"some*.pattern"&gt;,或者最好使用glob 内置函数。

    【讨论】:

    • 那么,“while () { ...”只给了我“IO::Pipe::End=GLOB(0x6df0f0)”...跨度>
    • 同样的事情——&lt;$handle&gt; 语法仅适用于“简单”文件句柄参数。请改用while (readline($ua_pipe[0])) { ...
    • @at0m33 哦,抱歉,我忽略了这一点。我刚刚对我的答案进行了编辑,但是 mob 的评论是一个很好的总结。
    • 卷曲对&lt;&gt; 运算符没有帮助。你必须使用readline或者先把复杂的表达式赋值给一个简单的表达式(我犯了这个错误morethan once)。
    • 对于阅读,您还可以使用IO::Handle API 中的$ua_pipe[0]-&gt;getline
    猜你喜欢
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 2013-09-27
    • 2015-01-01
    • 1970-01-01
    相关资源
    最近更新 更多