How to return the line number that right next to a match?

P

Peng Yu

After I did a regex match, I want to figure out what the line number
is after the match in (). Is there an easy way to do it?

$string =~ /xxxx(somepattern)yyyy/;
 
D

Dr.Ruud

Peng said:
After I did a regex match, I want to figure out what the line number
is after the match in (). Is there an easy way to do it?

$string =~ /xxxx(somepattern)yyyy/;

Do you mean that your $string contains multiple lines?

Otherwise see $. in perlvar, as you have been told before.
 
D

Dr.Ruud

Peng said:
Yes. $string contains multiple lines.

So how did they end up there, did you slurp a file into it?
If so, then why not just process the file line-by-line?


You can still use a while-loop on the $string, for example:

my $n = 0;
while ( my ($line) = $string =~ /.*/g ) {
++$n;
print "$n ($1)\n" if $line =~ /xxxx(somepattern)yyyy/;
}
 
W

Willem

Peng Yu wrote:
) After I did a regex match, I want to figure out what the line number
) is after the match in (). Is there an easy way to do it?
)
) $string =~ /xxxx(somepattern)yyyy/;

Just count the newlines in the substring up to the (somepattern) capture.

my $linenr = substr($string, 0, $+[-1]) =~ tr/\n//;

See 'perldoc perlvar' for an explanation of the @+ array.


SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
 
C

C.DeRykus

After I did a regex match, I want to figure out what the line number
is after the match in ().  Is there an easy way to do it?

$string =~ /xxxx(somepattern)yyyy/;


The pre-match variable greatly simplifies the
solution, and with 5.10's /p switch, doesn't
incur a global performance penalty:

if ( $string =~ /somepattern/p ) {
my $linenum = {^PREMATCH} =~ tr/\n//;
}
 
C

C.DeRykus

...

The pre-match variable greatly simplifies the
solution, and with 5.10's /p switch, doesn't
incur a global performance penalty:

if ( $string =~ /somepattern/p ) {
   my $linenum = {^PREMATCH} =~ tr/\n//;
^^^^^^^^^^^
${^PREMATCH}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top