9

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
lisprogtor
  • 5,677
  • 11
  • 17

2 Answers2

17

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>);
Curt Tilmes
  • 3,035
  • 1
  • 12
  • 24
  • 4
    I had an answer like yours queued up hours ago but then got sidetracked by its many wrinkles. Perhaps that's why you wrote "simple replacements"? It works for complex replacements too. For example you can list regexes on the LHS. But in general `trans` DWEMs. I just made DWEM up. It'll do for this comment. A DWEM is like a DWIM but the *I* is an expert. Imo the [`trans` doc](https://docs.perl6.org/routine/trans) is opaque at first read. It also seems quite incomplete. I'm working on a gist trying to cover `trans`. If I get it done I'll add a link to it as a comment here. – raiph Sep 04 '18 at 11:49
9

The simplest way it probably to make a Map of your substitutions and then reference it.

my $a = "123123";
my $map = Map.new(1 => "tom", 2 => "mary", 3 => "jane"); 
$a ~~ s:g/\d/$map{$/}/; 
say $a
"tomemaryjanetommaryjane"

If you only want to map certain values you can update your match of course :

my $a = "12341234";
my $map = Map.new(1 => "tom", 2 => "mary", 3 => "jane"); 
$a ~~ s:g/1 || 2 || 3/$map{$/}/; 
say $a
"tomemrayjane4tommaryjane4"
Scimon Proctor
  • 4,558
  • 23
  • 22
  • Thank you very much Scimon !!! I was think something like your answer, but I wonder why I seemed to have a mental block at that time :-) Thanks !!! – lisprogtor Sep 05 '18 at 07:57