Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl last capture match variable

Tags:

regex

perl

I am relatively novice to perl, and with my recent learning I ended up with some script and stumbled upon this regex

$+ which says the last bracket matched by the last search pattern. This is useful if you don't know which of a set of alternative patterns matched. For example:

/Version: (.*)|Revision: (.*)/` && `($rev = $+);

Sounds interesting but I could not understand what it actually does, can some one please help me understand its usage,

I also found some examples which state as below,

"$<digit> Regexp parenthetical capture holders."

like image 943
Gopal Avatar asked Jan 01 '26 12:01

Gopal


1 Answers

Regexes can have capture groups, which after a successful match contain the matched substring for that part of the pattern:

/Version: (.*)|Revision: (.*)/
#         $1             $2

These are enumerated left to right as $1, $2, …. Sometimes, we may want to access the last successful capture. E.g:

"Version: v123"  → "v123"
"Revision: v678" → "v678"

So we either need $1 or $2, they will not be filled at the same time. We could do:

/Version: (.*)|Revision: (.*)/ and $rev = ($1 // $2)

which uses the // defined-or operator. Or we could use $+ to refer whatever capture succeeded most recently. You can think of it a bit as $-1: the last capture group (except that it's not the last in the source code, but the most recent in time).

In this simple example, using $+ might make sense, but I've never actually used it. Better workarounds include:

  • Using named captures, which are accessible via the %+ hash:

    /Version: (?<rev>.*)|Revision: (?<rev>.*)/ and $rev = $+{rev}
    
  • Resetting the numbering with the (?| ... | ... ) construct. This breaks the normal numbering of capture groups from left to right, and instead numbers each alternative independently:

    /(?|Version: (.*)|Revision: (.*))/ and $rev = $1
    #            $1             $1
    
like image 59
amon Avatar answered Jan 03 '26 04:01

amon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!