如何将变量插入 Perl 6 正则表达式字符 class?

How to interpolate variables into Perl 6 regex character class?

我想将单词中的所有辅音字母大写:

> my $word = 'camelia'
camelia
> $word ~~ s:g/<-[aeiou]>/{$/.uc}/
(「c」 「m」 「l」)
> $word
CaMeLia

为了使代码更通用,我将所有辅音的列表存储在一个字符串变量中

my $vowels = 'aeiou';

或数组

my @vowels = $vowels.comb;

如何用$vowels@vowels变量解决原题?

您可以使用 <!before …> 以及 <{…}>. 来实际捕捉角色。

my $word = 'camelia';
$word ~~ s:g/

  <!before         # negated lookahead
    <{             # use result as Regex code
      $vowel.comb  # the vowels as individual characters
    }>
  >

  .                # any character (that doesn't match the lookahead)

/{$/.uc}/;
say $word;         # CaMeLia

您可以用 @vowels

取消 <{…}>

我认为意识到您可以使用 .subst

也很重要
my $word = 'camelia';
say $word.subst( :g, /<!before @vowels>./, *.uc ); # CaMeLia
say $word;                                         # camelia

我建议改为将正则表达式存储在变量中。

my $word = 'camelia'
my $vowel-regex = /<-[aeiou]>/;

say $word.subst( :g, $vowel-regex, *.uc ); # CaMeLia

$word ~~ s:g/<$vowel-regex>/{$/.uc}/;
say $word                                  # CaMeLia

也许 trans 方法比 subst 子或运算符更合适。

试试这个:

my $word = "camelia";
my @consonants = keys ("a".."z") (-) <a e i o u>;
say $word.trans(@consonants => @consonants>>.uc);
# => CaMeLia

的帮助下,解决方法如下:

my constant $vowels = 'aeiou';
my regex consonants {
    <{
       "<-[$vowels]>"
     }>
}

my $word = 'camelia';
$word ~~ s:g/<consonants>/{$/.uc}/;
say $word;  # CaMeLia