The most basic regular expression operator is the matching operator, m/PATTERN/.
Works on $_ by default.
In scalar context, returns true (1) if the match succeeds, or false (the empty string) if the match fails.
In list context, returns a list of any parts of the pattern which are enclosed in parentheses. If there are no parentheses, the entire pattern is treated as if it were parenthesized.
The m is optional if you use slashes as the pattern delimiters.
If you use the m you can use any delimiter you like instead of the slashes. This is very handy for matching on strings which contain slashes, for instance directory names or URLs.
Using the /i modifier on the end makes it case insensitive.
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 |
This is the substitution operator, and can be used to find text which matches a pattern and replace it with something else.
Works on $_ by default.
In scalar context, returns the number of matches found and replaced.
In list context, behaves the same as in scalar context and returns the number of matches found and replaced.
You can use any delimiter you want, the same as the m// operator.
Using /g on the end of it matches globally, otherwise matches (and replaces) only the first instance of the pattern.
Using the /i modifier makes it case insensitive.
# 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.
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
Operator | Meaning |
---|---|
=~ | 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"; } |