Programming Tips - Perl: the best way to read a directory/folder

Date: 2009may13 Updated: 2023aug26 Language: perl Keywords: getDir Q. Perl: the best way to read a directory/folder I don't want to include the the dot and dot dot entries. A. Here's a nice function that reads a directory and returns an array:
sub readDir($) { my($dir) = @_; my(@nodes); # `nodes` rather than `files` because might be subdirs local(*DIR); if (!opendir(DIR, $dir)) { return () } # Return an empty array on failure @nodes = sort(grep(!/^(\.|\.\.)$/, readdir(DIR))); # Exclude special folders . and .. but not files that begin # with dot like .htaccess # Its nice to have the array sorted closedir(DIR); return @nodes; } sub exampleUse() { for my $i (readDir('/etc')) { print "$i\n"; } }
There is also the glob() function. There are libraries in CPAN but they add dependencies.