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

132,309

Solution 1

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'

Solution 2

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";

Solution 3

print "bla: ", $myvar =~ tr{a}{b},"\n";

Solution 4

print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;
Share:
132,309
sleske
Author by

sleske

Software developer, mathematician SOreadytohelp

Updated on July 16, 2022

Comments

  • sleske
    sleske almost 2 years

    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?