{
    "mode": "perldoc",
    "parameter": "Carp::Assert",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/Carp%3A%3AAssert/json",
    "generated": "2026-06-15T16:47:17Z",
    "synopsis": "# Assertions are on.\nuse Carp::Assert;\n$nextsunrisetime = sunrise();\n# Assert that the sun must rise in the next 24 hours.\nassert(($nextsunrisetime - time) < 24*60*60) if DEBUG;\n# Assert that your customer's primary credit card is active\naffirm {\nmy @cards = @{$customer->creditcards};\n$cards[0]->isactive;\n};\n# Assertions are off.\nno Carp::Assert;\n$nextpres = divinenextpresident();\n# Assert that if you predict Dan Quayle will be the next president\n# your crystal ball might need some polishing.  However, since\n# assertions are off, IT COULD HAPPEN!\nshouldnt($nextpres, 'Dan Quayle') if DEBUG;",
    "sections": {
        "NAME": {
            "content": "Carp::Assert - executable comments\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "# Assertions are on.\nuse Carp::Assert;\n\n$nextsunrisetime = sunrise();\n\n# Assert that the sun must rise in the next 24 hours.\nassert(($nextsunrisetime - time) < 24*60*60) if DEBUG;\n\n# Assert that your customer's primary credit card is active\naffirm {\nmy @cards = @{$customer->creditcards};\n$cards[0]->isactive;\n};\n\n\n# Assertions are off.\nno Carp::Assert;\n\n$nextpres = divinenextpresident();\n\n# Assert that if you predict Dan Quayle will be the next president\n# your crystal ball might need some polishing.  However, since\n# assertions are off, IT COULD HAPPEN!\nshouldnt($nextpres, 'Dan Quayle') if DEBUG;\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "\"We are ready for any unforseen event that may or may not\noccur.\"\n- Dan Quayle\n\nCarp::Assert is intended for a purpose like the ANSI C library assert.h\n<http://en.wikipedia.org/wiki/Assert.h>. If you're already familiar with assert.h, then you can\nprobably skip this and go straight to the FUNCTIONS section.\n\nAssertions are the explicit expressions of your assumptions about the reality your program is\nexpected to deal with, and a declaration of those which it is not. They are used to prevent your\nprogram from blissfully processing garbage inputs (garbage in, garbage out becomes garbage in,\nerror out) and to tell you when you've produced garbage output. (If I was going to be a cynic\nabout Perl and the user nature, I'd say there are no user inputs but garbage, and Perl produces\nnothing but...)\n\nAn assertion is used to prevent the impossible from being asked of your code, or at least tell\nyou when it does. For example:\n\n# Take the square root of a number.\nsub mysqrt {\nmy($num) = shift;\n\n# the square root of a negative number is imaginary.\nassert($num >= 0);\n\nreturn sqrt $num;\n}\n\nThe assertion will warn you if a negative number was handed to your subroutine, a reality the\nroutine has no intention of dealing with.\n\nAn assertion should also be used as something of a reality check, to make sure what your code\njust did really did happen:\n\nopen(FILE, $filename) || die $!;\n@stuff = <FILE>;\n@stuff = dosomething(@stuff);\n\n# I should have some stuff.\nassert(@stuff > 0);\n\nThe assertion makes sure you have some @stuff at the end. Maybe the file was empty, maybe",
            "subsections": [
                {
                    "name": "do_something",
                    "content": "where the problem lies, rather than 50 lines down at when you wonder why your program isn't\nprinting anything.\n\nSince assertions are designed for debugging and will remove themelves from production code, your\nassertions should be carefully crafted so as to not have any side-effects, change any variables,\nor otherwise have any effect on your program. Here is an example of a bad assertation:\n\nassert($error = 1 if $king ne 'Henry');  # Bad!\n\nIt sets an error flag which may then be used somewhere else in your program. When you shut off\nyour assertions with the $DEBUG flag, $error will no longer be set.\n\nHere's another example of bad use:\n\nassert($nextpres ne 'Dan Quayle' or goto Canada);  # Bad!\n\nThis assertion has the side effect of moving to Canada should it fail. This is a very bad\nassertion since error handling should not be placed in an assertion, nor should it have\nside-effects.\n\nIn short, an assertion is an executable comment. For instance, instead of writing this\n\n# $life ends with a '!'\n$life = beginlife();\n\nyou'd replace the comment with an assertion which enforces the comment.\n\n$life = beginlife();\nassert( $life =~ /!$/ );\n"
                }
            ]
        },
        "FUNCTIONS": {
            "content": "assert\nassert(EXPR) if DEBUG;\nassert(EXPR, $name) if DEBUG;\n\nassert's functionality is effected by compile time value of the DEBUG constant, controlled\nby saying \"use Carp::Assert\" or \"no Carp::Assert\". In the former case, assert will function\nas below. Otherwise, the assert function will compile itself out of the program. See\n\"Debugging vs Production\" for details.\n\nGive assert an expression, assert will Carp::confess() if that expression is false,\notherwise it does nothing. (DO NOT use the return value of assert for anything, I mean it...\nreally!).\n\nThe error from assert will look something like this:\n\nAssertion failed!\nCarp::Assert::assert(0) called at prog line 23\nmain::foo called at prog line 50\n\nIndicating that in the file \"prog\" an assert failed inside the function main::foo() on line\n23 and that foo() was in turn called from line 50 in the same file.\n\nIf given a $name, assert() will incorporate this into your error message, giving users\nsomething of a better idea what's going on.\n\nassert( Dogs->isa('People'), 'Dogs are people, too!' ) if DEBUG;\n# Result - \"Assertion (Dogs are people, too!) failed!\"\n\naffirm\naffirm BLOCK if DEBUG;\naffirm BLOCK $name if DEBUG;\n\nVery similar to assert(), but instead of taking just a simple expression it takes an entire\nblock of code and evaluates it to make sure its true. This can allow more complicated\nassertions than assert() can without letting the debugging code leak out into production and\nwithout having to smash together several statements into one.\n\naffirm {\nmy $customer = Customer->new($customerid);\nmy @cards = $customer->creditcards;\ngrep { $->isactive } @cards;\n} \"Our customer has an active credit card\";\n\naffirm() also has the nice side effect that if you forgot the \"if DEBUG\" suffix its\narguments will not be evaluated at all. This can be nice if you stick affirm()s with\nexpensive checks into hot loops and other time-sensitive parts of your program.\n\nIf the $name is left off and your Perl version is 5.6 or higher the affirm() diagnostics\nwill include the code begin affirmed.\n\nshould\nshouldnt\nshould  ($this, $shouldbe)   if DEBUG;\nshouldnt($this, $shouldntbe) if DEBUG;\n\nSimilar to assert(), it is specially for simple \"this should be that\" or \"this should be\nanything but that\" style of assertions.\n\nDue to Perl's lack of a good macro system, assert() can only report where something failed,\nbut it can't report *what* failed or *how*. should() and shouldnt() can produce more\ninformative error messages:\n\nAssertion ('this' should be 'that'!) failed!\nCarp::Assert::should('this', 'that') called at moof line 29\nmain::foo() called at moof line 58\n\nSo this:\n\nshould($this, $that) if DEBUG;\n\nis similar to this:\n\nassert($this eq $that) if DEBUG;\n\nexcept for the better error message.\n\nCurrently, should() and shouldnt() can only do simple eq and ne tests (respectively). Future\nversions may allow regexes.\n",
            "subsections": []
        },
        "Debugging vs Production": {
            "content": "Because assertions are extra code and because it is sometimes necessary to place them in 'hot'\nportions of your code where speed is paramount, Carp::Assert provides the option to remove its\nassert() calls from your program.\n\nSo, we provide a way to force Perl to inline the switched off assert() routine, thereby removing\nalmost all performance impact on your production code.\n\nno Carp::Assert;  # assertions are off.\nassert(1==1) if DEBUG;\n\nDEBUG is a constant set to 0. Adding the 'if DEBUG' condition on your assert() call gives perl\nthe cue to go ahead and remove assert() call from your program entirely, since the if\nconditional will always be false.\n\n# With C<no Carp::Assert> the assert() has no impact.\nfor (1..100) {\nassert( dosomereallytimeconsumingcheck ) if DEBUG;\n}\n\nIf \"if DEBUG\" gets too annoying, you can always use affirm().\n\n# Once again, affirm() has (almost) no impact with C<no Carp::Assert>\nfor (1..100) {\naffirm { dosomereallytimeconsumingcheck };\n}\n\nAnother way to switch off all asserts, system wide, is to define the NDEBUG or the PERLNDEBUG\nenvironment variable.\n\nYou can safely leave out the \"if DEBUG\" part, but then your assert() function will always\nexecute (and its arguments evaluated and time spent). To get around this, use affirm(). You\nstill have the overhead of calling a function but at least its arguments will not be evaluated.\n",
            "subsections": []
        },
        "Differences from ANSI C": {
            "content": "assert() is intended to act like the function from ANSI C fame. Unfortunately, due to Perl's\nlack of macros or strong inlining, it's not nearly as unobtrusive.\n\nWell, the obvious one is the \"if DEBUG\" part. This is cleanest way I could think of to cause\neach assert() call and its arguments to be removed from the program at compile-time, like the\nANSI C macro does.\n\nAlso, this version of assert does not report the statement which failed, just the line number\nand call frame via Carp::confess. You can't do \"assert('$a == $b')\" because $a and $b will\nprobably be lexical, and thus unavailable to assert(). But with Perl, unlike C, you always have\nthe source to look through, so the need isn't as great.\n",
            "subsections": []
        },
        "EFFICIENCY": {
            "content": "With \"no Carp::Assert\" (or NDEBUG) and using the \"if DEBUG\" suffixes on all your assertions,\nCarp::Assert has almost no impact on your production code. I say almost because it does still\nadd some load-time to your code (I've tried to reduce this as much as possible).\n\nIf you forget the \"if DEBUG\" on an \"assert()\", \"should()\" or \"shouldnt()\", its arguments are\nstill evaluated and thus will impact your code. You'll also have the extra overhead of calling a\nsubroutine (even if that subroutine does nothing).\n\nForgetting the \"if DEBUG\" on an \"affirm()\" is not so bad. While you still have the overhead of\ncalling a subroutine (one that does nothing) it will not evaluate its code block and that can\nsave a lot.\n\nTry to remember the if DEBUG.\n",
            "subsections": []
        },
        "ENVIRONMENT": {
            "content": "NDEBUG\nDefining NDEBUG switches off all assertions. It has the same effect as changing \"use\nCarp::Assert\" to \"no Carp::Assert\" but it effects all code.\n\nPERLNDEBUG\nSame as NDEBUG and will override it. Its provided to give you something which won't conflict\nwith any C programs you might be working on at the same time.\n\nBUGS, CAVETS and other MUSINGS\nConflicts with \"POSIX.pm\"\nThe \"POSIX\" module exports an \"assert\" routine which will conflict with \"Carp::Assert\" if both\nare used in the same namespace. If you are using both together, prevent \"POSIX\" from exporting\nlike so:\n\nuse POSIX ();\nuse Carp::Assert;\n\nSince \"POSIX\" exports way too much, you should be using it like that anyway.\n\n\"affirm\" and $^S",
            "subsections": [
                {
                    "name": "affirm",
                    "content": "will be wrong.\n\n\"shouldn't\"\nYes, there is a \"shouldn't\" routine. It mostly works, but you must put the \"if DEBUG\" after it.\n\nmissing \"if DEBUG\"\nIt would be nice if we could warn about missing \"if DEBUG\".\n"
                }
            ]
        },
        "SEE ALSO": {
            "content": "assert.h <http://en.wikipedia.org/wiki/Assert.h> - the wikipedia page about \"assert.h\".\n\nCarp::Assert::More provides a set of convenience functions that are wrappers around\n\"Carp::Assert\".\n\nSub::Assert provides support for subroutine pre- and post-conditions. The documentation says\nit's slow.\n\nPerlX::Assert provides compile-time assertions, which are usually optimised away at compile\ntime. Currently part of the Moops distribution, but may get its own distribution sometime in\n2014.\n\nDevel::Assert also provides an \"assert\" function, for Perl >= 5.8.1.\n\nassertions provides an assertion mechanism for Perl >= 5.9.0.\n",
            "subsections": []
        },
        "REPOSITORY": {
            "content": "<https://github.com/schwern/Carp-Assert>\n",
            "subsections": []
        },
        "COPYRIGHT": {
            "content": "Copyright 2001-2007 by Michael G Schwern <schwern@pobox.com>.\n\nThis program is free software; you can redistribute it and/or modify it under the same terms as\nPerl itself.\n\nSee http://dev.perl.org/licenses/\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Michael G Schwern <schwern@pobox.com>\n",
            "subsections": []
        }
    },
    "summary": "Carp::Assert - executable comments",
    "flags": [],
    "examples": [],
    "see_also": []
}