Regex matching in Perl
Binding strings to patterns with =~, plus !~ and the /i flag.
use strict;
use warnings;
my $line = "Error: disk /dev/sda1 is 93% full";
# =~ binds a string to a pattern; !~ negates the match
print "flagged\n" if $line =~ /disk/;
print "shouting\n" if $line =~ /error/i;
print "network is fine\n" if $line !~ /eth\d/;
if ($line =~ /(\d+)% full/) {
print "usage at $1\n";
}
How it works
=~is true when the pattern matches somewhere in the string;!~when it does not./imakes the match case-blind, soerrorfindsError.- Parentheses capture the digits, and
$1holds them after a successful match.
Keywords and builtins used here
ifmyprintuse
The run, in numbers
- Lines
- 13
- Characters to type
- 312
- Tokens
- 49
- Three-star pace
- 60 tpm
At the three-star pace of 60 tokens a minute, this run takes about 49 seconds.
Step 1 of 3 in Regular expressions, step 7 of 27 in Language basics.