regex intermediate

How to use the qr// operator to compile regex in Perl?

Question

How to use the qr// operator to compile regex in Perl?

Using the qr// Operator to Compile Regex in Perl

The qr// operator in Perl provides a way to compile a regular expression and save it as a reusable regex object. This compiled regex can then be used later in matching operations, increasing code clarity and potential performance benefits when the same pattern is used multiple times.

Perl’s regex system typically evaluates patterns on the fly, but qr// allows you to pre-compile the pattern once and reuse it. This fits with Perl’s "There's more than one way to do it" (TMTOWTDI) philosophy by adding flexibility for regex management.

Basic Usage

Using qr// you can create a regex object, which behaves like a scalar but is internally a compiled regex pattern:


my $re = qr/abc/;    # compiled regex for matching "abc"

You can then use $re in pattern matching with =~ or m//:


if ("abcdef" =~ $re) {
    print "Matched!\n";
}

Advantages of qr//

  • Reusability: Define the regex once and use multiple times in your program.
  • Clarity: Naming the pattern improves readability in complex regex-heavy code.
  • Modifiers: You can include regex modifiers directly inside qr// like i, m, s.
  • Interpolation: You can interpolate variables safely, avoiding quoting issues.

Example Showing Compilation and Reuse


#!/usr/bin/perl
use strict;
use warnings;

# Compile a regex with case-insensitive modifier
my $word_re = qr/\bhello\b/i;

my @test_strings = (
    "Hello world",
    "Say hello!",
    "No greetings here",
);

foreach my $line (@test_strings) {
    if ($line =~ $word_re) {
        print "'$line' contains the word 'hello'\n";
    } else {
        print "'$line' does NOT contain the word 'hello'\n";
    }
}

This script compiles a regex that matches the word "hello" case-insensitively, then tests several strings against it. The output will be:


'Hello world' contains the word 'hello'
'Say hello!' contains the word 'hello'
'No greetings here' does NOT contain the word 'hello'

Additional Notes and Gotchas

  • Context: The qr// returns a regex object (blessed scalar) which is treated as a pattern in matching. It must be used on the right side of =~ or with m//.
  • Modifiers: You can add modifiers inside qr//, e.g., qr/abc/i for case-insensitive, or outside when interpolated.
  • Interpolation: Variables inside qr// are interpolated just like double-quoted strings, so be careful to escape special characters if needed.
  • Version: The qr// operator has been available since Perl 5.6, with enhanced features in newer versions, but basic usage is consistent across Perl 5.8+.

Summary

The qr// operator is a handy tool in Perl for compiling regex patterns ahead of time. It improves readability, maintainability, and sometimes performance, especially in complex or repeatedly executed pattern matching code. Use qr// when you want to define your pattern once and use it many times.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 5ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
(empty)
STDERR
(empty)

Was this helpful?

Related Questions