Perl (Scripting) - List directories

by
Jeremy Canfield |
Updated: March 09 2020
| Perl (Scripting) articles
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";
Did you find this article helpful?
If so, consider buying me a coffee over at