Search notes:

Perl substitution: replace and assign

In order to assign the changed value of a substition to a new variable without changing the original value, the initialization of the new variable along with the assignment must be put into parentheses: (my $new_var = $orig_var) =~ s/.../.../;
#!/usr/bin/perl
use warnings;
use strict;

my $original  = "ADC DEDGH IDD DLMN OD";
#
#  The following changes $original and
#  assignes the number of changes
#  to $changed.
#
my $changed   = $original =~ s/D/*/g;

print "original: $original\n";
print "changed:  $changed\n";
#
# original: A*C *E*GH I** *LMN O*
# changed:  7

print "-------------------------------\n";


 my $original_  = "ADC DEDGH IDD DLMN OD";
#
#  The following first assigns $original_
#  to $changed_ (Note the paranthesis),
#  THEN changes the substituon on $changed_,
#  thus preserving $original_.
#
(my $changed_   = $original_) =~ s/D/*/g;

print "original_: $original_\n";
print "changed_:  $changed_\n";
#  
# original_: ADC DEDGH IDD DLMN OD
# changed_:  A*C *E*GH I** *LMN O*
Github repository about-perl, path: /functions/s__replace_and_assign.pl

See also

Perl function: s (substitute)
Perl substitution: e flag
Perl functions

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1759397903, '216.73.216.42', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Perl/functions/s__replace_and_assign(81): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78