Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl 6 regex variable and capturing groups

Tags:

raku

When I make a regex variable with capturing groups, the whole match is OK, but capturing groups are 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 modify 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」
like image 398
Eugene Barsky Avatar asked Jan 04 '23 08:01

Eugene Barsky


1 Answers

With your code, the compiler gives the following warning:

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

That tells us something is wrong—regex shouldn't be treated as strings. There are two more proper ways to nest regexes. First, you can include sub-regexes within assertions(<>):

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

Note that I'm not matching / $rgx /. That is putting one regex inside another. Just match $rgx.

The nicer way is to use named regexes. Defining atom and the regex as follows will let you access the match groups as $<atom>[0] and $<atom>[1]:

my regex atom { \d ** 2 };
my $rgx = / <atom> \w+ <atom> /;
$str ~~ $rgx;
like image 179
piojo Avatar answered Jan 12 '23 10:01

piojo