2012-08-14 89 views
1

我目前正在嘗試使用Perl中的命令行參數設置調試標誌,而且我似乎遇到了一些我認爲很容易的問題。

my $debugvalue; 

    my $file = $ARGV[0] or die; 

    if ($ARGV[1] == "debug") 
    { 
     $debugvalue = 1; 
    }else 
    { 
     $debugvalue = 0; 
    } 

我期待輸入一個文件,然後一個字純粹的說法調試,如果它不那麼標誌設置爲0。

test.pl file.txt debug 
  • 請問標誌設置爲1

    test.pl file.txt的調試

  • 請問標誌設置爲0

我會假設這一點,你怎麼做到這一點,除了無論是輸入,它總是落入如果第一部分並設置標誌爲1

+1

好,'0 == 0'。 – cjm 2012-08-14 17:17:22

+1

這是[warnings](http://perldoc.perl.org/warnings.html)會引起的問題。 – 2012-08-14 18:41:58

+0

'$ ARGV [1] eq「debug」' – 2012-10-12 22:14:10

回答

5

這將正常工作,但您需要使用字符串比較,eq,而不是數字比較,==

if ($ARGV[1] eq "debug") 

此外,還可以縮短,最多隻是:

my $debugvalue = $ARGV[1] eq "debug"; 

在一般情況下,我更喜歡使用的調試設置的環境,雖然。

my $debugvalue = $ENV{DEBUG} || 0; 

然後,你可以做這樣的事情:

DEBUG=1 test.pl file.txt 

或設置測試對在bash或zsh中每次運行:

export DEBUG=1 
test.pl file.txt 
test.pl file2.txt 
test.pl file3.txt 

,甚至有一個以上的調試級別,如果您需要積極的調試輸出來幫助診斷特定問題:

DEBUG=3 test.pl file.txt 

並在代碼:

warn "Fiddly Detail $x\n" if $debugvalue > 2; 
3

你應該做字符串比較與eq==

if ($ARGV[1] eq "debug") 
4

我幾乎總是使用的Getopt或:: Getopt的龍。在CPAN中,超級簡單易用且非常標準化。例如:

#!/usr/bin/perl 

use strict; 
use warnings; 

use Getopt::Long; 

my $debug = 0; 

my $result = GetOptions(
    debug => \$debug 
); 

my $file = shift; 

if ($debug) { 
    print("debug is on for processing $file..."); 
} 

當然,因爲它使用標準語法,你會正是如此稱呼它:

#> test.pl file.txt --debug 

#> test.pl --debug file.txt 

---- ----編輯

@zostay提出了一個很好的觀點,各級調試都可以很seful。可以添加到Getopot ::龍的做法正是如此:

#!/usr/bin/perl 

use strict; 
use warnings; 

use Getopt::Long; 

my $debug = 0; 

my $result = GetOptions(
    "debug+" => \$debug 
); 

my $file = shift; 

if ($debug > 2) { 
    print("debug is at least level 2 for processing $file..."); 
} 

而且,對於2級調試,將被稱爲:

#> test.pl --debug --debug file.txt的

1

由於人們已經指出,「eq」應該用於字符串比較和其他支持調試功能的方式,我唯一需要添加的其他建議是在開發過程中使用perl的-w(警告)標誌是也有助於發現類似於您的問題:

#!/usr/bin/perl -w 

在你最初的例子中,它會又回到像一個警告:

爭論「調試」不是在./foo.pl線數字EQ(==)數字7.

它也可能是更清潔的比較使用前檢查$ ARGV [1]的存在:

if ($ARGV[1] && $ARGV[1] eq "debug") 
{ 
    $debugvalue = 1; 
... 
+3

我建議'使用warnings'而不是'-w'。首先,'-w'打開你沒有寫的代碼的警告,這很少有幫助。另一方面,'use warnings'不像'-w'那樣是短暫的(當你完成調試時,並沒有真正的理由將它取出*)。 – hobbs 2012-08-14 17:30:27