Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl6 Simultaneous substitutions with s///?

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

like image 381
lisprogtor Avatar asked Sep 04 '18 03:09

lisprogtor


2 Answers

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>);
like image 50
Curt Tilmes Avatar answered Oct 10 '22 21:10

Curt Tilmes


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"
like image 36
Scimon Proctor Avatar answered Oct 10 '22 22:10

Scimon Proctor