Passing regexes as arguments in Perl 6

爷,独闯天下 提交于 2019-12-07 10:34:53

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!