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 tolike. For example,qr/Perl/matches the substring "Perl". - Sigils:
$inputis a scalar variable holding the string to test. - Context:
likereturns 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
likeyou could manually match using=~andok, butlikeis 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::Morewithtests => Nor usedone_testing()to avoid warnings. likeis for regex matching. For exact string equality, useis.
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
1..3
ok 1 - String contains "Perl"
ok 2 - String ends with "!"
ok 3 - Starts with "hello", case-insensitive
(empty)Was this helpful?
Related Questions
- How to use Test::Deep for complex data structure comparison?
- How to test Mojolicious applications in Perl?
- How to test HTTP responses with Test::WWW::Mechanize in Perl?
- How to use prove command to run Perl tests?
- How to test database code with Test::mysqld in Perl?
- How to use Test::Fatal for exception testing in Perl?