Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Getting the line numbers of a multi-line match

by jwkrahn (Abbot)
on May 02, 2012 at 05:34 UTC ( [id://968358]=note: print w/replies, xml ) Need Help??


in reply to Getting the line numbers of a multi-line match

my @lines = <$fh>; # read whole file foreach (0 .. $#lines) { if ($lines[$_] =~ /$regex/) { printf "Match found on line %d\n", ($_ + 1); $match = 1; } }

No need to read the whole file at once:

while ( <$fh> ) { if ( /$regex/ ) { print "Match found on line $.\n"; $match = 1; } }


This may solve your multi-line problem (UNTESTED):

my $lines; while ( <$fh> ) { $lines .= $_; if ( $lines =~ /($regex)/sm ) { my $newlines = $1 =~ tr/\n//; if ( $newlines ) { print "Match found on lines ", $. - $newlines, " through $ +.\n"; } else { print "Match found on line $.\n"; } $match = 1; $lines = $_; } }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://968358]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2024-04-25 12:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found