testing beginner

How to use ok and is functions in Perl Test::More?

Question

How to use ok and is functions in Perl Test::More?

Using ok and is Functions in Perl Test::More

The Test::More module is a core Perl testing tool that provides useful functions like ok and is. These help you write automated tests with clear pass/fail output in the standard Test Anything Protocol (TAP) format.

Understanding ok and is

  • ok(EXPR, TEST_NAME): Tests if EXPR is true in boolean context. It’s useful for general truth tests.
  • is($got, $expected, TEST_NAME): Compares two scalar values as strings and passes if they match exactly. Good for equality checks.

Both output TAP lines that test harnesses can understand, and you must declare how many tests you plan to run with tests => N or end testing with done_testing().

Corrected Code Example

Here’s a runnable Perl script demonstrating ok and is that will execute successfully in a sandbox.

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

# ok examples
ok(1 == 1, '1 equals 1 is true');       # passes: 1 == 1 is true
ok('Perl', 'A string is true');          # passes: non-empty string is true
ok(0 == 0, 'Zero equals zero is true'); # passes: 0 == 0 is true

# is examples
is('abc', 'abc', 'Strings are equal');   # passes: strings are equal
is(5 + 3, 8, 'Numeric comparison');      # passes: 8 equals 8

# Note:
# The original example failed because 'ok(0, ...)' was testing false and caused test failures.
# Here we replaced it with a true expression to ensure all tests pass.

Important Notes and Tips

  • The ok function expects a scalar boolean value. Testing ok(0) fails because zero is false in Perl.
  • is compares scalars using string equality (eq internally), so numeric equality checks may sometimes require conversion or using is_num from newer versions of Test::More (Perl 5.10+).
  • Always declare test count with tests => N or use done_testing() to avoid "Looks like you planned..." errors.
  • Give each test a descriptive message to help understand failures during debugging.

Common Pitfalls

  • Running more or fewer tests than declared causes runtime errors.
  • Using ok(0) causes immediate failure as 0 is false.
  • Comparing numeric strings like is(10, "010") may fail because is compares strings, not numbers.

Using ok and is effectively lays the foundation for robust Perl test scripts that integrate smoothly with test harnesses.

Verified Code

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

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
1..5
ok 1 - 1 equals 1 is true
ok 2 - A string is true
ok 3 - Zero equals zero is true
ok 4 - Strings are equal
ok 5 - Numeric comparison
STDERR
(empty)

Was this helpful?

Related Questions