Lines that don't execute well when they die in a foreach loop

I just have strange behavior that I would like to understand.

Here is my perl script where I just check for multiple folders:

#!/usr/bin/env perl
use warnings;

$root = "C:\\Data\\Tests";
@check = ("folder1", "folder2", "folder3");
foreach $check (@check){
    print $check;
    print -d "$root\\$check" ? " OK\n" : die " NOK : not accessible";
}

      

Now, suppose folder3 is missing, so I should have the output:

folder1 OK
folder2 OK
folder3 NOK : not accessible at C:\Data\Tests\strange.pl line 8.

      

Instead, I:

folder1 OK
folder2 OK
 NOK : not accessible at C:\Data\Tests\strange.pl line 8.
folder3

      

So it looks like in the last loop, the second line is executed before the first.

Does anyone know why?

+3


source to share


2 answers


So it looks like in the last loop, the second line is executed before the first.

Does anyone know why?

die ".."

as opposed to print

going intoSTDERR



Also, the output is buffered, so you can turn it off to get the output you want,

STDOUT->autoflush();
STDERR->autoflush();

      

+11


source


You should only use one print statement, for example:



#!/usr/bin/env perl
use warnings;

$root = "C:\\Data\\Tests";
@check = ("folder1", "folder2", "folder3");
foreach $check (@check){
    print -d "$root\\$check" ? "$check OK\n" : die "$check NOK : not accessible";
}

      

0


source







All Articles