testing beginner

How to test regular expressions with like in Perl Test::More?

Question

How to test regular expressions with like in Perl Test::More?

In Perl, the Test::More module provides a convenient way to write tests, including testing whether a string matches a regular expression. The function like is specifically designed for this purpose: it tests if a string matches a regex pattern and reports whether the test passed or failed.

What does like do?

The like function takes two mandatory arguments and one optional argument:

  • $string: The string you want to test.
  • $regex: A compiled or literal regex to check against $string.
  • $test_name (optional): A description to identify the test in the output.

If $string matches $regex, the test passes; otherwise, it fails.

Basic example

Here’s a simple example demonstrating like in action:

use strict;
use warnings;
use Test::More tests => 3;

my $input = "Hello, Perl community!";

# Test if $input contains the word 'Perl'
like($input, qr/Perl/, 'String contains "Perl"');

# Test if $input ends with an exclamation mark
like($input, qr/!$/, 'String ends with "!"');

# Test if $input starts with 'hello' case-insensitive
like($input, qr/^hello/i, 'Starts with "hello", case-insensitive');

Running this script will output test results indicating success or failure for each regex.

Important Perl concepts illustrated

  • Regular expressions (regex): The qr// operator compiles a regex, making it easy to pass to like. For example, qr/Perl/ matches the substring "Perl".
  • Sigils: $input is a scalar variable holding the string to test.
  • Context: like returns a boolean test result but primarily reports to TAP (Test Anything Protocol) output.
  • TMTOWTDI: “There’s more than one way to do it” — instead of like you could manually match using =~ and ok, but like is clearer and idiomatic for regex tests.

Common pitfalls

  • Make sure the regex is properly quoted with qr// or bare // delimiters. Passing a plain string (e.g., "Perl") will test for string equality, not matching.
  • Remember to specify the total number of tests in Test::More with tests => N or use done_testing() to avoid warnings.
  • like is for regex matching. For exact string equality, use is.

Summary

Use like from Test::More to verify strings match regexes cleanly and idiomatically. It shows readable test output integrated with Perl’s TAP-based testing system. Just pass the string and a compiled regex, optionally labeling your test for clarity.

Verified Code

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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
1..3
ok 1 - String contains "Perl"
ok 2 - String ends with "!"
ok 3 - Starts with "hello", case-insensitive
STDERR
(empty)

Was this helpful?

Related Questions