7

如何检查变量在 Perl 中是否具有特定值?是否有停止脚本执行以查找其中一些变量的命令?

我想知道我是否可以使用 Pythonic 的插入实践:

    assert 0, (foo, bar)

以无调试器的方式调试脚本?

4

6 回答 6

12

快速 CPAN 搜索建议Carp::Assert

于 2009-06-21T12:58:04.723 回答
8

鲤鱼::断言

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;
};
于 2009-06-21T12:58:05.330 回答
5

Smart::Comments are nice.

于 2009-06-21T13:44:06.503 回答
3

PerlMonks有一个脚本,它介绍了一种快速断言方法。

速度很重要,因为 Perl 被解释并且任何内联检查都会影响性能(例如,与简单的 C 宏不同)


我不确定这些东西是否可以直接使用。


好的!这就是我一直在寻找的——PDF 警告:Test-Tutorial.pdfTest::Harness用于编写 Perl 模块测试。

于 2009-06-21T12:54:23.903 回答
1
$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?

于 2009-06-21T13:51:18.873 回答
1
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,则可以执行此操作。

于 2012-03-14T17:50:37.030 回答