Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re^5: Using grep and glob to find directories containing file

by 7stud (Deacon)
on Feb 03, 2013 at 18:03 UTC ( #1016846=note: print w/ replies, xml ) Need Help??


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.


Comment on Re^5: Using grep and glob to find directories containing file
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1016846]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (5)
As of 2014-10-25 03:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (141 votes), past polls