Perl: Use s/ (replace) and return new string
print "bla: ", $myvar =~ tr{a}{b},"\n";
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'
If you have Perl 5.14 or greater, you can use the /r
option with the substitution operator to perform non-destructive substitution:
print "bla: ", $myvar =~ s/a/b/r, "\n";
In earlier versions you can achieve the same using a do()
block with a temporary lexical variable, e.g.:
print "bla: ", do { (my $tmp = $myvar) =~ s/a/b/; $tmp }, "\n";
print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;