BudiBadu Logo
Samplebadu

Perl by Example: Regular Expressions

Perl 5

Pattern matching and text manipulation with this code example demonstrating binding operator for regex application, match operator with modifiers, substitution operator for replacement, capture groups with automatic variables, and metacharacter usage.

Code

#!/usr/bin/perl
use strict;
use warnings;

my $text = "The quick brown fox jumps over the lazy dog";

# Matching (=~)
if ($text =~ /fox/) {
    print "Found 'fox'\n";
}

# Case insensitive match (i modifier)
if ($text =~ /FOX/i) {
    print "Found 'FOX' (case insensitive)\n";
}

# Substitution (s///)
my $new_text = $text;
$new_text =~ s/dog/cat/;
print "New text: $new_text\n";

# Capture groups
my $email = "user\@example.com";
if ($email =~ /^(.+)\@(.+)$/) {
    print "User: $1\n";
    print "Domain: $2\n";
}

Explanation

Perl is renowned for its powerful regular expression engine providing flexible and concise pattern matching within text. The binding operator =~ applies a regex to a string, with the match operator m// (or just //) returning true if the pattern is found. Regular expressions support various metacharacters, quantifiers, and modifiers for complex pattern matching including . for any character, * for zero or more, + for one or more, and ? for zero or one.

Regex modifiers alter matching behavior:

  • i modifier enables case-insensitive matching
  • g modifier performs global matching finding all occurrences
  • m modifier treats string as multiple lines affecting ^ and $ anchors
  • s modifier treats string as single line making . match newlines
  • x modifier allows whitespace and comments in patterns for readability

The substitution operator s/pattern/replacement/ modifies strings in place, supporting the same modifiers as matching. Parentheses () create capture groups storing matched content in special variables $1, $2, $3, etc. These captures persist until the next successful match, enabling powerful text parsing and extraction. The $& variable contains the entire matched string, while contain text before and after the match.

Code Breakdown

8
$text =~ /fox/ binding operator applies regex pattern to string.
13
/FOX/i case-insensitive modifier matches regardless of case.
19
s/dog/cat/ substitution operator replaces first occurrence in place.
24-26
Parentheses create capture groups, matched content stored in $1, $2.