in reply to grep return the index instead of the element content, and its speed

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

  • Comment on Re: grep return the index instead of the element content, and its speed
  • Download Code

Replies are listed 'Best First'.
Re^2: grep return the index instead of the element content, and its speed
by Anonymous Monk on Oct 08, 2010 at 17:27 UTC
    my $index = 0; my $i = 0; my $key = 10; my @array = .... my $success = grep {$array[$_] eq $key && ($in = $_)} 0..$#array; $success is 0 if not found, 1 if found $in contain the offset index