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.
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
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";
}
}
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";
}
}
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: