Perl 在 while 循环中挂起

标签 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.');

}

输出:

task1

最佳答案

这一行

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

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

所以我猜你没有在命令行上指定一个文件,你的程序就坐在那里等待从标准输入中获取输入。

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

my $file = do { local $/; <> };

参见 this article其他选项。

关于Perl 在 while 循环中挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70498099/

相关文章:

Perl - 将 PC UTF-8 转换为 PC ANSI

perl - 为什么常量不会自动继承?

java - while 循环内不会打印行

c++ - 具有随机数的无限 while 循环

Perl - 无法为子类创建类变量

perl - 在 Freebsd 中安装 perl 软件包时出错?

c++ - 在 C++ 中,我需要创建一个程序,当输入某个数字时循环并停止,然后显示最大值和最小值

Java while 循环处理 netbean 错误

c - While 循环未正确迭代

xml - Perl LibXML 打印额外的 "text"标签