Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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";
    }
like image 942
ImDrPatil Avatar asked Oct 29 '25 02:10

ImDrPatil


1 Answers

use File::Find;

use strict;
use warnings;

my @dirs;
my %has_children;

find(sub {
    if (-d) {
        push @dirs, $File::Find::name;
        $has_children{$File::Find::dir} = 1;
    }
}, 'D:/Temp');

my @ends = grep {! $has_children{$_}} @dirs;

print "$_\n" for (@ends);
like image 143
Miller Avatar answered Oct 30 '25 18:10

Miller