Replace a string in a single frame using perl

My input:

my $tmp = "rrccllrrc";

Expected Result:

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

My code is:

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

Someone can help shorten the regexp replacement time as much as possible.

+4
source share
2 answers

Can be done without regular expression

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

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

split with a template ''splits the string into a list of its characters and map uses a hash to replace each with its full word. The output list mapis space-joined.


Updated for comments

If the source string contains more other characters, you can filter them first

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

or, use an empty list in mapfor anything that is not defined in the hash

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

, c|l|r.

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

. , .

+8

:

#! /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>";
+7

Source: https://habr.com/ru/post/1660906/


All Articles