More(3)

🌸 NAME 🌸

Carp::Assert::More β€” Convenience assertions for common situations. This is the More(3) page from User Contributed Perl Documentation, and it’s here to make your assertion habit feel way less like homework. πŸ’–

✨ VERSION ✨

Version 2.9.0 β€” short, sweet, iconic.

πŸ¦‹ SYNOPSIS πŸ¦‹

A set of convenience functions for common assertions.

use Carp::Assert::More;

my $obj = My::Object;
assert_isa( $obj, 'My::Object', 'Got back a correct object' );

πŸ’… DESCRIPTION πŸ’…

Carp::Assert::More is a convenient set of assertions to make the habit of writing assertions even easier. No cap.

Everything in here is effectively syntactic sugar. There’s no technical difference between calling one of these functions:

assert_datetime( $foo );
assert_isa( $foo, 'DateTime' );

that are provided by Carp::Assert::More and calling these assertions from Carp::Assert

assert( defined $foo );
assert( ref($foo) eq 'DateTime' );

My intent here is to make common assertions easy so that we as programmers have no excuse to not use them. Periodt.


πŸŽ€ SIMPLE ASSERTIONS πŸŽ€

assert( $condition [, $name] )

Asserts that $condition is a true value. This is the same as assert in Carp::Assert, provided as a convenience.

assert_is( $string, $match [,$name] )

Asserts that $string is the same string value as $match.

undef is not converted to an empty string. If both strings are undef, they match. If only one string is undef, they don’t match. πŸ’€

assert_isnt( $string, $unmatch [,$name] )

Asserts that $string does NOT have the same string value as $unmatch.

undef is not converted to an empty string.

assert_cmp( $x, $op, $y [,$name] )

Asserts that the relation $x $op $y is true. It tells you why the comparison failed, rather than simply that it did fail, by giving better diagnostics than a plain assert(), as well as showing the operands in the stacktrace. It’s giving detective energy. πŸ”

Plain assert():

assert( $nitems <= 10, 'Ten items or fewer in the express lane' );
Assertion (Ten items or fewer in the express lane) failed!
Carp::Assert::assert("", "Ten items or fewer in the express lane") called at foo.pl line 12

With assert_cmp():

assert_cmp( $nitems, '<=', 10, 'Ten items or fewer in the express lane' );
Assertion (Ten items or fewer in the express lane) failed!
Failed: 14 <= 10
Carp::Assert::More::assert_cmp(14, "<=", 10, "Ten items or fewer in the express lane") called at foo.pl line 11

The following operators are supported:

  • == β€” numeric equal
  • != β€” numeric not equal
  • > β€” numeric greater than
  • >= β€” numeric greater than or equal
  • < β€” numeric less than
  • <= β€” numeric less than or equal
  • lt β€” string less than
  • le β€” string less than or equal
  • gt β€” string less than
  • ge β€” string less than or equal

(Yes, gt and ge are listed as β€œstring less than” on the page β€” keeping the original wording exactly, bestie. πŸ’€)

There is no support for eq or ne because those already have assert_is and assert_isnt, respectively.

If either $x or $y is undef, the assertion will fail.

If the operator is numeric, and $x or $y are not numbers, the assertion will fail.

assert_like( $string, qr/regex/ [,$name] )

Asserts that $string matches qr/regex/.

The assertion fails if either the string or the regex is undef.

assert_unlike( $string, qr/regex/ [,$name] )

Asserts that $string matches qr/regex/.

(The page literally says β€œmatches” here for assert_unlike β€” I’m not fixing it, I’m just reporting the vibe. πŸ’€)

The assertion fails if the regex is undef.

assert_defined( $this [, $name] )

Asserts that $this is defined.

assert_undefined( $this [, $name] )

Asserts that $this is not defined.

assert_nonblank( $this [, $name] )

Asserts that $this is not a reference and is not an empty string.


πŸ”₯ BOOLEAN ASSERTIONS πŸ”₯

These boolean assertions help make diagnostics more useful.

If you use assert with a boolean condition:

assert( $x && $y, 'Both X and Y should be true' );

you can’t tell why it failed:

Assertion (Both X and Y should be true) failed!
 at .../Carp/Assert/More.pm line 123
        Carp::Assert::More::assert(undef, 'Both X and Y should be true') called at foo.pl line 16

But if you use assert_and:

assert_and( $x, $y, 'Both X and Y should be true' );

the stacktrace tells you which half of the expression failed.

Assertion (Both X and Y should be true) failed!
 at .../Carp/Assert/More.pm line 123
        Carp::Assert::More::assert_and('thing', undef, 'Both X and Y should be true') called at foo.pl line 16

assert_and( $x, $y [, $name] )

Asserts that both $x and $y are true.

assert_or( $x, $y [, $name] )

Asserts that at least one of $x or $y is true.

assert_xor( $x, $y [, $name] )

Asserts that $x is true, or $y is true, but not both.


🌈 NUMERIC ASSERTIONS 🌈

assert_numeric( $n [, $name] )

Asserts that $n looks like a number, according to Scalar::Util::looks_like_number. undef will always fail.

assert_integer( $this [, $name ] )

Asserts that $this is an integer, which may be zero or negative.

assert_integer( 0 );      # pass
assert_integer( 14 );     # pass
assert_integer( -14 );    # pass
assert_integer( '14.' );  # FAIL

assert_nonzero( $this [, $name ] )

Asserts that the numeric value of $this is defined and is not zero.

assert_nonzero( 0 );    # FAIL
assert_nonzero( -14 );  # pass
assert_nonzero( '14.' );  # pass

assert_positive( $this [, $name ] )

Asserts that $this is defined, numeric and greater than zero.

assert_positive( 0 );    # FAIL
assert_positive( -14 );  # FAIL
assert_positive( '14.' );  # pass

assert_nonnegative( $this [, $name ] )

Asserts that $this is defined, numeric and greater than or equal to zero.

assert_nonnegative( 0 );      # pass
assert_nonnegative( -14 );    # FAIL
assert_nonnegative( '14.' );  # pass
assert_nonnegative( 'dog' );  # pass

assert_negative( $this [, $name ] )

Asserts that the numeric value of $this is defined and less than zero.

assert_negative( 0 );       # FAIL
assert_negative( -14 );     # pass
assert_negative( '14.' );   # FAIL

assert_nonzero_integer( $this [, $name ] )

Asserts that the numeric value of $this is defined, an integer, and not zero.

assert_nonzero_integer( 0 );      # FAIL
assert_nonzero_integer( -14 );    # pass
assert_nonzero_integer( '14.' );  # FAIL

assert_positive_integer( $this [, $name ] )

Asserts that the numeric value of $this is defined, an integer and greater than zero.

assert_positive_integer( 0 );     # FAIL
assert_positive_integer( -14 );   # FAIL
assert_positive_integer( '14.' ); # FAIL
assert_positive_integer( '14' );  # pass

assert_nonnegative_integer( $this [, $name ] )

Asserts that the numeric value of $this is defined, an integer, and not less than zero.

assert_nonnegative_integer( 0 );      # pass
assert_nonnegative_integer( -14 );    # FAIL
assert_nonnegative_integer( '14.' );  # FAIL

assert_negative_integer( $this [, $name ] )

Asserts that the numeric value of $this is defined, an integer, and less than zero.

assert_negative_integer( 0 );      # FAIL
assert_negative_integer( -14 );    # pass
assert_negative_integer( '14.' );  # FAIL

assert_numeric_between( $n, $lo, $hi [, $name ] )

Asserts that the value of $this is defined, numeric and between $lo and $hi, inclusive.

(Yes, the prose says $this even though the signature is $n β€” page is quirky, keeping it. 🫢)

assert_numeric_between( 15, 10, 100 );  # pass
assert_numeric_between( 10, 15, 100 );  # FAIL
assert_numeric_between( 3.14, 1, 10 );  # pass

assert_integer_between( $n, $lo, $hi [, $name ] )

Asserts that the value of $this is defined, an integer, and between $lo and $hi, inclusive.

assert_integer_between( 15, 10, 100 );  # pass
assert_integer_between( 10, 15, 100 );  # FAIL
assert_integer_between( 3.14, 1, 10 );  # FAIL

πŸŽ€ REFERENCE ASSERTIONS πŸŽ€

  • assert_isa( $this, $type [, $name ] ) β€” bestie, this one checks that $this is an object of type $type. That's it. That's the vibe check.
  • assert_isa_in( $obj, \@types [, $description] ) β€” slay, now you can allow multiple types at once. Asserts that the blessed $obj isa one of the types chillin' inside "\@types".
assert_isa_in( $obj, [ 'My::Foo', 'My::Bar' ], 'Must pass either a Foo or Bar object' );
  • assert_empty( $this [, $name ] ) β€” πŸ’… $this has to be a ref to either a hash or an array, mkay? Then it asserts that the collection contains no elements (so, literally empty). Heads up though: it will assert with its own message, not $name, unless you hand it a hash or array ref β€” periodt. Also it's OK if $this has been blessed into objecthood, but the semantics of checking an object to see if it does not have keys (for a hashref) or returns 0 in scalar context (for an array ref) may not be what you want. Just so you know. πŸ™ˆ
assert_empty( 0 );       # FAIL
assert_empty( 'foo' );   # FAIL
assert_empty( undef );   # FAIL
assert_empty( {} );      # pass
assert_empty( [] );      # pass
assert_empty( {foo=>1} );# FAIL
assert_empty( [1,2,3] ); # FAIL
  • assert_nonempty( $this [, $name ] ) β€” the reverse icon. $this must be a ref to either a hash or an array, and it asserts that the collection contains at least 1 element. Same caveat energy as above: it will assert with its own message, not $name, unless given a hash or array ref. And again, it's OK if $this has been blessed into objecthood, but the semantics of checking an object to see if it has keys (for a hashref) or returns >0 in scalar context (for an array ref) may not be what you want. 🫢
assert_nonempty( 0 );       # FAIL
assert_nonempty( 'foo' );   # FAIL
assert_nonempty( undef );   # FAIL
assert_nonempty( {} );      # FAIL
assert_nonempty( [] );      # FAIL
assert_nonempty( {foo=>1} );# pass
assert_nonempty( [1,2,3] ); # pass
  • assert_nonref( $this [, $name ] ) β€” asserts that $this is not undef and not a reference. Simple. Clean. We love a low-drama assertion. ✨
  • assert_hashref( $ref [,$name] ) β€” asserts that $ref is defined, and is a reference to a (possibly empty) hash.

NB: this method returns false for objects, even those whose underlying data is a hashref. And that's exactly as it should be, under these assumptions:

  1. you shouldn't rely on the underlying data structure of a particular class, and
  2. you should use "assert_isa" instead.
  • assert_hashref_nonempty( $ref [,$name] ) β€” asserts that $ref is defined and is a reference to a hash with at least one key/value pair. Not empty. Nope. Not today. πŸ’€
  • assert_arrayref( $ref [, $name] )
  • assert_listref( $ref [,$name] ) β€” asserts that $ref is defined, and is a reference to an array, which may or may not be empty. Both of these do the same thing, iykyk. πŸ‘‘

NB: the same caveat about objects whose underlying structure is a hash (see "assert_hashref") applies here; this method returns false even for objects whose underlying structure is an array.

Heads up bestie: "assert_listref" is an alias for "assert_arrayref" and may go away in the future. Use "assert_arrayref" instead, fr fr.

  • assert_arrayref_nonempty( $ref [, $name] ) β€” asserts that $ref is a reference to an array that has at least one element in it. No sad empty arrays allowed. 🌸
  • assert_arrayref_of( $ref, $type [, $name] ) β€” asserts that $ref is a reference to an array, and that any/all elements are of type $type. Obsessed with type safety tbh.

For example:

my @users = get_users();
assert_arrayref_of( \@users, 'My::User' );
  • assert_arrayref_nonempty_of( $ref, $type [, $name] ) β€” asserts that $ref is a reference to an array, that it has at least one element, and that all elements are of type $type.

This is the same function as "assert_arrayref_of", except that it also requires at least one element. So basically the extra-picky version. 🧚

  • assert_arrayref_all( $aref, $sub [, $name] ) β€” asserts that $aref is a reference to an array that has at least one element in it. Then each element of the array gets passed to subroutine $sub, which is assumed to be an assertion. It's giving "for each, go off". πŸ”₯

For example:

my $aref_of_counts = get_counts();
assert_arrayref_all( $aref, \&assert_positive_integer, 'Counts are positive' );

Whatever you pass as $name, a string saying "Element #N" will be appended, where N is the zero-based index of the array. So your messages stay cute and specific. πŸ’–

  • assert_aoh( $ref [, $name ] ) β€” verifies that $array is an arrayref, and that every element is a hashref. (Array of hashes β€” hence "aoh", iykyk.)

Good news: the array $array can be an empty arrayref and the assertion will still pass. πŸ™Œ

  • assert_coderef( $ref [,$name] ) β€” asserts that $ref is defined, and is a reference to a closure. Code refs are main character energy, ngl.
  • assert_regex( $ref [,$name] ) β€” asserts that $ref is defined, and is a reference to a regex.

It's functionally the same as "assert_isa( $ref, 'Regexp' )". Same thing, different outfit. ✨


🌈 TYPE-SPECIFIC ASSERTIONS 🌈

assert_datetime( $date )

Asserts that $date is a DateTime object. That's the whole thing. Short and iconic. πŸ•


πŸ¦‹ SET AND HASH MEMBERSHIP πŸ¦‹

  • assert_in( $string, \@inlist [,$name] ); β€” asserts that $string matches one of the elements of \@inlist. And yes, $string may be undef, no biggie.

But listen: \@inlist must be an array reference of non-ref strings. If any element is a reference, the assertion fails. No cap. ⚠️

  • assert_exists( \%hash, $key [,$name] )
  • assert_exists( \%hash, \@keylist [,$name] ) β€” asserts that %hash is indeed a hash, and that $key exists in %hash... or that all of the keys in @keylist exist in %hash. Two flavors, one vibe. πŸ’œ
assert_exists( \%custinfo, 'name', 'Customer has a name field' );

assert_exists( \%custinfo, [qw( name addr phone )],
                        'Customer has name, address and phone' );
  • assert_lacks( \%hash, $key [,$name] )
  • assert_lacks( \%hash, \@keylist [,$name] ) β€” asserts that %hash is indeed a hash, and that $key does NOT exist in %hash, or that none of the keys in @keylist exist in %hash. The list @keylist cannot be empty β€” that's a hard rule, don't try it. 🚫
assert_lacks( \%users, 'root', 'Root is not in the user table' );

assert_lacks( \%users, [qw( root admin nobody )], 'No bad usernames found' );
  • assert_all_keys_in( \%hash, \@names [, $name ] ) β€” asserts that each key in %hash is in the list of @names. This is the go-to when you wanna make sure there are no extra keys sneaking into a given hash. Gatekeeping, but make it code. πŸ’…
assert_all_keys_in( $obj, [qw( height width depth )], '$obj can only contain height, width and depth keys' );

Fun fact: you can pass an empty list of @names. Slay.

  • assert_keys_are( \%hash, \@keys [, $name ] ) β€” asserts that the keys for %hash are exactly @keys. No more, no less. Precision. Iconic. Periodt. 🎯

🫢 CONTEXT ASSERTIONS 🫢

assert_context_nonvoid( [$name] )

Verifies that the function currently being executed has not been called in void context. This is to ensure the calling function is not ignoring the return value of the executing function. Very "respect my effort" of it. 😀

Given this function:

sub something {
    ...

    assert_context_nonvoid();

    return $important_value;
}

These calls to "something" will pass:

my $val = something();
my @things = something();

but this will fail:

something();

If the $name argument is not passed, a default message of "<funcname> must not be called in void context" is provided. πŸŽ€

assert_context_void( [$name] )

Verifies that the function currently being executed has been called in void context. This is for functions that do not return anything meaningful. Like, they're just here for the vibes and the side effects. πŸ¦‹

Given this function:

sub something {
    ...

    assert_context_void();

    return; # No meaningful value.
}

These calls to "something" will fail:

my $val = something();
my @things = something();

but this will pass:

something();

If the $name argument is not passed, a default message of "<funcname> must be called in void context" is provided.

assert_context_scalar( [$name] )

Verifies that the function currently being executed has been called in scalar context. This is to ensure the calling function is not ignoring the return value of the executing function. (Yes, same goal as assert_context_nonvoid, just stricter about how.) ⭐

Given this function:

sub something {
    ...

    assert_context_scalar();

    return $important_value;
}

This call to "something" will pass:

my $val = something();

but these will fail:

something();
my @things = something();

If the $name argument is not passed, a default message of "<funcname> must be called in scalar context" is provided.

assert_context_list( [$name] )

Verifies that the function currently being executed has been called in list context. We stan a function that knows it's a list kinda girl. 🌸

Given this function:

sub something {
    ...

    assert_context_scalar();

    return @values;
}

This call to "something" will pass:

my @vals = something();

but these will fail:

something();
my $thing = something();

If the $name argument is not passed, a default message of "<funcname> must be called in list context" is provided.


πŸ’€ UTILITY ASSERTIONS πŸ’€

  • assert_fail( [$name] ) β€” an assertion that always fails. assert_fail($msg) is exactly the same as calling "assert(0,$msg)", but it eliminates that case where you accidentally use assert($msg), which of course never fires. We've all been there bestie, this one's got your back. πŸ™ˆ

Copyright 2005-2025 Andy Lester

This program is free software; you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.


πŸ“ ACKNOWLEDGEMENTS πŸ“

Thanks to Eric A. Zarko, Bob Diss, Pete Krawczyk, David Storrs, Dan Friedman, Allard Hoeve, Thomas L. Shinnick, and Leland Johnson for code and fixes. Genuinely so grateful, mwah. πŸ’–


Okay that's the whole page bestie, you ate it up ✨ this was perl v5.42.0, dated 2025-07-25 β€” go forth and assert responsibly πŸŽ€πŸ’…

πŸ“¦ where this page comes from