Perl : Read directory until a file is there
<p>I am writing a simple program to check for existence of file in a directory. The file is created by some external program with no uniform time. So, I need to check for the existence of file in a loop as I need to process it as soon as it borns.</p>

<p>This program runs continuously, even if the file has been created.</p>

<pre><code>#!/usr/bin/perl
use strict;
use warnings;


my $dir = "/my/path";
opendir( my $dh, $dir ) || die "can't opendir $dir: $!";
my @files = grep { /^[^\.]/ &amp;&amp; -f "$dir/$_" } readdir($dh);
until (@files) {
    print "No files Found: Sleeping for a sec\n";
    sleep(1);
    @files = grep { /^[^\.]/ &amp;&amp; -f "$dir/$_" } readdir($dh);
}
print @files;
</code></pre>

<p>The below program worked as expected.</p>

<pre><code>#!/usr/bin/perl
use strict;
use warnings;


my $dir = "/my/path";
opendir( my $dh, $dir ) || die "can't opendir $dir: $!";
my @files = grep { /^[^\.]/ &amp;&amp; -f "$dir/$_" } readdir($dh);
closedir $dh;
until (@files) {
    opendir( my $dh, $dir ) || die "can't opendir $dir: $!";
    print "No files Found: Sleeping for a sec\n";
    sleep(1);
    @files = grep { /^[^\.]/ &amp;&amp; -f "$dir/$_" } readdir($dh);
    closedir $dh;
}

print @files;
</code></pre>

<p>I want to know difference between both of these two approaches. Why the former one didn't work even though I am reading the directory every time in a loop. Why I need to open the directory every time in a loop to make it work?</p>