http://www.perlmonks.org?node_id=993232

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

Scenario: A variable is mentioned in multiple file names and im able to grep once only. I want the file names in which the variable is mentioned whereas im able to grep only one file name.

sub module{ my $File1 = $File::Find::name; $File1 =~ s,/,\\,g; if ( $File1 =~ /.+\.doc/i) { open FILE, $File1 ; if ( grep /$variable/, <FILE> ) { $FOUND = 1; $FUN1 = $_; } close FILE; } } return 1;

Here $variable contains the search tag.. Any suggestions how to proceed Thanks

Replies are listed 'Best First'.
Re: Multiple file handling
by moritz (Cardinal) on Sep 12, 2012 at 14:38 UTC
    Scenario: A variable is mentioned in multiple file names and im able to grep once only.

    Why should that be the case? That sounds like a rather odd restriction. If you absolutely must work with that restriction, you can do something like

    use autodie; use List::MoreUtils qw/uniq/; open my $F1, $filename1; open my $F2, $filename2; my @files = unique map $_->[0], grep $_->[1] =~ /$variable/, (map [$filename1, $_] <$F1>), (map [$filename2, $_] <$F2>), ;

    Of course that code is much slower and uses much more memory than if you'd just search file by file.

Re: Multiple file handling
by tobyink (Canon) on Sep 12, 2012 at 14:56 UTC

    I'm not entirely sure I understand your requirements, but...

    use 5.010; use Path::Class qw(dir file); say "GOT $_" for grep_dir_recursively( qr(say), # pattern to grep for (with smartmatch) qr(\.pl$), # pattern to match file names (with smartmatch) '/home/tai/tmp', # directory to search ); sub grep_dir_recursively { my $text_pattern = shift; my $file_pattern = shift; my @results; for my $root (@_) { dir($root)->recurse(callback => sub { my $file = shift; return if $file->is_dir; return unless $file ~~ $file_pattern; my $fh = $file->open; while (<$fh>) { if ($_ ~~ $text_pattern) { push @results, $file; last; } } }); } return @results; }
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'