regex ( )

Documentation for regex ( ) assembled from the following types:

language documentation Regexes

From Regexes

(Regexes) regex ( )

The round parentheses don't just group, they also capture; that is, they make the string matched within the group available as a variable, and also as an element of the resulting Match object:

my $str =  'number 42';
if $str ~~ /'number ' (\d+/ {
    say "The number is $0";         # OUTPUT: The number is 42 
    # or 
    say "The number is $/[0]";      # OUTPUT: The number is 42 
}

Pairs of parentheses are numbered left to right, starting from zero.

if 'abc' ~~ /(a) b (c)/ {
    say "0: $0; 1: $1";             # OUTPUT: «0: a; 1: c␤» 
}

The $0 and $1 etc. syntax is shorthand. These captures are canonically available from the match object $/ by using it as a list, so $0 is actually syntactic sugar for $/[0].

Coercing the match object to a list gives an easy way to programmatically access all elements:

if 'abc' ~~ /(a) b (c)/ {
    say $/.list.join: ''  # OUTPUT: «a, c␤» 
}