Perl 101 (part 6) - The Perl Toolbox - Engry Young Men (
Page 3 of 8 )
In addition to simple
matching, Perl also allows you to perform substitutions.
Take a look at
our next example, which prompts you to enter a line of text, and then replaces
all occurrences of the letter "a" with the letter "e".
#!/usr/bin/perl
# get a line of input
print "Gimme a line!\n";
$line = ;
chomp ($line);
# substitute with the substitution operator
$line =~ s/a/e/;
# and print
print $line;
In this case, we've used Perl's substitution operator - it looks like this:
s/search-pattern/replacement-pattern/
In the example above, the line
$line =~ s/a/e/;
simply means "substitute a with e in the scalar variable $line".
And
here's the output:
Gimme a line!
angry young man
engry young man
Ummm...didn't work quite as advertised, did it? All it did was replace the first
occurrence of the letter "a". How about adding the "g" operator, which does a
global search-and-replace?
#!/usr/bin/perl
# get a line of input
print "Gimme a line!\n";
$line = ;
chomp ($line);
# substitute with the substitution operator
$line =~ s/a/e/g;
# and print
print $line;
And this time,
angry young man
is replaced with
engry young men
Much better! But what if your sentence contains an upper-case "a", also known as
"A". Well, that's why Perl also has the case-insensitivity operator "i", which
takes care of that last niggling problem:
#!/usr/bin/perl
# get a line of input
print "Gimme a line!\n";
$line = ;
chomp ($line);
# substitute with the substitution operator
$line =~ s/a/e/gi;
# and print
print $line;
And the output:
Gimme a line!
Angry young man
Engry young men
Of course, we're just scratching the tip of the regex iceberg here. Things get
even more interesting when you start using patterns and metacharacters instead
of actual words...
This article copyright Melonfire
2000. All rights reserved.