Reputation: 6002
Here I make a regex
manually from Regex
elements of an array.
my Regex @reg =
/ foo /,
/ bar /,
/ baz /,
/ pun /
;
my $r0 = @reg[0];
my $r1 = @reg[1];
my Regex $r = / 0 $r0 | 1 $r1 /;
"0foo_1barz" ~~ m:g/<$r>/;
say $/; # (「0foo」 「1bar」)
How to do it with for @reg {...}
?
Upvotes: 2
Views: 171
Reputation: 12842
If a variable contains a regex, you can use it without further ado inside another regex.
The second trick is to use an array variable inside a regex, which is equivalent to the disjunction of the array elements:
my @reg =
/foo/,
/bar/,
/baz/,
/pun/
;
my @transformed = @reg.kv.map(-> $i, $rx { rx/ $i $rx /});
my @match = "0foo_1barz" ~~ m:g/ @transformed /;
.say for @match;
Upvotes: 6
Reputation: 5072
my @reg =
/foo/,
/bar/,
/baz/,
/pun/
;
my $i = 0;
my $reg = @reg
.map({ $_ = .perl; $_.substr(1, $_.chars - 2); })
.map({ "{$i++}{$_}" })
.join('|');
my @match = "foo", "0foo_1barz" ~~ m:g/(<{$reg}>) /;
say @match[1][0].Str;
say @match[1][1].Str;
# 0foo
# 2baz
See the docs
Edit: Actually read the docs myself. Changed implicit eval to $() construct.
Edit: Rewrote answer to something that actually works
Edit: Changed answer to a terrible, terrible hack
Upvotes: 3