Sprad has asked for the wisdom of the Perl Monks concerning the following question:

I can't for the life of me figure this one out.

I'm writing some code to search through a series of directories and return the name of the one and only .txt file inside each one. For some reason, though, my variable is only being set correctly every othertime the code runs. It doesn't matter if I search the same directory several times, or different ones. It always fails every other time. Here's a simplified version and its output on my system:

@paths = ( "//johnsp/dist", "//johnsp/dist", "//johnsp/dist", "//johnsp/dist", "//johnsp/dist", "//johnsp/dist" ); foreach $dir (@paths) { my $tmp; print "looking in $dir\n"; $tmp = glob("$dir/*.txt"); print glob("$dir/*.txt"), "\n"; print "set tmp to $tmp\n\n"; } Output: looking in //johnsp/dist //johnsp/dist/x86.txt set tmp to //johnsp/dist/x86.txt looking in //johnsp/dist //johnsp/dist/x86.txt set tmp to looking in //johnsp/dist //johnsp/dist/x86.txt set tmp to //johnsp/dist/x86.txt looking in //johnsp/dist //johnsp/dist/x86.txt set tmp to looking in //johnsp/dist //johnsp/dist/x86.txt set tmp to //johnsp/dist/x86.txt looking in //johnsp/dist //johnsp/dist/x86.txt set tmp to

Any guesses?

---
A fair fight is a sign of poor planning.

Replies are listed 'Best First'.
Re: Glob Misbehavin'
by no_slogan (Deacon) on Jun 14, 2001 at 01:45 UTC
    Even if you know there's only one .txt file in the directory, you still need to call glob in an array context
    my @txt = glob("$dir/*.txt");
    ... or a loop
    while ( defined(my $txt = glob("$dir/*.txt")) ) { }
    When you call glob in a scalar context, it returns the file the first time, then returns nothing the next time to let you know there are no more files.
      or - to be able to use the scalar variable and not having to change the rest of the program

      my ($txt) = glob("$dir/*.txt");

      -- Hofmator

Re: Glob Misbehavin'
by LD2 (Curate) on Jun 14, 2001 at 02:13 UTC
    From merlyn's book (Learning Perl)..pg. 23

    glob works much like <STDN>, in that each time it is accessed, it returns the next value. When there are no additional filenames to be returned, the filename glob returns an empty string.

    Since there is only one file to be found - it will default to an empty string the second time.