问题
A continuation of this question, and probably an even more weird one.
Can I e.g. concatenate two regexes
using a sub
?
(Of course, I understand, how to do it with a regex
)
The following code is totally wrong, but I hope it can explain what I want to do:
my Regex sub s12 ( $c, $v) {
return / <{$c}> <{$v}> /
}
my regex consonant { <[a .. z] -[aeiou]> }
my regex vowel { <[aeiou]> }
my regex open_syllable { &s12( &consonant, &vowel ) }
"bac" ~~ m:g/ <open_syllable> /;
say $/; # should be 'ba'
回答1:
What you wrote is basically right, but you need to tweak the syntax a little. First, you should declare your combining function like any other sub. Next, it seems like to interpolate a regex into another, <$r>
is the right syntax, and to interpolate a function call into a regex, <{my-sub(args)}>
is the right syntax. (No need to prefix the sub with an ampersand when calling it—&
is mostly for when you want to refer to a Callable
without calling it.) Combine these little fixes and your code works:
sub combine(Regex $a, Regex $b --> Regex) {
/ <$a> <$b> /
}
my regex consonant { <[a .. z] -[aeiou]> }
my regex vowel { <[aeiou]> }
my regex open_syllable { <{combine(&consonant, &vowel)}> }
"bac" ~~ m:g/ <open_syllable> /;
say ~$/; # output: ba
来源:https://stackoverflow.com/questions/47224387/passing-regexes-as-arguments-in-perl-6