Matching basics
The =~ operator tests whether a string contains a pattern.
In this page:
Matching basics
A pattern is written between slashes, as in /perl/, and the binding operator =~ applies it to a string. The match returns true or false, so it fits naturally in an if statement, and !~ negates the test. Without =~, a pattern is matched against the default variable $_.
Note:
Use a different delimiter such as m{...} when the pattern contains many slashes.
Example: Matching basics
use strict;
use warnings;
my $text = "The quick brown fox";
if ($text =~ /quick/) {
print "found 'quick'\n";
}
print "no 'slow'\n" if $text !~ /slow/;
print "starts with The\n" if $text =~ /^The/;
print "ends with fox\n" if $text =~ /fox$/;
for (qw(cat cart dog)) {
print "$_ matches ca\n" if /ca/;
}
my $path = "/usr/local/bin";
print "path matches\n" if $path =~ m{^/usr/local};
# Output:
# found 'quick'
# no 'slow'
# starts with The
# ends with fox
# cat matches ca
# cart matches ca
# path matches
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Writing = instead of =~ and assigning instead of matching
- Forgetting that a pattern matches anywhere in the string unless anchored
- Using == or eq to test for a pattern
Chapter Summary
- /pattern/ =~ string tests a match
- !~ tests for no match
- A match succeeds anywhere in the string
- $_ is the default target
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: