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

Hey monks, I'm trying to read some files into an array, which I think uses the built in Glob function of perl.  @files = <$file_directory/outgoing/$new_files*.txt>; A strange thing happens that when it enters the function the first time, it goes just fine, the second time (with different variables) it returns blank. Any ideas...i.e. does Glob only run at the start of a program with the initial variables? Thanks

Replies are listed 'Best First'.
Re: Globbidy glob glob glob
by Somni (Friar) on Oct 11, 2007 at 10:04 UTC
    It's returning "blank" (I'm guessing this means @files is empty) because no files matched. It's probably simply due to what you changed the variables to. Perhaps the path is relative and something called chdir, or the values you passed were expecting a different working directory.

    Double-check what the variables are set to. If the path is relative make sure the current directory is what you expect. Make sure you have read permission for $file_directory/outgoing, and execute permission for all of the directories leading up to it.

    Also, please, for the sanity of everyone having to read your code, use glob("$file_directory/outgoing/$new_files*.txt") instead of angle brackets.

      Furthermore, check that the final glob pattern ("$file_directory/outgoing/$new_files*.txt") contains no spaces. The glob function, by default, treats spaces specially: it splits the string at spaces into one or more patterns.

      C:\>perl -w -e "print qq($_\n) for glob('C:\Documents and Settings\*') +" C:./Documents and
      A word spoken in Mind will reach its own level, in the objective world, by its own weight
Re: Globbidy glob glob glob
by ysth (Canon) on Oct 11, 2007 at 23:59 UTC
    I have just a sneaking suspicion that may not be doing quite what you say you are. Above, you show using <> aka glob() in list context. It should work fine the second time with different variables. Since it doesn't, I'm guessing you are actually using scalar context.

    glob, in scalar context, acts as an iterator; it returns one result at a time and undef to signal no more results. If a single call to glob in your perl code has a variable parameter, as in your example, the actual value is only noticed the first time it's called (or the time after returning undef).

    Moral: don't use glob in scalar context. Or if you do, make sure your code will always exhaust the iterator before starting a fresh iteration.

    (The other possibility is that your variables are not what you think they are.)