5 use strict qw(subs vars);
8 use vars qw(@ISA $VERSION %EXPORT_TAGS);
16 NDEBUG => [qw(assert affirm should shouldnt DEBUG)],
18 $EXPORT_TAGS{DEBUG} = $EXPORT_TAGS{NDEBUG};
19 Exporter::export_tags(qw(NDEBUG DEBUG));
22 # constant.pm, alas, adds too much load time (yes, I benchmarked it)
23 sub REAL_DEBUG () { 1 } # CONSTANT
24 sub NDEBUG () { 0 } # CONSTANT
26 # Export the proper DEBUG flag according to if :NDEBUG is set.
27 # Also export noop versions of our routines if NDEBUG
29 sub noop_affirm (&;$) { undef };
32 my $env_ndebug = exists $ENV{PERL_NDEBUG} ? $ENV{PERL_NDEBUG}
34 if( grep(/^:NDEBUG$/, @_) or $env_ndebug ) {
36 foreach my $func (grep !/^DEBUG$/, @{$EXPORT_TAGS{'NDEBUG'}}) {
37 if( $func eq 'affirm' ) {
38 *{$caller.'::'.$func} = \&noop_affirm;
40 *{$caller.'::'.$func} = \&noop;
43 *{$caller.'::DEBUG'} = \&NDEBUG;
47 Carp::Assert->_export_to_level(1, @_);
52 # 5.004's Exporter doesn't have export_to_level.
57 (undef) = shift; # XXX redundant arg
58 my $callpkg = caller($level);
59 $pkg->export($callpkg, @_);
70 # Can't call confess() here or the stack trace will be wrong.
73 my $msg = 'Assertion';
74 $msg .= " ($name)" if defined $name;
82 Carp::Assert - executable comments
89 $next_sunrise_time = sunrise();
91 # Assert that the sun must rise in the next 24 hours.
92 assert(($next_sunrise_time - time) < 24*60*60) if DEBUG;
94 # Assert that your customer's primary credit card is active
96 my @cards = @{$customer->credit_cards};
101 # Assertions are off.
104 $next_pres = divine_next_president();
106 # Assert that if you predict Dan Quayle will be the next president
107 # your crystal ball might need some polishing. However, since
108 # assertions are off, IT COULD HAPPEN!
109 shouldnt($next_pres, 'Dan Quayle') if DEBUG;
118 delete @ENV{qw(PERL_NDEBUG NDEBUG)};
119 require Carp::Assert;
120 Carp::Assert->import;
124 delete @ENV{qw(PERL_NDEBUG NDEBUG)};
128 "We are ready for any unforseen event that may or may not
132 Carp::Assert is intended for a purpose like the ANSI C library
133 assert.h. If you're already familiar with assert.h, then you can
134 probably skip this and go straight to the FUNCTIONS section.
136 Assertions are the explict expressions of your assumptions about the
137 reality your program is expected to deal with, and a declaration of
138 those which it is not. They are used to prevent your program from
139 blissfully processing garbage inputs (garbage in, garbage out becomes
140 garbage in, error out) and to tell you when you've produced garbage
141 output. (If I was going to be a cynic about Perl and the user nature,
142 I'd say there are no user inputs but garbage, and Perl produces
145 An assertion is used to prevent the impossible from being asked of
146 your code, or at least tell you when it does. For example:
150 # Take the square root of a number.
154 # the square root of a negative number is imaginary.
163 is( my_sqrt(4), 2, 'my_sqrt example with good input' );
164 ok( !eval{ my_sqrt(-1); 1 }, ' and pukes on bad' );
166 The assertion will warn you if a negative number was handed to your
167 subroutine, a reality the routine has no intention of dealing with.
169 An assertion should also be used as something of a reality check, to
170 make sure what your code just did really did happen:
172 open(FILE, $filename) || die $!;
174 @stuff = do_something(@stuff);
176 # I should have some stuff.
179 The assertion makes sure you have some @stuff at the end. Maybe the
180 file was empty, maybe do_something() returned an empty list... either
181 way, the assert() will give you a clue as to where the problem lies,
182 rather than 50 lines down at when you wonder why your program isn't
185 Since assertions are designed for debugging and will remove themelves
186 from production code, your assertions should be carefully crafted so
187 as to not have any side-effects, change any variables, or otherwise
188 have any effect on your program. Here is an example of a bad
191 assert($error = 1 if $king ne 'Henry'); # Bad!
193 It sets an error flag which may then be used somewhere else in your
194 program. When you shut off your assertions with the $DEBUG flag,
195 $error will no longer be set.
197 Here's another example of B<bad> use:
199 assert($next_pres ne 'Dan Quayle' or goto Canada); # Bad!
201 This assertion has the side effect of moving to Canada should it fail.
202 This is a very bad assertion since error handling should not be
203 placed in an assertion, nor should it have side-effects.
205 In short, an assertion is an executable comment. For instance, instead
208 # $life ends with a '!'
209 $life = begin_life();
211 you'd replace the comment with an assertion which B<enforces> the comment.
213 $life = begin_life();
214 assert( $life =~ /!$/ );
217 my $life = 'Whimper!';
218 ok( eval { assert( $life =~ /!$/ ); 1 }, 'life ends with a bang' );
227 assert(EXPR) if DEBUG;
228 assert(EXPR, $name) if DEBUG;
230 assert's functionality is effected by compile time value of the DEBUG
231 constant, controlled by saying C<use Carp::Assert> or C<no
232 Carp::Assert>. In the former case, assert will function as below.
233 Otherwise, the assert function will compile itself out of the program.
234 See L<Debugging vs Production> for details.
240 ::ok( eval { assert(0) if DEBUG; 1 } );
243 Give assert an expression, assert will Carp::confess() if that
244 expression is false, otherwise it does nothing. (DO NOT use the
245 return value of assert for anything, I mean it... really!).
248 ok( eval { assert(1); 1 } );
249 ok( !eval { assert(0); 1 } );
251 The error from assert will look something like this:
254 Carp::Assert::assert(0) called at prog line 23
255 main::foo called at prog line 50
259 like( $@, '/^Assertion failed!/', 'error format' );
260 like( $@, '/Carp::Assert::assert\(0\) called at/', ' with stack trace' );
262 Indicating that in the file "prog" an assert failed inside the
263 function main::foo() on line 23 and that foo() was in turn called from
264 line 50 in the same file.
266 If given a $name, assert() will incorporate this into your error message,
267 giving users something of a better idea what's going on.
269 assert( Dogs->isa('People'), 'Dogs are people, too!' ) if DEBUG;
270 # Result - "Assertion (Dogs are people, too!) failed!"
273 eval { assert( Dogs->isa('People'), 'Dogs are people, too!' ); };
274 like( $@, '/^Assertion \(Dogs are people, too!\) failed!/', 'names' );
281 Carp::confess( _fail_msg($_[1]) );
289 affirm BLOCK if DEBUG;
290 affirm BLOCK $name if DEBUG;
292 Very similar to assert(), but instead of taking just a simple
293 expression it takes an entire block of code and evaluates it to make
294 sure its true. This can allow more complicated assertions than
295 assert() can without letting the debugging code leak out into
296 production and without having to smash together several
302 my $customer = Customer->new($customerid);
303 my @cards = $customer->credit_cards;
304 grep { $_->is_active } @cards;
305 } "Our customer has an active credit card";
310 my $foo = 1; my $bar = 2;
311 eval { affirm { $foo == $bar } };
312 like( $@, '/\$foo == \$bar/' );
315 affirm() also has the nice side effect that if you forgot the C<if DEBUG>
316 suffix its arguments will not be evaluated at all. This can be nice
317 if you stick affirm()s with expensive checks into hot loops and other
318 time-sensitive parts of your program.
320 If the $name is left off and your Perl version is 5.6 or higher the
321 affirm() diagnostics will include the code begin affirmed.
326 unless( eval { &{$_[0]}; } ) {
329 if( !defined $name ) {
332 $name = B::Deparse->new->coderef2text($_[0]);
335 'code display non-functional on this version of Perl, sorry'
340 Carp::confess( _fail_msg($name) );
349 should ($this, $shouldbe) if DEBUG;
350 shouldnt($this, $shouldntbe) if DEBUG;
352 Similar to assert(), it is specially for simple "this should be that"
353 or "this should be anything but that" style of assertions.
355 Due to Perl's lack of a good macro system, assert() can only report
356 where something failed, but it can't report I<what> failed or I<how>.
357 should() and shouldnt() can produce more informative error messages:
359 Assertion ('this' should be 'that'!) failed!
360 Carp::Assert::should('this', 'that') called at moof line 29
361 main::foo() called at moof line 58
365 should($this, $that) if DEBUG;
369 assert($this eq $that) if DEBUG;
371 except for the better error message.
373 Currently, should() and shouldnt() can only do simple eq and ne tests
374 (respectively). Future versions may allow regexes.
379 unless($_[0] eq $_[1]) {
381 &Carp::confess( _fail_msg("'$_[0]' should be '$_[1]'!") );
387 unless($_[0] ne $_[1]) {
389 &Carp::confess( _fail_msg("'$_[0]' shouldn't be that!") );
394 # Sorry, I couldn't resist.
395 sub shouldn't ($$) { # emacs cperl-mode madness #' sub {
396 my $env_ndebug = exists $ENV{PERL_NDEBUG} ? $ENV{PERL_NDEBUG}
402 shouldnt($_[0], $_[1]);
408 =head1 Debugging vs Production
410 Because assertions are extra code and because it is sometimes necessary to
411 place them in 'hot' portions of your code where speed is paramount,
412 Carp::Assert provides the option to remove its assert() calls from your
415 So, we provide a way to force Perl to inline the switched off assert()
416 routine, thereby removing almost all performance impact on your production
419 no Carp::Assert; # assertions are off.
420 assert(1==1) if DEBUG;
422 DEBUG is a constant set to 0. Adding the 'if DEBUG' condition on your
423 assert() call gives perl the cue to go ahead and remove assert() call from
424 your program entirely, since the if conditional will always be false.
426 # With C<no Carp::Assert> the assert() has no impact.
428 assert( do_some_really_time_consuming_check ) if DEBUG;
431 If C<if DEBUG> gets too annoying, you can always use affirm().
433 # Once again, affirm() has (almost) no impact with C<no Carp::Assert>
435 affirm { do_some_really_time_consuming_check };
438 Another way to switch off all asserts, system wide, is to define the
439 NDEBUG or the PERL_NDEBUG environment variable.
441 You can safely leave out the "if DEBUG" part, but then your assert()
442 function will always execute (and its arguments evaluated and time
443 spent). To get around this, use affirm(). You still have the
444 overhead of calling a function but at least its arguments will not be
448 =head1 Differences from ANSI C
450 assert() is intended to act like the function from ANSI C fame.
451 Unfortunately, due to Perl's lack of macros or strong inlining, it's not
452 nearly as unobtrusive.
454 Well, the obvious one is the "if DEBUG" part. This is cleanest way I could
455 think of to cause each assert() call and its arguments to be removed from
456 the program at compile-time, like the ANSI C macro does.
458 Also, this version of assert does not report the statement which
459 failed, just the line number and call frame via Carp::confess. You
460 can't do C<assert('$a == $b')> because $a and $b will probably be
461 lexical, and thus unavailable to assert(). But with Perl, unlike C,
462 you always have the source to look through, so the need isn't as
468 With C<no Carp::Assert> (or NDEBUG) and using the C<if DEBUG> suffixes
469 on all your assertions, Carp::Assert has almost no impact on your
470 production code. I say almost because it does still add some load-time
471 to your code (I've tried to reduce this as much as possible).
473 If you forget the C<if DEBUG> on an C<assert()>, C<should()> or
474 C<shouldnt()>, its arguments are still evaluated and thus will impact
475 your code. You'll also have the extra overhead of calling a
476 subroutine (even if that subroutine does nothing).
478 Forgetting the C<if DEBUG> on an C<affirm()> is not so bad. While you
479 still have the overhead of calling a subroutine (one that does
480 nothing) it will B<not> evaluate its code block and that can save
483 Try to remember the B<if DEBUG>.
492 Defining NDEBUG switches off all assertions. It has the same effect
493 as changing "use Carp::Assert" to "no Carp::Assert" but it effects all
498 Same as NDEBUG and will override it. Its provided to give you
499 something which won't conflict with any C programs you might be
500 working on at the same time.
505 =head1 BUGS, CAVETS and other MUSINGS
507 =head2 Conflicts with C<POSIX.pm>
509 The C<POSIX> module exports an C<assert> routine which will conflict with C<Carp::Assert> if both are used in the same namespace. If you are using both together, prevent C<POSIX> from exporting like so:
514 Since C<POSIX> exports way too much, you should be using it like that anyway.
516 =head2 C<affirm> and C<$^S>
518 affirm() mucks with the expression's caller and it is run in an eval
519 so anything that checks $^S will be wrong.
523 Yes, there is a C<shouldn't> routine. It mostly works, but you B<must>
524 put the C<if DEBUG> after it.
526 =head2 missing C<if DEBUG>
528 It would be nice if we could warn about missing C<if DEBUG>.
533 L<assertions> is a new module available in 5.9.0 which provides assertions which can be enabled/disabled at compile time for real, no C<if DEBUG> necessary.
538 Copyright 2001-2007 by Michael G Schwern E<lt>schwern@pobox.comE<gt>.
540 This program is free software; you can redistribute it and/or
541 modify it under the same terms as Perl itself.
543 See F<http://dev.perl.org/licenses/>
548 Michael G Schwern <schwern@pobox.com>
552 return q|You don't just EAT the largest turnip in the world!|;