Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in Perl regex variable $+{name} and $-{name}

Tags:

regex

perl

What is the difference between Perl regex variables $+{name} and $-{name} when both are used to refer to the same regex group from Perl statement/expression code?

like image 836
user17227456 Avatar asked Apr 06 '26 16:04

user17227456


1 Answers

While $+{name} holds the captured substring referred by name as a scalar value, $-{name} refers to an array which holds capture groups with the name.
Here is a tiny example:

#!/usr/bin/perl

use strict;
use warnings;

'12' =~ /(?<foo>\d)(?<foo>\d)/; # '1' and '2' will be captured individually

print $+{'foo'}, "\n";          # prints '1'

for (@{$-{'foo'}}) {            # $-{'foo'} is a reference to an array
    print $_, "\n";             # prints '1' and '2'
}

As $+{name} can hold only a single scalar value, it is assigned to the first (leftmost) element of the capture groups.

like image 91
tshiono Avatar answered Apr 08 '26 11:04

tshiono



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!