Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Multiple file handling

by stallion (Acolyte)
on Sep 12, 2012 at 14:12 UTC ( #993232=perlquestion: print w/ replies, xml ) Need Help??
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

Comment on Multiple file handling
Download Code
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 (Abbot) 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'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://993232]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (9)
As of 2014-11-26 01:57 GMT
Find Nodes?
    Voting Booth?

    My preferred Perl binaries come from:

    Results (160 votes), past polls