aennen has asked for the wisdom of the Perl Monks concerning the following question:

Just curious as to why the direct reference to scalar for the default array does no work here ?
@x=(a..z); @y=(0..9); &func(\@x, \@y); sub func() { my ($mx, $my) = @_; $z = $_[1]; print "@{$_[0]}\n"; # works print "@$_[1]\n"; # Does Not work, why ? print "@$z\n"; # works print "@$mx\n"; # works }

Replies are listed 'Best First'.
•Re: Pass by ref an array weirdness
by merlyn (Sage) on Dec 05, 2002 at 16:36 UTC
Re: Pass by ref an array weirdness
by sauoq (Abbot) on Dec 05, 2002 at 17:56 UTC

    Your question has been answered but you have another issue that will eventually cause problems for you.

    Your sub, "func" is defined with an empty prototype.

    sub func() {
    Later, you get around the problems caused by the prototype by calling the sub with an explicit &.

    &func(\@x, \@y);

    That's a terrible habit to get into. Prototypes in Perl aren't anything like prototypes in other languages and you shouldn't use them at all unless you really understand what they are for and can pick out the special case where they make sense. It would be better to define "func" as

    sub func { ... }
    and call it like
    func(\@x, \@y);

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Pass by ref an array weirdness
by bronto (Priest) on Dec 05, 2002 at 17:08 UTC

    When you are dereferencing, it's always safer (but more bothering to type, I know) to explicitly include braces, as you did with $_[0]; this way you will be sure that the code really does what you asked it to do.

    Note that not always "what you asked it to do" is the same as "what you wanted him to do" ;-)

    Ciao!
    --bronto

    # Another Perl edition of a song:
    # The End, by The Beatles
    END {
      $you->take($love) eq $you->make($love) ;
    }