Hi, if you need to lookup multiple strings in the same file, I would generalize the detection routine like this:
use strict; use warnings; sub check_strings { my ($file, $r_stringsNeeded, $r_stringsToAvoid) = @_; open my $fh, '<', $file or die "Can't open '$file': $!\n"; my %foundNeeded = map { $_ => 0 } @{$r_stringsNeeded}; my %foundToAvoid = map { $_ => 0 } @{$r_stringsToAvoid}; while (<$fh>) { for my $string (@{$r_stringsNeeded}) { ++$foundNeeded{$string} if /\Q$string/; } for my $string (@{$r_stringsToAvoid}) { ++$foundToAvoid{$string} if /\Q$string/; } } my $foundAllNeeded = 0 == scalar grep { $_ == 0 } values %foun +dNeeded; my $foundNoneOfAvoided = 0 == scalar grep { $_ != 0 } values %foun +dToAvoid; return $foundAllNeeded && $foundNoneOfAvoided; } if (!check_strings('search.txt', ['first_neededString', 'second_needed +String'], ['firstStringToAvoid', 'secondStringToAvoid'])) { die "file did not contain all needed Strings or contained forbidde +n strings\n"; }
Here the file is only read once. You could supply multiple strings you want to have present in the first array reference, and multiple strings in the second array reference where none of them should be present in the file. This simple subroutine only gives a boolean answer, but it could be extended to give more detailed answers what was matched and what not.

Hope that helps.


In reply to Re: Perl script to Parse a file for a string by hexcoder
in thread Perl script to Parse a file for a string by user786

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.