Skip to content
Perl

Regular Expressions

Perl is famous for its powerful regex support.

By EZ4Code Team
regexpattern

Code

my $text = "Hello, World! Email: [email protected]";

# Match
if ($text =~ /(\w+@(\w+)\.(\w+))/) {
  print "Email: $1\n";      # [email protected]
  print "Domain: $2\n";     # example
  print "TLD: $3\n";        # com
}

# Substitute
my $s = "Hello, World!";
$s =~ s/World/Perl/;          # "Hello, Perl!"
$s =~ s/(\w+)/\u$1/g;       # capitalize each word (global)

# Transliterate
my $lower = "HELLO";
$lower =~ tr/A-Z/a-z/;        # "hello"
my $count = ($lower =~ tr/l/L/);  # count replacements

# Split with regex
my @parts = split(/\s*,\s*/, "a, b ,c , d");

# Greedy vs non-greedy
"aaaa" =~ /a+a/;     # matches "aaaa" (greedy)
"aaaa" =~ /a+?a/;    # matches "aa" (lazy)

# Common patterns
my $ip = /(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/;
my $url = qr{https?://[\w.-]+(/[\w./?-]*)*};

# Named captures (Perl 5.10+)
if ($text =~ /(?<email>\w+@\w+\.\w+)/) {
  print $+{email};
}

Explanation

Perl regex is the gold standard — PCRE (Perl-Compatible Regular Expressions) is named after it. =~ binds a string to a regex. Captures go to $1, $2, ...; named captures to $+{name}. s/// substitutes; tr/// transliterates. Use qr// to precompile patterns. Greedy (*+) vs lazy (*?) modifiers control matching. Perl 5.10+ adds many features (?<name>...), (?>...), etc.

More Perl Snippets