简体   繁体   中英

How can I have variable assertions in Perl?

How can I check that a variable has a specific value in Perl? Is there a command to stop a script's execution to look up some of it's variables?

I wonder if I can use the Pythonic practice of inserting:

    assert 0, (foo, bar)

to debug scripts in a debuger-less way?

快速的CPAN搜索建议Carp :: Assert

See Carp::Assert :

 use Carp::Assert; $next_sunrise_time = sunrise(); # Assert that the sun must rise in the next 24 hours. assert(($next_sunrise_time - time) < 24*60*60) if DEBUG; # Assert that your customer's primary credit card is active affirm { my @cards = @{$customer->credit_cards}; $cards[0]->is_active; }; 

Smart ::评论很好。

There is a script at PerlMonks that introduces a fast assert method.

Speed is important since Perl is interpreted and any inline checks will impact performance (unlike simple C macros for example)


I am not sure if these things are going to be directly usable.


Ok! This is what i was looking for -- PDF Warning: Test-Tutorial.pdf . The Test::Harness is used for writing Perl module tests.

$var_to_check =~ /sometest/ or die "bad variable!";

I tend to throw things like this in my code, and later use a find and replace to get rid of them (in production code).

Also, ' eval ' can be used to run a section of code and capture errors and can be used to create exception handling functionality. If you are asserting that a value is not 0, perhaps you want to throw an exception and handle that case in a special way?

if ( $next_sunrise_time > 24*60*60 ) { warn( "assertion failed" ); } # Assert that the sun must rise in the next 24 hours.

如果您无权访问Carp :: Assert所需的Perl 5.9,则可以执行此操作。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM