in reply to How do I read all the file names of a directory into an array?

Use the directory functions: opendir, closedir and readdir.

opendir DIR, $dir or die "cannot open dir $dir: $!"; my @file= readdir DIR; closedir DIR;

This will neatly put the list of file names in the @file array (with no \n at the end of each file name).

There is a couple of other things you can improve in your code BTW:

Finally I have no idea why $filename$i =~ s/\*//g; is there? Is there a chance you that you might find a '*' in filenames?

  • Comment on Re: How do I read all the file names of a directory into an array?
  • Download Code

Replies are listed 'Best First'.
Re: Answer: How do I read all the file names of a directory into an array?
by Ri-Del (Friar) on Dec 10, 2000 at 19:47 UTC
    Wow! Everyone thank you ever so much for your help, I've been learning so much! Yes, there is a chance I will find a '*' in the filenames. For some reason when I am connected to my department's server (running RedHat 7.0) and I 'ls' a directory some of the files (not all of them) have a '*' after their name. I'm not quite sure why, but I knew I needed to get rid of them to craft the link correctly for the webpage.
      That's a perfect example of why you should be reading the directory listing from within Perl (i.e. the opendir/readdir solution), rather than using a non-portable external command.

      On the department's server, `ls` is aliased to `ls -F`. The -F option causes ls to add * to executables, / to directories, and @ to symbolic links. Useful when looking at a directory listing from the command prompt; not useful when getting a list of filenames within Perl.

      I believe that the reason there are *'s after some files is because ls is aliased to ls -F, which will add a * to the end of files that are executeable. It will also add some other characters onto files that are directories, symlinks, etc.... You won't run into that using readdir though. Hope this helps!

      - Brad