regexperl

Perl last capture match variable


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."


Solution

  • $<digit> holds the capture buffer info.

    Regex -

       Version:\ 
       ( .* )            # (1)
    |  
       Revision:\ 
       ( .* )            # (2)
    

    Code -

    if ( $str =~ /Version: (.*)|Revision: (.*)/ )
    {
        if ( defined $1 ) {
            $ver = $1;
        }
        elsif ( defined $2 ) {
            $rev = $2;
        }
    }