in reply to Easy way to search files?

File::Find will handle recursive directory spanning.

Here's a simple sub which takes a filepath and a string, returning true if the file contains the string. Slurp is used, so files should be smallish.

sub contains { my ($file, $string) = @_; my $content; { local $/; open my $fh, '<', $file or die $!; $content = <$fh>; close $fh or die $!; } index( $content, $string) == -1 ? 0 : 1; }
That should be fairly quick.

Update: Any sub returns the value of its last expression unless an explicit return comes before. In sub contains, the trinary operator ?: tests whether index returned -1, and evaluates to zero if so, otherwise evaluates to 1. That could as well have been written     return not index( $content, $string) == -1 or     return index( $content, $string) != -1 where the return keyword is optional.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re: Re: Easy way to search files?
by matth (Monk) on Jan 06, 2003 at 14:42 UTC

    That looks like what I need. I have a basic question though. I know how to return variables from a subroutine. I'm not, however, sure how this subroutine returns true. Or should I say that I am not sure how to return the fact that this subroutine returns true for each file. Can i just code to return a variable called $file_hit or something? That if indeed the file has been found to be true. I think that this post might be a bit confusing. I'm posting it anyway just in case people understand what is going through my mind.<\p>

      Hi ,

      The file content or pointer could be returned .