将参数传递给 Perl 中的子例程

Passing parameters to a subroutine in Perl

我正在尝试创建一个子程序来打开和编辑文件。

我已经能够将 运行 的子例程作为单个 Perl 脚本单独获取,但是当它以子例程的形式出现时,我无法正确传递参数。

我来自 VB.Net 和 Objective-C 的背景,其中 subroutines/functions 是原型。

$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.

Avoid prototypes。 Perl 中的原型不像其他语言中那样工作,也不像新程序员期望的那样工作。

Prototype mismatch ... 表示您已经定义(或重新定义)了一个与原始 declaration/definition 不同原型的方法。在这种情况下。

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

有两个不同的原型(即第二个声明没有原型)。要修复,您可以使子定义使用相同的原型

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

但在大多数情况下,没有原型会更好(然后您也不需要预声明)

# sub addComment ($$$$);  # don't need this
sub addComment { ... }