Hello Monks,

I wrote this simple script ‘findinfile.pl’ to search for arbitrary text in a file:

use strict; use warnings; print "\n"; scalar @ARGV == 2 or die "USAGE: perl $0 <filename> <regex>\n"; open(my $fh, '<', $ARGV[0]) or die "Unable to open file '$ARGV[0]' for reading: $!"; my $match = 0; my $regex = qr/$ARGV[1]/; my @lines = <$fh>; # read whole file foreach (0 .. $#lines) { if ($lines[$_] =~ /$regex/) { printf "Match found on line %d\n", ($_ + 1); $match = 1; } } print "No matches found\n" unless $match;

Example use: to find the main() function (if any) in file ‘run.c’, enter (I’m using a Windows command prompt):

>perl findinfile.pl run.c "int\s+main\s*\("

This works well (except that it doesn’t allow for embedded comments), provided the regex matches on a single line of text. However, some programmers code like this:

int main(int argc, char** argv)

So, I can modify the script as follows:

... my $text; my $match = 0; my $regex = qr/$ARGV[1]/; { local $/; # enable "slurp" mode $text = <$fh>; # read whole file } while ($text =~ /$regex/gms) { print "Match found\n"; $match = 1; } print "No matches found\n" unless $match;

but now I’ve lost track of the line numbers.

I read somewhere that I could count occurrences of "\n" to calculate the line number of each match, but how would I identify the start- and end-points of each substring between successive matches? Or, is there a more straightforward approach that will retain line numbers while searching across multiple lines?

Thanks,

Athanasius <°(((><contra mundum


In reply to Getting the line numbers of a multi-line match by Athanasius

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.