Substitution and tr///
Matching finds text; substitution changes it. The s/// operator replaces what a pattern matches, and tr/// translates individual characters.
s/PATTERN/REPLACEMENT/
use strict;
use warnings;
my $greeting = "Hello, World";
$greeting =~ s/World/Perl/;
print "$greeting\n";
my $spaces = "too many spaces";
$spaces =~ s/\s+/ /g; # /g replaces every match, not just the first
print "$spaces\n";
my $count = (my $csv = "a;b;c;d") =~ s/;/,/g;
print "$csv ($count replacements)\n";Hello, Perl
too many spaces
a,b,c,d (3 replacements)
s/// changes the variable in place and returns the number of substitutions made (or false if none).
Using captures in the replacement
The replacement part is like a double-quoted string, so it can use $1, $2 and named captures:
use strict;
use warnings;
my $date = "2024-12-25";
(my $us_date = $date) =~ s/(\d+)-(\d+)-(\d+)/$2\/$3\/$1/;
print "US format: $us_date\n";
my $name = "Lovelace, Ada";
$name =~ s/^(?<last>\w+), (?<first>\w+)$/$+{first} $+{last}/;
print "Name: $name\n";US format: 12/25/2024
Name: Ada Lovelace
(my $copy = $original) =~ s/.../.../; copies first and then modifies the copy, leaving the original untouched. It is a well-known idiom.
The /r modifier: return a new string
With /r, s/// leaves the original alone and returns the modified string. This is cleaner than the copy idiom and works nicely in map:
use strict;
use warnings;
my $title = "learning perl the fun way";
my $slug = $title =~ s/\s+/-/gr;
print "Title stays: $title\n";
print "Slug: $slug\n";
my @files = qw(report.TXT image.PNG notes.txt);
my @lower = map { s/\.(\w+)$/'.' . lc $1/er } @files;
print "@lower\n";Title stays: learning perl the fun way
Slug: learning-perl-the-fun-way
report.txt image.png notes.txt
The /e modifier: compute the replacement
With /e, the replacement is evaluated as Perl code, and its result is used as the replacement text:
use strict;
use warnings;
my $order = "3 apples at 2 each, 5 pears at 3 each";
(my $priced = $order) =~ s/(\d+) (\w+) at (\d+) each/"$1 $2 = " . $1 * $3/ge;
print "$priced\n";
my $template = "Hello {name}, your plan is {plan}.";
my %vars = (name => "Omar", plan => "Pro");
$template =~ s/\{(\w+)\}/$vars{$1} \/\/ "?"/ge;
print "$template\n";3 apples = 6, 5 pears = 15
Hello Omar, your plan is Pro.
The second example is a tiny template engine: every {word} is replaced by the value from the hash.
tr///: translating characters
tr/SEARCH/REPLACE/ (also spelled y///) replaces characters one for one. It does not use regexes, only character lists and ranges. It returns the number of characters it touched, which makes it a fast counter:
use strict;
use warnings;
my $dna = "ATGCGTTA";
(my $complement = $dna) =~ tr/ATGC/TACG/;
print "Complement: $complement\n";
my $shout = "quiet please";
$shout =~ tr/a-z/A-Z/;
print "$shout\n";
my $text = "Mississippi";
my $s_count = ($text =~ tr/s//); # empty replacement: count only
print "Letter s appears $s_count times\n";
my $squeezed = "boooook keeeeper" =~ tr/a-z//sr; # /s squeezes repeats, /r returns
print "$squeezed\n";
my $digits_only = "Call +1 (555) 010-9999" =~ tr/0-9//cdr; # /c complement, /d delete
print "$digits_only\n";Complement: TACGCAAT
QUIET PLEASE
Letter s appears 4 times
bok keper
15550109999
tr modifier |
Effect |
|---|---|
/d |
delete found characters that have no replacement |
/c |
complement: act on characters not in the search list |
/s |
squeeze runs of the same translated character into one |
/r |
return the new string instead of modifying |
Test yourself
What does $s =~ s/a/b/; do to "banana"?
bbnbnbbbnanabananabananb
What does the /r modifier do in s///r?
- Replaces from the right
- Returns the modified string and leaves the original unchanged
- Repeats the substitution
- Makes it recursive
How do you count the vowels in $word quickly?
$word =~ tr/aeiou//$word =~ s/aeiou//count($word, 'aeiou')$word =~ /aeiou/g