Perl: How to List All Files in a Directory

Perl makes life easy! In short lines of code it can make any task easier which otherwise looks arduous to do. At times we need to print a list of all the files present in a folder. It is a very basic task and Perl does it in a blink.

READ ALSO: Make list of all files in a folder using MS DOS commands

Yesterday, I needed to make a list of all the files present in a folder except a couple of files. If you also need to accomplish a similar task, you can use the following piece of Perl code:

my $directory = shift;
opendir(d, "$directory") || die "Can't open $directory: $!\n";
my @flist = readdir(d);
closedir(d);
foreach my $f (@flist) {
  print "\$file = $f\n";
}

Save this code in a file, let’s say, myfile.pl

Now you can run this Perl script while giving the path of the directory as first parameter.

perl myfile.pl “c:\project”

First line of the code will extract the first parameter and store it in the $directory variable. The second line tries to open the provided directory. Third line reads the content of opened directory into an array @flist. Fourth line in this Perl code closes the directory. And then a for loop lists the content of @flist array.

I hope it was useful for you. Please feel free to ask if you have any questions on this topic. I will be happy to try and help you. Thank you for using TechWelkin.

1 thought on “Perl: How to List All Files in a Directory”

  1. Hello,
    Nice Blog and post. I’m new in Perl and I need to list all file contained in a directory and write them in a text file, and when the file has had a determinate size that it can rename and create automaticaly a new file with the current date and hour.

    Is that possible?
    Thanks
    Obed

Leave a Comment

Your email address will not be published. Required fields are marked *