我想用一个单词大写的所有辅音:
> my $word = 'camelia'
camelia
> $word ~~ s:g/<-[aeiou]>/{$/.uc}/
(「c」 「m」 「l」)
> $word
CaMeLia
为了使代码更通用,我将所有辅音的列表存储在字符串变量
中my $vowels = 'aeiou';
或在数组中
my @vowels = $vowels.comb;
如何解决$vowels
或@vowels
变量的原始问题?
答案 0 :(得分:3)
也许trans
方法比subst
子或运算符更合适。
试试这个:
my $word = "camelia";
my @consonants = keys ("a".."z") (-) <a e i o u>;
say $word.trans(@consonants => @consonants>>.uc);
# => CaMeLia
答案 1 :(得分:3)
在moritz's explanation的帮助下,解决方案如下:
my constant $vowels = 'aeiou';
my regex consonants {
<{
"<-[$vowels]>"
}>
}
my $word = 'camelia';
$word ~~ s:g/<consonants>/{$/.uc}/;
say $word; # CaMeLia
答案 2 :(得分:2)
您可以使用<!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