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
Scalars, Arrays, and Hashes
Perl's three main data types with sigils.
Subroutines and References
Define subs and use references for complex data.
Complex Data Structures
Build nested structures with references.
Modules and Packages
Create reusable modules with package keyword.
File I/O
Read and write files with filehandles.
OOP with Moose
Modern object-oriented programming in Perl.