Reading a file line by line imposes an overhead by its very nature. If the files are smallish in nature compared to the machine you're running on, you should slurp them into memory and then operate upon their contents as a string. This alone will be a win compared to building an array, over and above the line-oriented cost.

You can then do a quick check on the entire contents to see if you find the string anywhere. This uses a fast Boyer-Moore algorithm, and can weed out files that don't match quickly. If you expect 99% of files to contain what you're searching for, this will probably be a net loss, so you should comment out the next statement (see below).

To find the line number, you just have to match the section before your match, the line containing the match itself, and count the intervening line-breaks afterwards. The regexp below is probably a bit horrible in terms of performance. No doubt a better regexp hacker than I would be able to come up with something that doesn't backtrack:

#! /usr/local/bin/perl use strict; use warnings; my $target = shift; $target = qr/$target/; for my $file (@ARGV) { my $str = do {local $/ = undef; open my $in, '<', $file; <$in>}; next unless $str =~ /$target/; my $current = 1; while ($str =~ /((?:[^\n]*?\n)*?)(.*?$target[^\n]*)/g) { $current += $1 =~ tr/\n/\n/; print "$file($current): $2\n"; } }

I would expect this to run faster than a grep-based version.

• another intruder with the mooring in the heart of the Perl


In reply to Re: grep return the index instead of the element content, and its speed by grinder
in thread grep return the index instead of the element content, and its speed 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.