ssr1012 ssr1012 - 3 months ago 26
Perl Question

Replace the string in Single shot using perl

My input:

my $tmp = "rrccllrrc";

Expected Output:

$tmp = "right right center center left left right right center"; #End should not be spaced definitely.

My Code:

$tmp=~s/c/center /g;
$tmp=~s/l/left /g;
$tmp=~s/r/right /g;

Someone can help to shorten the way to replace the regex as much possible.


Can do without a regex as well

my %repl = (c => 'center', l => 'left', r => 'right');

$tmp = join ' ', map { $repl{$_} }  split '', $tmp;

The split '' breaks a string into a list of its characters, and map uses the hash to replace each by its full word. The output list is joined by space.