web analytics

Perl: how to get the position of the match

Let’s search for the word “brave” in the string “Hello, new brave world!”.
There are several methods to get the position of the match in Perl.

#1 – use POS function
Function pos returns the position, where search was finished.

$txt = "Hello, brave new world!" ;
$txt =~ m/(brave)/g;
my $pos = pos($txt) - length $1;

#2 – use $PREMATCH variable
$PREMATCH varialbe (short name $`) contains the string, preceeding the match.
This method is easy, however it could significantly affect performance of other regular expressions (see RegExp book for the detailed explanation). Therefor, it’s not the best solution.

use English ;
$txt = "Hello, brave new world!" ;
$txt =~ m/(brave)/g;

###my $pos = length $`
my $pos = length $PREMATCH;

#3 – use @LAST_MATCH_START variable
This method was introduced in Perl 5.6.0 and it does not make any bad impact on performance – so it’s recommended solution.

use English qw( -no_match_vars );
$txt = "Hello, brave new world!" ;
$txt =~ m/(brave)/g;

### $pos = $-[0];
$pos = $LAST_MATCH_START[0];

1 comment to Perl: how to get the position of the match

  • Stephen D

    Is there ever a case when @- {aka @LAST_MATCH_START} or @+ {aka @LAST_MATCH_END} contain more than one element?

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>




This site uses Akismet to reduce spam. Learn how your comment data is processed.


A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna, tincidunt vitae molestie nec, molestie at mi. Nulla nulla lorem, suscipit in posuere in, interdum non magna.