← Back to Perl Course | Chapter 4: Regular Expressions | Lesson 1 of 7

Matching basics

The =~ operator tests whether a string contains a pattern.

In this page:

  1. Matching basics

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

perl
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
Common Mistakes
  1. Writing = instead of =~ and assigning instead of matching
  2. Forgetting that a pattern matches anywhere in the string unless anchored
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.