cs87
cs87

Reputation: 37

Perl , How to read subfolder Output

I am writing a script to read the content of multiple sub folder in a directory. And recently i need to read the content of folder inside multiple sub-folder. Want to ask how can i write the code to read those folder inside multiple sub-folder.

This is the new conditions
Multiple Sub-folder -> Local folder -> fileAAA.csv
how do i read this fileAAA in Local folder of Multiple Sub-folder?

Currently the code i am writing was in this condition and it works well.
Multiple Sub-folder -> fileAAA.csv
Able to read fileAAA from multiple Sub-folder

Below is the code i use to read
Multiple Sub-folder -> fileAAA.csv

my ( $par_dir, $sub_dir );
opendir( $par_dir, "$parent" );
while ( my $sub_folders = readdir($par_dir) ) {
    next if ( $sub_folders =~ /^..?$/ );    # skip . and ..
    my $path = $parent . '/' . $sub_folders;
    next unless ( -d $path );               # skip anything that isn't a directory

    opendir( $sub_dir, $path );
    while ( my $file = readdir($sub_dir) ) {
        next unless $file =~ /\.csv?$/i;
        my $full_path = $path . '/' . $file;
        print_file_names($full_path);
    }
    closedir($sub_dir);
    $flag = 0;
}
closedir($par_dir);

 ...... 

Upvotes: 0

Views: 107

Answers (2)

mkHun
mkHun

Reputation: 5927

Without using moudle try this

Instead of opendir can you try glob for subdirectory search.

In below script i make a subroutine for continuous search. When elsif condition is satisfied the path of the directory is will go to the find subroutine then it'll seach and so on.

my $v = "/Multiple Sub-folder"; 
find($v);
sub find{
    my ($s) = @_;
    foreach my $ma (glob "$s/*")
    {
        if(-f $ma)
        {
            if($ma =~m/.csv$/) # Here search for csv files.
            {
                print "$ma\n";
            }
        }
        elsif(-d $ma)
        {
            find("$ma")
        }

    }
}

But can you use File::Find module for search the files in the directory as the answer of Borodin Which is the best approach.

Upvotes: 0

Borodin
Borodin

Reputation: 126722

Updated

You should look at the File::Find module which has everything already in place to do searches like this, and has taken account of all corner cases for you

I wrote that on my tablet and at the time I couldn't offer sample code to support it. I believe this will do what you're asking for, which is simply to find all CSV files at any level beneath a parent directory

use strict;
use warnings;

use File::Find qw/ find /;

STDOUT->autoflush;

my $parent = '/Multiple Sub-folder';

find(sub {
    return unless -f and /\.csv$/i;
    print_file_names($File::Find::name);
}, $parent);

sub print_file_names {
    my ($fn) = @_;
    print $fn, "\n";
}

Upvotes: 2

Related Questions