Test whether a string matches a pattern with the =~ operator and the match operator m//:
use strict; use warnings;
my $line = "Error: disk full on /dev/sda1";
if ($line =~ m/Error: (.+) on (.+)/) {
print "Message: $1\n"; # disk full
print "Device: $2\n"; # /dev/sda1
}
The substitution operator s/// replaces matches. Use the g flag for global replacement:
my $text = "the cat sat on the mat";
(my $copy = $text) =~ s/\bcat\b/dog/; # replace first
$text =~ s/at/AT/g; # replace all occurrences
print "$text\n"; # the cAT sAT on the mAT
Common modifiers: i (case-insensitive), m (multiline), s (. matches newline), x (allow whitespace and comments for readability):
my $email = '[email protected]';
if ($email =~ m/
^ # start of string
[\w.+-]+ # local part
@ # at symbol
[\w-]+ # domain
(?:\.[\w-]+)+ # TLD(s)
$ # end of string
/x) {
print "Valid email\n";
}