Regular expression operators and functions

m/PATTERN/ - the match operator

The most basic regular expression operator is the matching operator, m/PATTERN/.

while (<>) {
        print if m/foo/;        # prints if a line contains "foo"
        print if m/foo/i;       # prints if a line contains "foo", "FOO", etc
        print if /foo/i;        # exactly the same; the m is optional
        print if m!http://!;    # using ! as an alternative delimiter
        

s/PATTERN/REPLACEMENT/ - the substitution operator

This is the substitution operator, and can be used to find text which matches a pattern and replace it with something else.

# fix some misspelt text

while (<>) {
        s/freind/friend/g;
        s/teh/the/g;
        s/jsut/just/g;
        print;
}

The above example can be found in exercises/spellcheck.pl.

Binding operators

If we want to use m// or s/// to operate on something other than $_ we need to use binding operators to bind the match to another string.

Table 8-1. Binding operators

OperatorMeaning
=~True if the pattern matches
!~True if the pattern doesn't match
print "Please enter your homepage URL: ";
my $url = <STDIN>;
if ($url =~ /geocities/) {
        print "Ahhh, I see you have a geocities homepage!\n";
}