user17227456
user17227456

Reputation: 1317

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

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?

Upvotes: 10

Views: 325

Answers (1)

tshiono
tshiono

Reputation: 22042

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.

Upvotes: 11

Related Questions