typestar

Substitution with s/// in Perl

Search and replace with s///: global edits, and /r when the original must survive.

use strict;
use warnings;

my $csv = "perl;ruby;go;rust";
$csv =~ s/;/, /g;
print "$csv\n";

# /r returns the edited copy and leaves the original alone
my $path = "/usr/local/share/doc";
my $mounted = $path =~ s{^/usr}{/mnt}r;
print "$path stays, $mounted is new\n";

my $spaced = "too   many    gaps";
$spaced =~ s/\s+/ /g;
print "$spaced\n";

my $greet = "hello, world";
$greet =~ s/(\w+)/\u$1/g;
print "$greet\n";

How it works

  1. s/;/, /g replaces every separator; without /g only the first would change.
  2. /r returns the edited copy instead of touching $path, and s{}{} swaps delimiters.
  3. s/\s+/ /g squeezes each whitespace run to one space; \u$1 uppercases each word.

Keywords and builtins used here

The run, in numbers

Lines
19
Characters to type
416
Tokens
69
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 69 seconds.

Type this snippet

Step 2 of 3 in Regular expressions, step 8 of 27 in Language basics.

← Previous Next →