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

how can I get an array with all the files seen in a directory? I'm on Windows.

Replies are listed 'Best First'.
Re: array of files in directory
by zer (Deacon) on Mar 14, 2006 at 02:08 UTC
    this is something i had to deal with before when writing a script on a windows test server... then switching it to unix... (a bad move not recomended)

    The problem i faced was that the -d option didnt work on windows. i did it by looking at the numbers of stat... the second field "file mode" does the trick. When i switched to nix i had to change the numbers and that was it

    #!/usr/bin/perl my @allfiles; $dir = "..\\"; opendir (THISDIR, $dir) or die "Can't read dir"; @temp = grep { not /^[.][.]?\z/ } readdir THISDIR; foreach $l(@temp){ (@status[0..12]) = stat($dir.$l); if ($status[2] == 16895){ #windows dir will $alldir[++$#alldir] = $l; print "\nDirectory = $l"; }else{ print "\nFile = $l"; } }

    i know there is a better solution but this was my make fast one. Note that this does not deal with symbolic links

Re: array of files in directory
by sulfericacid (Deacon) on Mar 14, 2006 at 01:55 UTC
    Make use of readdir().
    my $dir = "."; opendir(DIR,$dir) or die "Error: $!"; my @files = readdir(DIR) or die "Error: $!"; closedir(DIR); print @files;


    "Age is nothing more than an inaccurate number bestowed upon us at birth as just another means for others to judge and classify us"

    sulfericacid
Re: array of files in directory
by spiritway (Vicar) on Mar 14, 2006 at 02:04 UTC

    Check out perldoc perlfunc for starters, to find the builtins that allow you to access files and directories. Also check out Super Search. Finally, check out the vital How (Not) To Ask A Question. This helpful article will explain how to ask a question so that people will be more likely to answer it. Basically, people want to see that you did some work, tried something out - or that you tried looking for the information somewhere.

Re: array of files in directory
by smokemachine (Hermit) on Mar 14, 2006 at 03:16 UTC

      I was thinking glob, which is what implements the above behaviour, but then got distracted and forgot to post. However, upon seeing this, I must recommend glob over the <> operator. For starters, it's way clearer. The <> operator is already overloaded for the much more common "read from filehandle" use, so people seeing this would be easily confused, or at least have to take a second or two to recall this odd usage.

      Also, the <> operator has some weird properties when dealing with spaces and such where the glob function doesn't.

      @files = glob '*';