How to list directories in Perl

Home > Search > How-to
  by

The following perl script will list every file listed in the specified directory.

opendir(DIR, "/path/to/directory") or die "cannot open directory";
@files = readdir(DIR);
closedir DIR;

print "@files \n";

 


Only list certain files (grep)

Grep can be used to only list certain files in the directory. In this example, only txt files will be printed.

opendir(DIR, "/path/to/directory") or die "cannot open directory";
@files = grep {/.txt/} readdir(DIR);
closedir DIR;

print "@files \n";

 


Exclude hidden files

To exclude hidden files, you want to exclude files that begin with a period. To do this, use grep with a regular expression to not list files that begin with a period.

opendir(DIR, "/path/to/directory") or die "cannot open directory";
@files = grep {!/\./} readdir(DIR);
closedir DIR;

print "@files \n";

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments