Perl 在 while 循环中挂起

Sus*_*Boy 2 perl while-loop

while (<>) { $file .= $_};该代码由于某种原因挂起,或者在查询时不再继续执行。这是为什么?

一旦我用输入的文本启动代码,就不会发生比它输出的更多的事情task1,然后它就会挂起。

代码:

#!/usr/bin/perl -w

use strict;
use JSON;

my $json = JSON->new->allow_nonref;
my $file = "";

print('task1');

while (<>) { $file .= $_ };

print('task2');

my $json_output = $json->decode( $file );
my ($c, $i, $cstr, $istr);
foreach my $cert (@$json_output)  {

        print('task3');
        $i = $json_output->{i};
        $c = $json_output->{c};

        $istr = join("", map { sprintf("%02x",$_) } @$i);
        $cstr = pack("C*", @$c);
        open(F, ">$istr.der"); print F $cstr; close(F);
        print('done.');

}

Run Code Online (Sandbox Code Playgroud)

输出:

task1
Run Code Online (Sandbox Code Playgroud)

And*_*ter 5

这条线

while (<>) { $file .= $_ };
Run Code Online (Sandbox Code Playgroud)

正在尝试从命令行上指定的文件读取,或者如果没有,则从标准输入读取。如果没有任何内容通过管道传输到标准输入,那么它就会等待您在键盘上键入内容。

所以我猜测您没有在命令行上指定文件,并且您的程序正坐在那里等待从标准输入获取输入。

此外,将整个文件读入单个变量的更简单方法如下:

my $file = do { local $/; <> };
Run Code Online (Sandbox Code Playgroud)

有关其他选项,请参阅本文。