http://www.perlmonks.org?node_id=1016846


in reply to Re^4: Using grep and glob to find directories containing file
in thread Using grep and glob to find directories containing file

foreach (1,2,3,4) { print "dir1\n" if glob("dir1/f*"); print "dir2\n" if glob("dir2/f*"); }
I get 'dir1' printed 3 times

I would think your code would print 'dir1' twice. In your second code example, there is no advancing iterator because you can double the number of print statements and you will get double the output.

Your first example doesn't tell the whole story. Look at this output:

use strict; use warnings; use 5.012; for my $i (1..10) { print "$i: "; if (my $x = glob "dir1/f*") { print "\t$x"; } if (my $y = glob "dir2/f*") { print "\t$y"; } print "\n"; } --output:-- 1: dir1/f1 2: dir1/f2 3: 4: dir1/f1 5: dir1/f2 6: 7: dir1/f1 8: dir1/f2 9: 10: dir1/f1

So it appears that inside a loop, once the iterator is exhausted, the next call to glob() returns undef, then the next call to glob() creates a new iterator(or resets the old iterator) and returns the first matching filename again.

You can run a similar test on your second example:

use strict; use warnings; use 5.012; if (my $x = glob "dir1/f*") { say $x; } if (my $x = glob "dir1/f*") { say $x; } if (my $x = glob "dir1/f*") { say $x; } if (my $x = glob "dir1/f*") { say $x; } if (my $x = glob"dir1/f*") { say $x; } --output:-- dir1/f1 dir1/f1 dir1/f1 dir1/f1 dir1/f1

No loop, no call to the iterator's next() method. So as is often the case, perl examines the context of the statement to determine its return value.