I don't understand what glob does here

D

Darren Dunham

I don't understand the behavior of the following...

$ touch "file"
$ perl -e 'foreach $num (0 .. 4) { print "$num .. "; print (scalar glob("file")); print " "; print (scalar glob("file")); { print " ok\n"; } }'
0 .. file file ok
1 .. ok
2 .. file file ok
3 .. ok
4 .. file file ok

I thought that if I were to get "undef" returned on the second scalar
invocation, I would have seen one "file" in each iteration, not 2
successful followed by 2 unsuccessful.

Why does the behavior change between iterations of the foreach loop
here? I've read through glob and File::Glob and I haven't seen anything
that appears to explain this.

Thanks.
 
P

Paul Lalli

Darren said:
I don't understand the behavior of the following...

$ touch "file"
$ perl -e 'foreach $num (0 .. 4) { print "$num .. "; print (scalar glob("file")); print " "; print (scalar glob("file")); { print " ok\n"; } }'
0 .. file file ok
1 .. ok
2 .. file file ok
3 .. ok
4 .. file file ok

I thought that if I were to get "undef" returned on the second scalar
invocation, I would have seen one "file" in each iteration, not 2
successful followed by 2 unsuccessful.

Why does the behavior change between iterations of the foreach loop
here? I've read through glob and File::Glob and I haven't seen anything
that appears to explain this.

Each individual glob() call maintains its own state. The first time
through the for loop is the first call to glob("file") for each glob()
statement. The second time through the loop is the second call to each
glob().

Each glob() only returns the "next" value (undef in the case of only
one match) for successive calls to the *same* glob() statement,
regardless of whether or not a different glob() statement has been
called with the same argument.

$ perl -le 'print (scalar glob("file")); print (scalar glob("file
"));print (scalar glob("file"));print (scalar glob("file"));'
file
file
file
file
$

$ perl -le 'print (scalar glob("file")) for 0..3'
file

file

$

Hope this helps,
Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top