Replace and save in another scalar

How can I use $ _ to store my string, and then use another scalar variable to store the replaced string so that I have both instances. Do we have a modifier to copy the default argument to 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";

In the end, I want the original $ _ and the substituted string to be there as well.

Edit: I used

my $new = s/X/Sam/gr

But I get an error related to the assembly, and it does not solve the problem. I am using version 5.10.1

perl --version

This is perl, v5.10.1 (*) built for x86_64-linux-thread-multi
+4
source share
3 answers

One way, of course, is to first copy the original and replace it with copies.

( my $new = $_ ) =~ s/X/Sam/g;

- /r ( v5.14). ,

my $new = $_ =~ s/X/Sam/gr;

perlop "s/PATTERN/REPLACEMENT/msixpodualngcer".

. /r

my $new = s/X/Sam/gr;

/r v5.14 , use 5.014;, Perls . , Perl , , .

+7

$_ - , , . , $_ . , , , ...

$orig = $_;
$changed = $_;
$changed = s/X/Sam/g;
print "CHANGED: ".$changed."\bORIGINAL: ".$orig\n";
+1

You can use the following if you need compatibility with versions of Perl older than 5.14:

#! /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";
my $m;
($m = $_)=~s/X/Sam/g;
print $m, "\n";

It $mstores the changed data, but $_remains unchanged.

+1
source

Source: https://habr.com/ru/post/1670504/


All Articles