How to read directories and sub-directories without knowing the directory name in perl?

Viewed 1389

Hi i want to read directories and sub-directories without knowing the directory name. Current directory is "D:/Temp". 'Temp' has sub-directories like 'A1','A2'. Again 'A1' has sub-directories like 'B1','B2'. Again 'B1' has sub-directories like 'C1','C2'. Perl script doesn't know these directories. So it has to first find directory and then read one file at a time in dir 'C1' once all files are read in 'C1' it should changes to dir 'C2'. I tried with below code here i don't want to read all files in array(@files) but need one file at time. In array @dir elements should be as fallows.

$dir[0] = "D:/Temp/A1/B1/C1"
$dir[1] = "D:/Temp/A1/B1/C2"
$dir[2] = "D:/Temp/A1/B2/C1"

Below is the code i tried.

    use strict;
    use File::Find::Rule;
    use Data::Dumper;

    my $dir = "D:/Temp";
    my @dir = File::Find::Rule->directory->in($dir);
    print Dumper (\@dir);
    my $readDir = $dir[3];
    opendir ( DIR, $readDir ) || die "Error in opening dir $readDir\n";
    my @files = grep { !/^\.\.?$/ } readdir DIR;
    print STDERR "files: @files \n\n";

    for my $fil (@files) {
        open (F, "<$fil");
        read (F, my $data);
        close (F);
        print "$data";
    }
5 Answers
Related