3

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.

2
  • Add this after your code : $tmp =~ s/\s*$//g; Commented Nov 16, 2016 at 8:10
  • @AbhiNickz: will do. Commented Nov 16, 2016 at 9:15

2 Answers 2

7

Can do without a regex as well

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

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

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


Updated to comments

If the original string contains yet other characters, can filter them out first

$tmp = join ' ', map { $repl{$_} } grep { /c|l|r/ } split '', $tmp;

or, use an empty list in the map for anything that isn't defined in the hash

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

This removes altogether everything other than c|l|r. To keep them in the result

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

which has them separated by space as well. To keep them together need to tweak it further.

Sign up to request clarification or add additional context in comments.

5 Comments

I'd suggest that a hash written with => would be a clearer way of showing what's happening here.
@zdim: Use of uninitialized value in join or string at a.pl line I am getting this error.
@ssr1012 What strings are you feeding to this? Whatever chars are in the string they have to be in the hash. If the string can have yet other ones, which you'd discard, this is easily adjusted, for example by adding grep { /c|l|r/ } after split (this would remove others altogether). Let me know.
@Sobrique Indeed. It was typed quickly and felt easy to read, but there is no reason for the shortcut. Thank you.
You could build the grep operation into the map if you just did a map { $repl{$_} // () } - so it'll return the looked up element or an empty list if there isn't one. (Or have it return a 'default' if you prefer)
6

You can use a hash of replacements in the substitution:

#! /usr/bin/perl
use warnings;
use strict;
use feature 'say';

my $tmp = "rrccllrrc";

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

$tmp =~ s/(.)/$replace{$1} /g;
chop $tmp;
say "<$tmp>";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.