Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl String - Substitute Characters without forming a new variable

Tags:

perl

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

like image 503
bryan sammon Avatar asked Jan 08 '11 19:01

bryan sammon


2 Answers

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) ;
like image 183
justintime Avatar answered Nov 15 '22 22:11

justintime


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 { }->($_)

like image 30
Stelf Avatar answered Nov 15 '22 21:11

Stelf