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
s/;/, /greplaces every separator; without/gonly the first would change./rreturns the edited copy instead of touching$path, ands{}{}swaps delimiters.s/\s+/ /gsqueezes each whitespace run to one space;\u$1uppercases each word.
Keywords and builtins used here
myprintuse
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.
Step 2 of 3 in Regular expressions, step 8 of 27 in Language basics.