The substitution operator replaces matching text with new text.

substitution A substitution uses `s/pattern/replacement/` to change matching text.

Substitution

phrase
substitution.pl
Replay: real traced execution (multi-file project)
use strict;
use warnings;

my $phrase = "red fish red";
my $changed = $phrase;
my $count = ($changed =~ s/red/gold/g);

print "phrase=$phrase\n";
print "changed=$changed\n";
print "count=$count\n";
use strict;
use warnings;

my $phrase = "blue fish";
my $changed = $phrase;
my $count = ($changed =~ s/red/gold/g);

print "phrase=$phrase\n";
print "changed=$changed\n";
print "count=$count\n";
use strict;
use warnings;

my $phrase = "red bird";
my $changed = $phrase;
my $count = ($changed =~ s/red/gold/g);

print "phrase=$phrase\n";
print "changed=$changed\n";
print "count=$count\n";
  1. $phrase ← red fish red, $changed ← red fish red, $count ← 2

    4my $phrase→ red fish red = "red fish red"; #@phrase="blue fish", "red bird"5my $changed→ red fish red = $phrasered fish red;6my $count→ 2 = ($changed→ gold fish gold =~ s/red/gold/g);78print "phrase=$phrasered fish red\n";9print "changed=$changedgold fish gold\n";10print "count=$count2\n";
    outputphrase=red fish red
    changed=gold fish gold
    count=2
  1. $phrase ← blue fish, $changed ← blue fish, $count ← (empty)

    4my $phrase→ blue fish = "blue fish";5my $changed→ blue fish = $phraseblue fish;6my $count→ (empty) = ($changedblue fish =~ s/red/gold/g);78print "phrase=$phraseblue fish\n";9print "changed=$changedblue fish\n";10print "count=$count(empty)\n";
    outputphrase=blue fish
    changed=blue fish
    count=
  1. $phrase ← red bird, $changed ← red bird, $count ← 1

    4my $phrase→ red bird = "red bird";5my $changed→ red bird = $phrasered bird;6my $count→ 1 = ($changed→ gold bird =~ s/red/gold/g);78print "phrase=$phrasered bird\n";9print "changed=$changedgold bird\n";10print "count=$count1\n";
    outputphrase=red bird
    changed=gold bird
    count=1

Follow the Replacement

  1. $phrase starts as red fish red.
  2. $changed starts as the same text.
  3. s/red/gold/g replaces every red in $changed.
  4. Two replacements happen.
  5. The program prints changed=gold fish gold and count=2. | phrase | changed | count | | --- | --- | --- | | red fish red | gold fish gold | 2 | | blue fish | blue fish | 0 | | red bird | gold bird | 1 |

Exercise: substitution.pl

Reproduce phrase=red fish red, changed=gold fish gold, and count=2, then use the pinned phrase variants blue fish and red bird to predict count=0 and count=1.