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 3 steps at once?
Thanks !!!
lisprog
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>);
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With