Brackets in brackets as an array (Perl)

I seem to remember that there was a way to gain access to the matching regular expression match in Perl (ie $1, $2, $3, etc.) as an array, but now I can not seem to find it. Neither one nor the other @+, and @-.

Edit: I have to add that I want to access this array inside s///(substitution), for example:

s/(foo)(bar)+(baz)/mySubst(@!)/e;

(if @!- the array I'm looking for)

+3
source share
4 answers

I am not aware of the built-in magic array that contains all the groups in brackets, but this does not stop you from doing the following:

{package Match::Parens;
    sub TIEARRAY {bless []}
    sub FETCH {no strict 'refs'; ${$_[1] + 1}}
    sub FETCHSIZE {$#+}
    tie @!, __PACKAGE__;
}

sub mySubst {join ', ' => map ucfirst, @_}

my $str = 'foobarbarbaz';

$str =~ s/(foo)(bar)+(baz)/mySubst(@!)/e;

say $str;  # prints 'Foo, Bar, Baz'

, Match::Parens @! . , , . 0, , , 1, vars $1, $2, $3.

+5

@array = $foo = ~ m/() (reg) (exp)/;

+1

, ?

@matches = /x(.+?)y/g;   # Matching against $_

.

, . , , .

+1

Here is the work. You can also access them as a link.

s/(foo)(bar)+(baz)/mySubst([$1,$2,$3,$4])/e; 

This will work well if you know the upper bound of the corresponding elements. This solution does not interrupt with warnings.

0
source

Source: https://habr.com/ru/post/1776473/