Is it possible to replace parts of a string without having to create a whole new variable?
Right now I do it like this:
$someString = "how do you do this";
$someString = s/how do/this is how/;
What I am trying to do is keep the original string ($someString) and be able to substitute a few characters without modifying the original string. Im more familiar with Javascript and I can do it like this in your code without having to create/modify a variable.
someString.replace(/how do/, "this is how")
Any help is appreciated, thanks alot
Note quite sure 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 is =~
not =
addition I think I now see what you want - to return the changed string rather than modify a variable. There will be a way to do this in Perl 5.14 but I am not aware of a way at present. See Use the /r substitution flag to work on a copy at The Effective Perler.
Update
The s/ / /r
functionallity has been in released Perl 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) ;
You may also use lambda, i.e.:
sub { local $_ = shift; s/how do/this is how/; $_ }->($someString)
This also preserves $_
in case you call the lambda as sub { }->($_)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With