How do I perform a Perl substitution on a string while keeping the original?
Under use strict
, say:
(my $new = $original) =~ s/foo/bar/;
instead.
This is the idiom I've always used to get a modified copy of a string without changing the original:
(my $newstring = $oldstring) =~ s/foo/bar/g;
In perl 5.14.0 or later, you can use the new /r
non-destructive substitution modifier:
my $newstring = $oldstring =~ s/foo/bar/gr;
NOTE:
The above solutions work without g
too. They also work with any other modifiers.
SEE ALSO:perldoc perlrequick
: Perl regular expressions quick start
The statement:
(my $newstring = $oldstring) =~ s/foo/bar/g;
Which is equivalent to:
my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;
Alternatively, as of Perl 5.13.2 you can use /r
to do a non destructive substitution:
use 5.013;
#...
my $newstring = $oldstring =~ s/foo/bar/gr;