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

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...', 1759406249, '216.73.216.42', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Perl/functions/s(114): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78