Perl 6 variable and exciting group

When I make a variable regexwith capture groups, the whole match is fine, but capture groups Nil.

my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;

$str ~~ / $rgx / ;
say ~$/;  # 12abc34
say $0;   # Nil
say $1;   # Nil

If I change the program to avoid $rgx, everything works as expected:

my $str = 'nn12abc34efg';

my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;

$str ~~ / ($atom) \w+ ($atom) /;
say ~$/;  # 12abc34
say $0;   # 「12」
say $1;   # 「34」
+4
source share
2 answers

Using your code, the compiler generates the following warning:

Regex object coerced to string (please use .gist or .perl to do that)

This tells us something wrong: the regular expression should not be treated as strings. There are two correct ways to place regular expressions. First, you can include sub-submissions in statements ( <>):

my $str = 'nn12abc34efg';
my Regex $atom = / \d ** 2 /;
my Regex $rgx = / (<$atom>) \w+ (<$atom>) /;
$str ~~ $rgx;

Please note that I do not match / $rgx /. This puts one regular expression inside another. Just match $rgx.

. atom , , $<atom>[0] $<atom>[1]:

my regex atom { \d ** 2 };
my $rgx = / <atom> \w+ <atom> /;
$str ~~ $rgx;
+5

, $str ~~ / $rgx /; " ". $rgx , $0 $1 Match, , . , , :

my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;

$str ~~ / $0=$rgx /;
say $/;

$0. , , :

my $str = 'nn12abc34efg';
my $atom = / \d ** 2 /;
my $rgx = / ($atom) \w+ ($atom) /;

$str ~~ / $<bits-n-pieces>=$rgx /;
say $/;
+4

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


All Articles