Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

I have a Perl script which prints all .pl files inside the current folder/directory, but this script wont print the .pl files inside the main folder (or the directory). I need to modify this script to do so. Can any Monks kindly help me on this.

Thanks in advance.

( I use windows, in the below code it just prints all .pl files which are present in the F: directory, but wont print .pl files which present in its children folders. I need thi modification.)

use strict; use warnings; use English; my $dir = 'F:'; foreach my $fp (glob("$dir/*.pl")) { printf "%s\n", $fp; open my $fh, "<", $fp or die "can't read open '$fp': $OS_ERROR"; while (<$fh>) { printf " %s", $_; } close $fh or die "can't read close '$fp': $OS_ERROR"; }

Replies are listed 'Best First'.
Re: Read Perl files inside a directory and its subfolders
by Random_Walk (Prior) on May 03, 2013 at 12:40 UTC

    Look up File::Find. It is a great way to recurse down a list of directories. Typically you put the code to run on the found files in a sub and pass it a ref to this sub.

    use File::Find; find(\&wanted, @directories_to_search); sub wanted { ... }

    Cheers,
    R.

    Pereant, qui ante nos nostra dixerunt!
Re: Read Perl files inside a directory and its subfolders
by RichardK (Parson) on May 03, 2013 at 13:38 UTC
Re: Read Perl files inside a directory and its subfolders
by hdb (Monsignor) on May 03, 2013 at 12:40 UTC
Re: Read Perl files inside a directory and its subfolders
by 2teez (Vicar) on May 03, 2013 at 16:00 UTC

    Hi Anonymous Monk,
    Has previously mentioned, it is a lot better to use modules like File::Find or File::Find::Rule and the likes to do what you wanted, than "re-invent", while there is no improvement to it.
    However, if you must do that with opendir then something like this can help:

    use warnings; use strict; scandir( $ARGV[0] ); ## where to look from CLI sub scandir { my ($file) = @_; if ( -d $file ) { print $file,$/; ## print directory name opendir my $dh, $file or die "can't open directory: $!"; while ( readdir($dh) ) { chomp; next if $_ eq '.' or $_ eq '..'; print "\t", $_, $/ if /\.pl$/; ## print *.pl files scandir("$file/$_"); ## check sub-directory... } } }
    Moreover, this has been done in perlmonks, times and again, so search is your friend. Please use it.
    Hope this helps.

    If you tell me, I'll forget.
    If you show me, I'll remember.
    if you involve me, I'll understand.
    --- Author unknown to me