Perl String - replace characters without forming a new variable

Is it possible to replace parts of a string without creating a whole new variable?

Now I am doing it like this:

$someString = "how do you do this"; $someString = s/how do/this is how/; 

What I'm trying to do is keep the original string ($ someString) and be able to replace multiple characters without changing the original string. I am more familiar with Javascript, and I can do this in your code without having to create / modify a variable.

 someString.replace(/how do/, "this is how") 

Any help is appreciated, thanks alot

+6
perl
source share
2 answers

Notice that I understand the question. If you want to leave the original string unchanged, you need to create a new variable.

 $newstring = $someString ; $newstring =~ s/how do/this is how/; 

Note that the operator =~ not =

I think now I see what you want - to return the changed string, and not change the variable. Perl 5.14 has a way to do this, but at the moment I don’t know how to do it. See Use the substitution flag / r to work with a copy in the Effective Perler .

Update The s/ / /r functionality has been in the Perl release for some time. You can do

 use 5.14.0 ; my $someString = "how do you do this"; say ($someString =~ s/how do/this is how/r) ; 
+11
source share

You can also use lambda, i.e.:

 sub { local $_ = shift; s/how do/this is how/; $_ }->($someString) 

This also saves $_ if you call lambda as sub { }->($_)

0
source share

All Articles