Eugene Barsky
Eugene Barsky

Reputation: 5992

How to interpolate variables into Perl 6 regex character class?

I want to make all the consonants in a word uppercase:

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

To make the code more general, I store the list of all the consonants in a string variable

my $vowels = 'aeiou';

or in an array

my @vowels = $vowels.comb;

How to solve the original problem with $vowels or @vowels variables?

Upvotes: 3

Views: 265

Answers (3)

Eugene Barsky
Eugene Barsky

Reputation: 5992

With the help of moritz's explanation, here is the solution:

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

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

Upvotes: 3

timotimo
timotimo

Reputation: 4329

Maybe the trans method would be more appropriate than the subst sub or operator.

Try this:

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

Upvotes: 3

Brad Gilbert
Brad Gilbert

Reputation: 34120

You can use <!before …> along with <{…}>, and . to actually capture the character.

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

You can do away with the <{…}> with @vowels

I think it is also important to realize you can use .subst

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

I would recommend storing the regex in a variable instead.

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

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

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

Upvotes: 2

Related Questions