in reply to Re: perlsub question..
in thread perlsub question..

You can't pass an array to a subroutine! You can pass the values of an array (which is what you did) or a reference to an array. Consider this:

sub foo { print "@_\n"; push @_, 99; } @a = (1,2,4); foo(@a, 666)

Now what's Perl supposed to do with this? Keep in mind that the foo() did not get two parameters, it got FOUR. The three elements of @a and the 666. The first three modifiable, the last readonly. No array was passed.

The docs talk about things like foo( $a[99]) and foo( $h{new_key}), where in an old version the @a would be expanded and the 'new_key' key added into the %h upon calling the subroutine, while in the new versions this is only done if necessary.

This is consistent with things like if (defined($a[99]){... versus $a[99] = 0;.

Replies are listed 'Best First'.
Re^3: perlsub question..
by NetWallah (Canon) on Jun 23, 2007 at 20:22 UTC
    Got it (++).

    So, would this statement be right :
    Elements of @_ are aliased to EXISTING (I was going to say DEFINED, but elements with the value 'undef' are updatable) elements of the passed parameter.

    This would explain why the indexes 5,6 and 8 never get created in the code I posted.

         "An undefined problem has an infinite number of solutions." - Robert A. Humphrey         "If you're not part of the solution, you're part of the precipitate." - Henry J. Tillman

      Elements of @_ are aliased to EXISTING/DEFINED elements of the passed parameter.
      Not necessarily.
      perl -MData::Dump::Streamer -le '@ary = (); x($ary[5],"foo"); sub x { +$_[0] = $_[1] }; Dump(\@ary)' $ARRAY1 = [ ( undef ) x 5, 'foo' ]; perl -MData::Dump::Streamer -le '@ary = (); x($ary[5],"foo"); sub x { +$_[0] }; Dump(\@ary)' $ARRAY1 = [];

      As you can see, the element at index 5 is not created merely by passing its alias to the sub. It doesn't exist and isn't defined, and may remain so after the sub has been called.

      --shmem

      _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                    /\_¯/(q    /
      ----------------------------  \__(m.====·.(_("always off the crowd"))."·
      ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
        You make a valid point(++), so I will modify my proposed behaviour statement to:

        Elements of @_ are aliased to EXISTING or EXPLICITLY-passed element(s) of the passed parameter(s).
        The sub may modify ONLY THESE elements. Attempts to modify othe elements will not be retained on sub exit.

             "An undefined problem has an infinite number of solutions." - Robert A. Humphrey         "If you're not part of the solution, you're part of the precipitate." - Henry J. Tillman