in reply to Reading Files Across Directories and Sub Directories

When those esteemed monks reply as they do you should take note. There is always more than one way to do it, although there is not always a good reason. If you really must reinvent the File::Find wheel:
use strict; use warnings; sub search_dir { my ($dir) = @_; my $dh; if ( !opendir ($dh, $dir)) { warn "Unable to open $dir: $!\n"; return; } # Two dummy reads for . & .. readdir ($dh); readdir ($dh); while (my $file = readdir ($dh) ) { my $path = "$dir/$file"; # / should work on UNIX & Win32 if ( -d $path ) { print "Directory $path found\n"; search_dir ($path); } else { print "File $path found\n"; } } closedir ($dh); } ########################################################## print "Enter The Directory Path"; my $dir = <STDIN>; chomp($dir); search_dir ($dir);

Replies are listed 'Best First'.
Re^2: Reading Files Across Directories and Sub Directories
by Fletch (Bishop) on Dec 02, 2008 at 17:41 UTC

    Probably better to explicitly ignore "." and ".." than to blithely do two dummy reads; I'm not aware of anything that mandates that those are the first results returned by a readdir (then again I don't know of any offhand where it isn't either, just it seems more portable to ignore them on the off chance and increase your portability (on the third hand, it's entirely possible that said system would have not-cwd-or-parent entries which are named "." and ".." that you might not want to ignore . . . :)).
    </nitpick>

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      Root directories don't have "." and ".." in Windows, for example
Re^2: Reading Files Across Directories and Sub Directories
by koti688 (Sexton) on Dec 03, 2008 at 07:24 UTC
    Thanks Cdarke, really helped a lot
Re^2: Reading Files Across Directories and Sub Directories
by Anonymous Monk on Apr 26, 2017 at 13:40 UTC
    This one resulted in all kinds of trouble, like infinite loops :D This works like a charm on the other hand.
    sub search_dir { my ($dir) = @_; print "Entered search_dir sub, working with directory => $dir \n"; my $dh; # handle if ( !opendir ($dh, $dir)) { warn "Unable to open $dir: $!\n"; return; } my @FILES = grep { $_ ne '.' && $_ ne '..' } readdir($dh); foreach my $file (@FILES) { my $path = "$dir/$file"; if ( -d $path ) { print "Directory $path found\n"; search_dir ($path); } else { print "File $path found\n"; } } closedir ($dh); } # END of search_dir sub ############## Output: ... File /csvfiles/2015/12/22.csv found Directory /csvfiles/2015/10 found Entered search_dir sub, working with directory => /csvfiles/2015/10 File /csvfiles/2015/10/16.csv found File /csvfiles/2015/10/22.csv found Directory /csvfiles/2015/11 found Entered search_dir sub, working with directory => /csvfiles/2015/11 File /csvfiles/2015/11/16.csv found File /csvfiles/2015/11/11.csv found ...