"Perl for Perl Newbies" - Part 2Regular ExpressionsSubstituting using Regular Expressions

7.7. Substituting using Regular Expressions

One can use regular expression to substitute an occurrence of a regular expression found inside a string to something else. The operator used for this is s/$exp_to_search/$exp_to_subs_for/. The following simple program replaces a number with the string "Some Number":

use strict;
use warnings;

my $string = shift;

$string =~ s/[0-9]+/Some Number/;

print $string, "\n";

Notice that in this case, only the first occurrence of the string will be substituted. The g switch which will be covered soon, enables us to substitute all of the occurrences.

One can include the captures that are matched in the expression as part of the substitution string. The first capture is $1, the second $2 etc.

Here's an example which reverses the order of two words at the beginning of a sentence:

use strict;
use warnings;

my $string = shift;

$string =~ s/^([A-Za-z]+) *([A-Za-z]+)/$2 $1/;

print $string, "\n";

Note

The $1, $2 variables are also available after the regular expression match or substitution is performed, and can be used inside your perl code.


Written by Shlomi Fish