Home > Blockchain >  Perl hangs up on while loop
Perl hangs up on while loop

Time:12-28

This code hangs up for some reason or just doesn't go any further when while (<>) { $file .= $_}; is queried. Why is that?

As soon as I start the code with the entered text does not happen more than that it outputs task1 and then it hangs.

Code:

#!/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("x",$_) } @$i);
        $cstr = pack("C*", @$c);
        open(F, ">$istr.der"); print F $cstr; close(F);
        print('done.');

}

Output:

task1

CodePudding user response:

This line

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

is trying to read from a file specified on the command line, or if there isn't one, from standard input. If there isn't anything piped to standard input, then it sits waiting for you to type something at the keyboard.

So I'm guessing you didn't specify a file on the command line, and your program is sitting there waiting to get input from standard input.

Also, the easier way to read in the entire file to a single variable is like so:

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

See this article for other options.

CodePudding user response:

How do you invoke your code? The <> operator means that it takes input from either all the files that you specify as arguments, or from standard input. If you call your script with no arguments, it will sit and wait for console input.

If you call it without arguments, try entering a few lines of text when it is "hanging", and then type Ctrl D if you are on Linux, or Ctrl Z on Windows. That should make the script work.

  • Related