in reply to Re: Getting Filenames that contains a particular string recursively From a Directory
in thread Getting Filenames that contains a particular string recursively From a Directory

There's nothing wrong in using an external find command in a pipe open, especially if you're not concerned about portability across systems.

But then you're using perl to run what is fundamentally a shell script. In particular there's absoultely no need to fork out external grep's with that system.

Also you have:

open (FIND_CMD, "find /home/modules |"); chomp (my @findArr = <FIND_CMD>);
I recommend:
  1. using the three args form of open and lexical filhandles,
  2. checking errors,
  3. avoiding to slurp in a potentially big list, whereas we have a syntactically sweet enough while loop just to process it one item at a time.
my $pattern = '.pm$'; my $FilePattern = "sub user_method"; my $ResultFilePath = '/tmp/ModuleSearch'; foreach my $File ( @findArr ) { next if ( $File !~ m/$pattern/ );

This will match Foo.apm; you may want to learn about \Q (and \E) in perldoc perlop.

But since you're running an external find anyway, why not let it do the dirty job? (-name '*.pm')

system ("grep -iHl \"$FilePattern\" \"$File\" >> $ResultFilePath ") +;

I wish I had not seen that...

All in all it may have been:

#!/usr/bin/perl use strict; use warnings; open my $find, '-|', 'find /home/modules -name "*.pm"' or die "Can't run find(1): $!\n"; $\="\n"; while (<$find>) { chomp; open my $fh, '<', $_ or die "Can't open `$_': $!\n"; while (my $line=<$fh>) { print, last if $line =~ /sub user_method/; } } __END__

A compressed version (having a huge pile o' magic in it) of which could be:

#!/usr/bin/perl -ln use strict; use warnings; BEGIN { @ARGV='find /home/modules -name "*.pm"|' } local @ARGV=$_; /sub user_method/ and (print $ARGV), last while <> ; __END__

(both untested)

  • Comment on Re^2: Getting Filenames that contains a particular string recursively From a Directory
  • Select or Download Code

Replies are listed 'Best First'.
Re^3: Getting Filenames that contains a particular string recursively From a Directory
by Anonymous Monk on Dec 06, 2005 at 14:33 UTC

    Hi !!

    Thanks for your valuable code !!

    I tried your first code.. the output is like this..

    /home/modules/one.pm /home/modules/two.pm /home/modules/three.pm
    I dono how to get only those filenames.. <br> i.e like one, two and three in an "array"<br>

    Thank u

      I'm not sure if I understand what you mean. Do you want to gather those filenames into an array, say @results? Well, if so then you just have to substitute a print with a

      (push @results, $_)