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

I'm having a problem passing a scalar containing a directory location into an array for loading the files within the directory. When I hard code the directory location into the function, everything works. When I assign the directory to loadup to a scalar, I don't get any files, even though I've confirmed the scalar is holding the correct location.
Is there some reason that you can't pass the location of a directory into an array?
#Works when I assign the directory from a string my @files = </Library/WebServer/Documents/*.txt>; #Does NOT work when I assign the directory from a variable my $Dir = '/Library/WebServer/Documents/*.txt'; my @files = <$Dir>; foreach my $item (@files) {
thanks!

Replies are listed 'Best First'.
Re: Pass variable as Directory
by Zaxo (Archbishop) on Aug 28, 2005 at 07:31 UTC

    davido is exactly right. You can use your $Dir as a filename pattern by saying instead, my @files = glob $Dir;

    After Compline,
    Zaxo

      Works. Works perfect. Many thanks guys.
Re: Pass variable as Directory
by davido (Cardinal) on Aug 28, 2005 at 07:27 UTC

    Here's the relevant section of perlop:

    If what's within the angle brackets is neither a filehandle nor a simple scalar variable containing a filehandle name, typeglob, or typeglob reference, it is interpreted as a filename pattern to be globbed, and either a list of filenames or the next filename in the list is returned, depending on context. This distinction is determined on syntactic grounds alone. That means <$x> is always a readline() from an indirect handle, but <$hash{key}> is always a glob(). That's because $x is a simple scalar variable, but $hash{key} is not--it's a hash element.

    One level of double-quote interpretation is done first, but you can't say <$foo> because that's an indirect filehandle as explained in the previous paragraph. (In older versions of Perl, programmers would insert curly brackets to force interpretation as a filename glob: <${foo}> . These days, it's considered cleaner to call the internal function directly as glob($foo), which is probably the right way to have done it in the first place.)


    Dave