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];

One thought on “Perl: how to get the position of the match

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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