使用 diagnostics

https://blog.gtwang.org/perl/perl-programming-debugging-basic-technique/

 

有時候 Perl 所自動產生的錯誤訊息並沒有提供足夠的資訊給程式開發者,例如這樣的訊息可能就會讓程式開發者一頭霧水:

Use of uninitialized value in string eq at /Library/Perl/5.8.6/WWW/Mechanize.pm line 695.

這時候我們可以使用 diagnostics,在程式的開頭加上這一行:

use diagnostics;

這樣一來,Perl 就會輸出比較詳細的訊息:

Use of uninitialized value in string eq at /Library/Perl/5.8.6/WWW/Mechanize.pm
    line 695 (#1)
(W uninitialized) An undefined value was used as if it were already
defined.  It was interpreted as a "" or a 0, but maybe it was a mistake.
To suppress this warning assign a defined value to your variables.

To help you figure out what was undefined, perl tells you what operation
you used the undefined value in.  Note, however, that perl optimizes your
program and the operation displayed in the warning may not necessarily
appear literally in your program.  For example, "that $foo" is
usually optimized into "that " . $foo, and the warning will refer to
the concatenation (.) operator, even though there is no . in your
program.

這樣可以讓程式設計者更容易看出問題在哪裡。

加上 diagnostics 之後,產生的訊息雖然很詳細,不過我們可能不是每次都需要看這麼詳細的內容,有時候訊息太多反而很麻煩,建議可以在平常開發時將這行註解起來,當出現看不懂的訊息時,再將這行打開。

另外如果不想更動原始的程式碼的話,我們也可以透過命令列的參數來啟用 diagnostics

perl -Mdiagnostics mycode.pl

若使用這樣的方式的話,mycode.pl 的程式碼就不需要另外加上 use diagnostics;

posted on 2018-03-14 17:56  guolongnv  阅读(479)  评论(0)    收藏  举报