substitutionrakusimultaneous

Simultaneous substitutions with s/// in Perl 6


Is there a way to do simultaneous substitutions with s///? For instance, if I have a string with a number of 1s, 2s, 3s, etc, and I want to substitute 1 with "tom", and 2 with "mary", and 3, with "jane", etc?

my $a = "13231313231313231";
say $a ~~ s:g/1/tom/;
say $a ~~ s:g/2/mary/;
say $a ~~ s:g/3/jane/;

Is there a good way to do all three steps at once?


Solution

  • For replacements like your example, you can use trans. Provide a list of what to search for and a list of replacements:

    my $a = "13231313231313231";
    $a .= trans(['1','2','3'] => ['tom', 'mary', 'jane']);
    say $a; 
    tomjanemaryjanetomjanetomjanemaryjanetomjanetomjanemaryjanetom
    

    For simple strings, you can simplify with word quoting:

    $a .= trans(<1 2 3> => <tom mary jane>);