Search notes:

Perl function: s (substitute)

use warnings;
use strict;

my $string;

$string = "20 22";
$string =~ s/(\d+) (\d+)/$1 + $2/e;
print "$string\n";
# 42

$string = "hello world";
$string =~ s/(\w+) (\w+)/$1 . '-' . $2/e;
print "$string\n";
# hello-world

$string = "'hello' . ' ' . 'world'";
$string =~s/(.*)/$1/e;
print "$string\n";
# 'hello' . ' ' . 'world'

$string = "'hello' . ' ' . 'world'";
$string =~ s/(.*)/eval($1)/e;
print "$string\n";
# hello world

$string = "'hello' . ' ' . 'world'";
$string =~ s/(.*)/$1/ee;
print "$string\n";
# hello world
Github repository about-perl, path: /functions/s__e.pl
#!/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 substitution: replace and assign
Perl substitution: e flag
Perl: regular expression to substitute within matched region
Perl functions

Index