Search code examples
perlforeachdie

Lines not executed in the good order while dying in foreach loop


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

Here is my perl script, where I just check if some folders are present :

#!/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, assume that 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 have :

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..

Someone knows why ?


Solution

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

    Someone knows why ?

    die ".." unlike print goes to STDERR

    Furthermore output is buffered so you might want to disable it in order to get wanted output,

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