typestar

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

  1. =~ is true when the pattern matches somewhere in the string; !~ when it does not.
  2. /i makes the match case-blind, so error finds Error.
  3. Parentheses capture the digits, and $1 holds them after a successful match.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Regular expressions, step 7 of 27 in Language basics.

← Previous Next →