Perl: use s / (replace) and return a new line

In Perl, the s/ operator is used to replace parts of a string. Now s/ will change its parameter (string) in place. I would, however, replace parts of the line before printing, as in

 print "bla: ", replace("a","b",$myvar),"\n"; 

Is there such a replace function in Perl or some other way to do this? s/ will not work directly in this case, and I would like to avoid using an auxiliary variable. Is there any way to do this online?

+29
source share
5 answers

Unverified:

 require 5.013002; print "bla: ", $myvar =~ s/a/b/r, "\n"; 

See perl5132delta :

The substitution operator now supports the / r option, which copies the input variable, performs 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' 
+64
source

If you have Perl 5.14 or higher, 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 by using the do() block with a temporary lexical variable, for example:

 print "bla: ", do { (my $tmp = $myvar) =~ s/a/b/; $tmp }, "\n"; 
+4
source
 print "bla: ", $myvar =~ tr{a}{b},"\n"; 
+2
source
 print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1; 
+1
source

If you really want this, you can make your own, but I wouldn’t do it because you have much more functionality with s/// ... you could create this functionality in your function, but why recreate what 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; } 
0
source

All Articles