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?
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With