Dir() - Recursive File Listing in Perl

Dir function can be used to list all the files in a given folder recursively.

I often had the need to list all files in a given folder. When I say 'all files', I don't mean just the files in that folder - but all the files in all folder under it. I wrote a small recursive function to do this. I had this requirement so many times that I have translated the code to almost all languages I know - I have this function in Perl, PHP, Ruby and Tcl.

Here is the perl part of the code...

# Function	: dir
# Arguments	: The path of the directory whose directory list you want
# Returns	: A flat list with the path of all the files in the directory given as the argument.
# This function will take a folder as the argument and go thru every it recursively and return the list of 
#		all files and folders in that folder.
sub dir {
	my $current_folder = shift;
	my @all;

	chdir($current_folder) or die("Cannot access folder $current_folder");

	#Get the all files and folders in the given directory.
	my @both = glob("*");

	my @folders;
	foreach my $item (@both) {
		if(-d $item) { #Get all folders into another array - so that first the files will appear and then the folders.
		} else { #If it is a file just put it into the final array.

	foreach my $this_folder (@folders) {
		#Add the directory name to the return list - comment the next line if you don't want this feature.

		#Continue calling this function for all the folders
		my $full_path = "$current_folder/$this_folder";

		my @deep_items = dir($full_path); # :RECURSION:
		foreach my $item (@deep_items) {
	return @all;

my @all  = dir("/home/binnyva/Scripts/Perl/");
foreach my $item (@all) { 
	print "--- $item ---\n";

This functionality is also available using the File::Find module available with any standard distribution. If you want to access more advanced features, use File::Find::Rule available from CPAN. The advantage of using my code is that you can modify the code to fit your purposes.

Subscribe to Feed