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.
			push(@folders,$item);
		} else { #If it is a file just put it into the final array.
			push(@all,$item);
		}
	}

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

		#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) {
			push(@all,"$this_folder/$item");
		}
	}
	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.

Comments

Comment

Please dont enter you comments in this form - this is a fake form to confuse spamming bots. The next form is the real one.




Comment




Comment Formating : HTML tags a, strong, em, b, i, code, pre, p and br allowed. Other tags will be shown as code(< will become &lt;). Urls, Line breaks will be auto-formated.
Subscribe to Feed