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.
SHARE

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.

Yesterday, I needed to make a list of all the files in a folder except a couple of files. To accomplish a similar task, you can use the following piece of 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";
}

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

perl myfile.pl “c:\project”

The first line of code will extract the first argument 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 closes the directory. Then a for loop lists the content of @flist array.

Leave a Reply

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