This question already has answers here:
Closed 5 months ago.
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?
Untested:
require 5.013002;
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: ", $myvar =~ tr{a}{b},"\n";
print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;
If you really want, you can make your own, but I wouldn't because you have much more functionality with s///
... you could build that functionality into your function, but why recreate something that already exists?
#!/usr/bin/perl -w
use strict;
main();
sub main{
my $foo = "blahblahblah";
print '$foo: ' , replace("lah","ar",$foo) , "\n"; #$foo: barbarbar
}
sub replace {
my ($from,$to,$string) = @_;
$string =~s/$from/$to/ig; #case-insensitive/global (all occurrences)
return $string;
}