How can I use $_ to store my string, and then use another scalar variable to store the substituted string such that I have both the copies. Do we have a modifier to copy the default argument in some another variable?
#! /usr/bin/perl/
use warnings;
use strict;
$_ = "X is a good boy. X works daily and goes to school. X studies for 12 hours daily \n";
s/X/Sam/g;
print $_, "\n";
What I want in the end is the original $_ and the substituted string as well.
Edit: I used
my $new = s/X/Sam/gr
But I get an error related to build, and it doesnt solve the issue. I am using version 5.10.1
perl --version
This is perl, v5.10.1 (*) built for x86_64-linux-thread-multi
One way, of course, is to first copy the original and make the substitution on the copy.
( my $new = $_ ) =~ s/X/Sam/g;
Another way is to use the /r
modifier (introduced in v5.14). It returns the new string, leaving the original unchanged
my $new = $_ =~ s/X/Sam/gr;
Find it in perlop, under the bullet "s/PATTERN/REPLACEMENT/msixpodualngcer".
Note interesting uses in Examples. With /r
you can also do
my $new = s/X/Sam/gr;
Since /r
modifier is available on v5.14 or newer you may want to have use 5.014;
, not allowing the code to run at all on older Perls and documenting the required version. On the other hand, without that on an older Perl you get a specific error, with the location where unavailable features are used.
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