Hi,
I want to find out if "do there exist any *.test files in a certain directory" on a certain set of directories.
Given: sub myglob { my @g = glob shift; @g }
What is the difference between these two statements:
?if (glob "$dir/*") { print "glob $dir: yes\n"; } if (myglob "$dir/*") { print "myglob $dir: yes\n"; }
They both work the "first time" they are invoked, but if I have a loop to check more than one directory, 'glob' works at first EVERY OTHER call; here is a whole program:
#!/usr/bin/perl -w sub glob2 { glob(shift); } sub myglob { my @g = glob(shift); @g } use strict; use diagnostics; my @dirs = ('dir1', 'dir2', 'dir3', 'dir4', 'dir5', 'dir6'); #my @dir_x = '~'; my @dir_x = '/bin'; #my @dir_x = '/dir-fake-root'; my @fakedirs = ('dir-fake1', 'dir-fake2'); map { mkdir($_,0777) ; local *F; open(F,">$_/x.test") && close(F) || d +ie; } @dirs; for my $dir (@dirs, @fakedirs, @dir_x, @dirs, @fakedirs) { print "$dir/*: "; if (myglob("$dir/*")) { print "myglob "; } if (glob ("$dir/*")) { print "glob "; } if (glob2 ("$dir/*")) { print "glob2 "; } print "\n"; } map { unlink("$_/x.test") || die; rmdir($_) || die; } @dirs;
On both v5.6.1 cygwin and v5.005_03 linux, perl produces these results:
dir1/*: myglob glob glob2 dir2/*: myglob dir3/*: myglob glob glob2 dir4/*: myglob dir5/*: myglob glob glob2 dir6/*: myglob dir-fake1/*: dir-fake2/*: /bin/*: myglob glob glob2 dir1/*: myglob glob glob2 dir2/*: myglob glob glob2 dir3/*: myglob glob glob2 dir4/*: myglob glob glob2 dir5/*: myglob glob glob2 dir6/*: myglob glob glob2 dir-fake1/*: glob glob2 dir-fake2/*: glob glob2
As you can see, glob2 behaves like glob in all respects. myglob always works correctly. Before globbing /usr/*, glob correctly globs an existing directory every other call, and correctly doesn't find nonexistant directories.
After globbing /usr/*, glob then reports 'true' to every directory, even nonexistant ones (however, globbing /nonexistant-dir/* instead of /usr/* would kept glob working as it did the first time).
So what is the difference between the myglob defined here and regular glob? This is probably a caveat in perl scoping or contexts that I don't know about - I just learned perl last week to write a testsuite. And is there a better way to check for existance of any files in a given directory (opendir/readdir maybe)?
--thanks
Edit: chipmunk 2001-07-18
In reply to glob weirdness / list contexts? by giantfish
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |