ssr1012 ssr1012 - 1 year ago 81
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download