Dave's Brain

Browse - Programming Tips - What's the best way to read a directory/folder in perl?

Date: 2009may13
Language: perl

Q.  What's the best way to read a directory/folder in perl?
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(@files); local(*DIR); if (!opendir(DIR, $dir)) { return () } # Return an empty array on failure @files = 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 @files } sub exampleUse() { my($i); for $i (readDir('/etc/')) { print "$i\n"; } }
There is also the glob() function. There are libraries in CPAN but they add extract dependencies.

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.