Perl: How to List All Files in a Directory

Few lines of Perl code can produce the list of all the files that are present in a given directory. Learn how.
6SHARES

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.

6SHARES
See Comments