How to accept an array of output parameters and scalar in perl?

I have a function where I want to check if a path exists, and if so, add this to the array. Here is what I tried:

# 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);
    }
}

where the caller is as follows:

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

But the die statement is always executed; the second parameter AddPathCandidate does not work out somehow.

Is this what I am trying to do here, even possibly, or is there another “perl-ish” way to accomplish this?

+4
source share
1 answer

Declare the variable as $targetwhen unpacking your arguments and unpack from @_:

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

Source: https://habr.com/ru/post/1626252/


All Articles