The first place to look is glob, since it appears that you don't want to recurse down a directory tree. As an example (NOT TESTED)

# insert appropriate shebang line use strict; use warnings; my @files = glob("chat/*.htm"); # use something like [Hh][Tt][Mm] if y +ou're unsure about the case @files = grep { -s $_ and -f _ and -r _} @list; print "Enter search string :"; my $string = <>; # read from STDIN chomp($string); # strip off the line feed resulting from <enter> my $quoted_string = quotemeta($string); # quote all meta-characters. + Remove if not needed foreach my $file (@files) { my $filehandle; unless(open($filehandle, "<", $file)) { warn "Could not open $file because $!\n"; next; } my @contents = <$filehandle>; # presuming the files are not too la +rge chomp(@contents); close($filehandle) or die "Could't close $file because $!\n"; @contents = grep { /$quoted_string/ } @contents; if(@contents){ print "$string was found in $file:\n\t",join("\n\t",@contents), +"\n"; } }
Warning! Code is NOT tested, and I won't even guarantee it will compile.

Doubtless there are better ways to do this than my example. One obvious improvement could be to slurp up the entire file into a scalar, not read it into an array, by setting $/ to undef; this is probably faster. Other improvements would be to permit regex.


Information about American English usage here and here. Floating point issues? Please read this before posting. — emc


In reply to Re: How to search string in all files in directory by swampyankee
in thread How to search string in all files in directory by oh5yw

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.