Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Use s/ (replace) and return new string [duplicate]

In Perl, the operator s/ is used to replace parts of a string. Now s/ will alter its parameter (the string) in place. I would however like to replace parts of a string befor printing it, as in

print "bla: ", replace("a","b",$myvar),"\n"; 

Is there such replace function in Perl, or some other way to do it? s/ will not work directly in this case, and I'd like to avoid using a helper variable. Is there some way to do this in-line?

like image 310
sleske Avatar asked Aug 09 '10 13:08

sleske


1 Answers

require 5.013002; # or better:    use Syntax::Construct qw(/r); print "bla: ", $myvar =~ s/a/b/r, "\n"; 

See perl5132delta:

The substitution operator now supports a /r option that copies the input variable, carries out the substitution on the copy and returns the result. The original remains unmodified.

my $old = 'cat'; my $new = $old =~ s/cat/dog/r; # $old is 'cat' and $new is 'dog' 
like image 101
daxim Avatar answered Sep 25 '22 05:09

daxim