4

I have a function where I want to check if a path exists, and if it does, add that to an array. Here's 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 looks like:

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

But the "die" statement always executes; the second parameter of AddPathCandidate isn't getting through somehow.

Is what I'm trying to do here even possible or is there some more "perl-ish way" to accomplish this?

3
  • @toolic: Also, the copy of perl I "get" to use is ancient 5.6, so it's possible they fixed this since then. Commented Jan 27, 2016 at 20:45
  • 1
    @BillyONeal Holy crap, Perl 5.6 is old enough to drive in some countries! Commented Jan 27, 2016 at 22:52
  • @duskwuff: Yeah. Our test harness is OLD Commented Jan 27, 2016 at 22:53

1 Answer 1

7

Declare the variable as $target when unpacking your arguments, and unpack from @_:

my ($target, $path) = @_;
    ^                 ^^
Sign up to request clarification or add additional context in comments.

5 Comments

So one double facepalm typo, and one perl just being strange. Got it, thanks!
What was the Perl being strange bit?
@Grant: Declaring the thing you want to be an array as a scalar.
@BillyONeal That's because the "thing" is not an array, it's a reference. And all references are scalars.
@BillyONeal If you really want to understand references Mark's very short tutorial about references is an excellent place to start.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.