2016-08-15 28 views
0

我正在嘗試創建一個將打開並編輯文件的子例程。將參數傳遞給Perl中的子例程

我已經能夠讓子程序自己作爲一個Perl腳本運行,但是當它以子程序的形式運行時,我無法正確傳遞參數。

我來自VB.Net和Objective-C的背景,其中子程序/函數是原型的。

$FileName在執行腳本時被分配$ARGV[0]

這是我的函數調用:

addComment("v-66721", "Open", "!!!FINDING!!! deployment.config does not exist.", $FileName); 

這裏是我的聲明:

sub addComment($$$$); 

而這裏的子程序:

sub addComment { 
    my $VULN  = $_[0]; 
    my $Result = $_[1]; 
    my $Comment = $_[2]; 
    my $FileName = $_[3]; 

    # Copy the checklist to a new file name. 
    my $outputFile = $FileName; 
    $outputFile =~ s/\.ckl/_commented\.ckl/; 
    copy($FileName, $outputFile); 

    # Create a temporary file to edit. 
    my $tempFile = $FileName; 
    $tempFile =~ s/\.ckl/\.ckl_temp/; 

    open(OLD, "<$outputFile") or die "Can't open $outputFile: $!"; 
    open(NEW, ">$tempFile") or die "Can't open $tempFile: $!"; 

    my $foundVULN = 0; 

    while (<OLD>) { 

     if ($foundVULN == 0 && $_ =~ /$VULN/) { 
      $foundVULN = 1; 
     } 

     if ($foundVULN == 1 && $_ =~ /Not_Reviewed/) { 
      s/Not_Reviewed/$Result/; 
     } 

     if ($foundVULN == 1 && $_ =~ /COMMENTS/) { 
      s/<COMMENTS>/<COMMENTS>$Comment/; 
      $foundVULN = 0; 
     } 

     print NEW $_; 
    } 

    close(OLD); 
    close(NEW); 

    # Replace the output file contents with what we did in our temp file. 
    rename($tempFile, $outputFile) or die "Can't rename $tempFile to $outputFile: $!"; 

    return; 
} 

我試着用

my $VULN = shift 
my $Result = shift 
my $Comment = shift 
my $FileName = shift 

但是,這似乎並沒有工作。

我讀過,我不應該使用原型,但它似乎並不工作,無論我是否做。

我得到的錯誤信息是:

Prototype mismatch: sub main::addComment ($$$$) vs none at ./Jre8_manual.pl line 614. 
+0

請告訴我你在哪裏學會了應用這樣的子程序原型? – Borodin

+0

請注意,熟悉Perl的人會感謝您使用'snake_case'作爲子例程和詞法變量。爲全局保留'CapitalisedNames'是最安全的。 Perl也有一個後置的條件語句,所以單語句if語句塊是異類的。 – Borodin

+0

如果有任何'VULN'可能包含標點符號的機會,那麼他們可能需要在正則表達式中跳過 – Borodin

回答

4

Avoid prototypes。 Perl中的原型不像其他語言和新程序員期望的那樣工作。

Prototype mismatch ...表示您已經定義(或重新定義了)與原始聲明/定義不同的原型的方法。在這種情況下。

sub addComment ($$$$); 
sub addComment { ... } 

有兩個不同的原型(即第二個聲明沒有原型)。要解決,你可以讓子定義中使用相同的原型

sub addComment ($$$$); 
sub addComment ($$$$) { ... } 

,但你最好沒有原型(然後你不需要predeclaration,要麼)大多數情況下

# sub addComment ($$$$); # don't need this 
sub addComment { ... } 
相關問題