如何在Perl中接受一个输出参数数组和一个标量?

4
我有一个函数,我想检查一个路径是否存在,如果存在,把它添加到一个数组中。这是我的尝试代码:
# If a path exists, adds the canonical version of that path to an array
sub AddPathCandidate {
    my (@$target, $path) = $_;
    die ('path needed') unless defined($path);
    $path = File::Spec->canonpath($path);
    if (-e $path) {
        push(@{$target}, $path);
    }
}

调用者的外观如下:

my @exampleDirs = ();
AddPathCandidate(\@exampleDirs, $inDir . 'a');
AddPathCandidate(\@exampleDirs, $inDir . "../b/a/$arch");
AddPathCandidate(\@exampleDirs, $inDir . "../../b/a/$arch");

但是,“die”语句总是会执行;AddPathCandidate的第二个参数以某种方式没有通过。

我在这里尝试的东西是否可行,还是有更多“perl-ish”的方法来完成这个任务?


@toolic:另外,我“获取”使用的perl版本是古老的5.6,所以自那时以来他们可能已经修复了这个问题。 - Billy ONeal
1
@BillyONeal 天啊,Perl 5.6 在一些国家已经够年龄开车了! - user149341
@duskwuff: 是的。我们的测试工具是_老旧的_。 - Billy ONeal
1个回答

7

当解包参数时,请将变量声明为$target,并从@_中进行解包:

my ($target, $path) = @_;
    ^                 ^^

所以出现了一个双倍的facepalm打字错误,还有一个Perl表现得很奇怪。明白了,谢谢! - Billy ONeal
Perl 有什么奇怪的地方? - Grant McLean
@Grant:将你想要作为数组的东西声明为标量。 - Billy ONeal
2
@BillyONeal 这是因为“thing”不是一个数组,而是一个引用。所有的引用都是标量。 - ThisSuitIsBlackNot
@BillyONeal 如果你真的想了解引用,Mark关于引用的简短教程是一个非常好的起点。 - Grant McLean

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接