Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

list of files in subdirectories

by ariczi55 (Initiate)
on Jun 06, 2012 at 06:38 UTC ( #974650=perlquestion: print w/replies, xml ) Need Help??
ariczi55 has asked for the wisdom of the Perl Monks concerning the following question:

how can I get a list of files in the directory /home/test/ (in subdirectories too)

results in array (if can)

Replies are listed 'Best First'.
Re: list of files in subdirectories
by davido (Archbishop) on Jun 06, 2012 at 06:43 UTC


    use strict; use warnings; use File::Find; my $starting_path = '/home/test'; my @list_of_files; find( sub { push @list_of_files, $File::Find::name if -e -f; }, $starting_path );


Re: list of files in subdirectories
by sabari (Beadle) on Jun 06, 2012 at 11:47 UTC
    You can also use opendir system call
    opendir(DIR, "/home/test"); @files = readdir(DIR); closedir(DIR); foreach $file (@files) { next if ($file eq "." or $file eq ".."); print $file; } For More detailed work on this can be found on below Link
    Best Regards, S.Sabarinathan,

      This falls short of meeting the OP's clear and simple specification in two ways:

      • It doesn't look in subdirectories.
      • It doesn't bother to check whether $file is actually a file (not everything that shows up in a directory needs to be a file.), so even in the directory that it does process, it's not providing accurate results.

      Remember, the OP wanted to find all files in a directory, including those found in subdirectories.


Re: list of files in subdirectories
by Anonymous Monk on Jun 06, 2012 at 11:53 UTC

      Here is a nice example from the book Higher-Order Perl by Mark Jason Dominus

      This example is for win32, but it is easily changable:

      use strict; use warnings; use Time::HiRes qw(gettimeofday tv_interval); my $start_time = [gettimeofday]; my $inp_dir = 'c:\temp\Tmp_User'; my ( $startdir ) = @ARGV; $startdir = $inp_dir; ( defined $startdir ) || usage(); walk_path( \&is_req_file, $startdir ); my $elapsed = tv_interval($start_time); $elapsed = sprintf "%.04f", $elapsed; print "\n...Elapsed is $elapsed sec\n"; 1; sub is_req_file { my ($filn) = @_; print "$filn\n"; return 1; } sub walk_path { my ( $filefunc, $startdir ) = @_; my $dos_cmd = "dir $startdir /b /S /A:-D"; map { $filefunc->($_) } ( split /\n/, qx{$dos_cmd} ); return; }

      The advantage is, that it runs really fast on windows.

      The missing sub usage is left as an exercise.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://974650]
Approved by davido
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (10)
As of 2018-06-19 05:23 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (111 votes). Check out past polls.