If you have an array, @file, then you have to loop through it. m// cannot loop through an array in perl5 (maybe perl 6?). However, if you put the entire file into a scalar, now we can get somewhere:

my $file = join '', @file; # put it all in a single scalar if ($file =~ m/(?:what you want to find.*){6}/) { print "'what you want to find' was in the file at least 6 times.\n"; }
That said, grep would use up less space, which may be important for large files. The reason is because you're duplicating the file in both an array and a scalar. The obvious way to overcome that is to put it in the scalar to begin with - which means you don't have an array later if you want to look up lines in an array.

Of course, for really large files, you'll want to iterate through the file one line at a time to keep from loading 100MB of text into memory at once:

my $count; while (<$fh>) { $count++ while /what you want to look for/g; if ($count >= 6) { last; } } $fh->close(); if ($count >= 6) { print "found 'what you want to look for' at least 6 times in the fil +e.\n"; }
And, of course, this means you don't have the file in memory at all when you're done, which may not be what you want either.


In reply to Re: find a string a certain number of times by Tanktalus
in thread find a string a certain number of times by Anonymous Monk

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.