Sunday, April 26, 2015

Recursive code to loop through subfolders

code for the following question:
"How to recursively show all the files in a folder including those in the subfolders with recursion?"
# use "my" declacration is a must for recursion
use strict;
our $wd = shift @ARGV || ".";
print "Now is scaning $wd\n";

# a recursive function to list all files
sub travelpath 
{
    my ($directory) = @_;
 #print "current is: $directory\n";
 
 #Exclue the case where $direcotory is a file rather than drectory
    return if not -d $directory;
 
 opendir (my $DIR, $directory);
 
 while (my $file = readdir($DIR)) 
 {
  next if $file eq '..' or $file eq '.';
  print "$file\n";
  travelpath("$directory/$file");
 }
    close $DIR;
    return;
}


travelpath($wd);