in reply to How to Recursively search down thru directories to find a string and display its location.

Here is a sample code:

use strict; use File::Find; my @dirs = qw( . ); ## add current directory to list of + dirs to search ## main processing done here my @found_files = (); my $pattern = qr/World/; find( \&wanted, @dirs ); ## fullpath name in $File::Find::name sub wanted { next if $File::Find::name eq '.' or $File::Find::name eq '..'; + open my $file, '<', $File::Find::name or die "Error openning file: + $!\n"; while( defined(my $line = <$file>) ) { if($line =~ /$pattern/) { push @found_files, $File::Find::name; last; } } close ($file); } ## display files - could be sorted if needed, etc foreach my $file( @found_files) { print $file, "\n"; }
  • Comment on Re: How to Recursively search down thru directories to find a string and display its location.
  • Download Code

Replies are listed 'Best First'.
Re^2: How to Recursively search down thru directories to find a string and display its location.
by jwkrahn (Abbot) on May 17, 2012 at 15:43 UTC
    next if $File::Find::name eq '.' or $File::Find::name eq '..';

    $File::Find::name contains the full path name so (in your example) it would start at ./. and continue with ./subdir/. etc. and would never match . or ...    Also you should use return when exiting from a subroutine.    Probably better as:

    return unless -f;


    open my $file, '<', $File::Find::name or die "Error openning file: + $!\n";

    Also, because File::Find::find() changes directories, trying to open $File::Find::name from the current directory when using relative directory names won't work.    Just use the file name in $_:

    open my $file, '<', $_ or die "Error openning '$_' $!\n";