Substitution with s///

s///

The substitution operator takes a pattern, a replacement and a target joined by =~. It changes the variable in place and returns the number of replacements.

my $s = "disk full"; $s =~ s/full/almost full/; print "$s\n"; # disk almost full

perl demo.pl

disk almost full

Add an r flag to get a new string and leave the original alone. That form is the cleaner choice inside a larger expression:

my $s = "disk full"; $s =~ s/full/almost full/; my $clean = $s =~ s/almost //r; print "$clean / $s\n"; # disk full / disk almost full

perl demo.pl

disk full / disk almost full

The g flag

Without a flag only the first match is replaced. The g flag repeats until the pattern stops matching, which is what you want for cleanup passes.

my $path = "//var//log///app.log"; $path =~ s{/+}{/}g; print "$path\n"; # /var/log/app.log

perl demo.pl

/var/log/app.log

Different delimiters keep slashes readable: s{/+}{/}g means the same as s/\/+\//\//g and needs no escaping at all.

Captures in the replacement

Captures from the pattern are available in the replacement. Swap two fields of a date with three groups and no temporary variables:

my $date = "2026-10-27"; $date =~ s{(\d{4})-(\d{2})-(\d{2})}{$3/$2/$1}; print "$date\n"; # 27/10/2026

perl demo.pl

27/10/2026

Escape a literal dollar sign as \$ and a literal at sign inside the replacement, or Perl will try to interpolate them.

The e flag

In a substitution the replacement is a double-quoted string, not code. The e flag changes that: the replacement is evaluated as Perl, so any expression may compute the new text.

my $nums = "1 2 3"; $nums =~ s{(\d+)}{$1 * 10}ge; print "$nums\n"; # 10 20 30

perl demo.pl

10 20 30

With e, a typo becomes a runtime error inside a loop, so keep the expression small. If it needs more than one statement, write a subroutine and call it from the replacement instead.

tr///

For one-character-to-one-character changes, tr is faster and simpler than a pattern. It maps each character on the left to the character in the same position on the right, and returns the count of characters changed.

my $dna = "ACGT"; $dna =~ tr/ACGT/TGCA/; print "$dna\n"; # TGCA

perl demo.pl

TGCA

tr does not use regular expressions, so no anchors, no quantifiers and no captures. A range also works: tr/a-z/A-Z/ upper-cases ASCII letters, which is what uc does more quickly.

Next: split and join

Article author: Arthur Isaev