paurus has asked for the wisdom of the Perl Monks concerning the following question:

I am relatively new to Perl, and as such am having a few questions. I am currently working on a text extraction script. I want to extract only a specific range of lines starting from the line or lines on which my reg exp is found. I am trying to extract from the line on which the expression is located + 3 lines, for a total of four displayed lines. Instead of using reg exps for range limiters (due to multiple finds), I want to use the $. variable. I have tried a few different ways in attempting to implement this variable. I have mainly modified line range examples I have found in bound documentation but to no avail. I have tried code such as:
while(<F>) { if(/\bREGEXP\b/) { $seen++; push(@lines, $.); print "\nMatch found:\n\n\tFILENAME: $dir/$file\n\tLINE: $. : '$`~$& +~$'"; if(($.) .. ($. + 3) { print; } # my range extract code # OR print "$`$&$'\n" if(($.)..($. + 3)); # my range extract code }else { next; } }
Is it possible to use the $. variable as a definitive start and end for a range of text extraction? If so, how can I go about implementing this for my line number range? Thank you. -paurus

Replies are listed 'Best First'.
Re: Line(s) extraction
by BrowserUk (Patriarch) on Apr 01, 2004 at 06:55 UTC

    Rather than bothering with $., why not just print the line containing the regex and then 3 more lines?

    #! perl -sw use strict; while( <DATA> ) { next unless m[two]; print; print scalar <DATA> for 1..3; } __DATA__ one two three four five six

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
Re: Line(s) extraction
by kvale (Monsignor) on Apr 01, 2004 at 06:56 UTC
    Here is a simple solution that doesn't use $.
    while (my $line = <F>) { next unless $line =~ /\bREGEXP\b/; $line .= <F>; $line .= <F>; $line .= <F>; print $line; }

    -Mark