Perl Basics   «Prev  Next»

Lesson 22

Perl Features for Web Programming using Regular Expressions in Perl

One of Perl’s most powerful features for web programming is its support for regular expressions. Regex allows you to search, match, and manipulate text with minimal code, an essential skill when working with form input, logs, or web content.

Example: Matching Words Containing "cat"

Suppose you have a list of words and you want to print all strings containing the substring cat:


my @words = (
  'laphroaig',
  'house cat',
  'catastrophe',
  'cat',
  'is awesome',
);

foreach my $word (@words) {
  if ( $word =~ /cat/ ) {
    print "$word\n";
  }
}
  

Output:

house cat
catastrophe
cat
  

How the Regex Operator Works

The operator =~ is called the binding operator. It applies a regular expression to a specific variable instead of the default $_.

For example, you can write the same loop more concisely:


foreach (@words) {
  if (/cat/) {
    print "$_\n";
  }
}

Negated Regex Matching

Perl also supports a negated binding operator, !~, which finds strings that do not match a pattern:


foreach my $word (@words) {
  if ( $word !~ /cat/ ) {
    print "$word\n";
  }
}
  

What’s Next

Regular expressions are the foundation for many web programming tasks, such as validating input or processing form data. In the next module, you’ll explore Web forms in detail, including: