|P is for Practical|
Getting the line numbers of a multi-line matchby Athanasius (Canon)
|on May 02, 2012 at 01:56 UTC||Need Help??|
Athanasius has asked for the
wisdom of the Perl Monks concerning the following question:
I wrote this simple script ‘findinfile.pl’ to search for arbitrary text in a file:
Example use: to find the main() function (if any) in file ‘run.c’, enter (I’m using a Windows command prompt):
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:
So, I can modify the script as follows:
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?
Athanasius <°(((>< contra mundum