in reply to Why does assignment change the result?

This is one of the biggest issue with Perl. @_ is a reference, and change its value will be seen in the calling func.

Any one didn't catch that at the very beginning is not a true saint.

  • Comment on Re: Why does assignment change the result?

Replies are listed 'Best First'.
Re^2: Why does assignment change the result?
by NetWallah (Canon) on May 24, 2007 at 03:56 UTC
        "@_ is a reference, and change its value will be seen in the calling func"

    Er - NO. From perldoc perlsub

    The array @_ is a local array, but its elements are aliases for the actual scalar parameters.

    So, you are wrong on 2 counts:

    • @_ is an array, not a reference
    • Since it is local, changing @_ will NOT change the caller
    Perhaps what you meant to say was - what trips perl newbies is that fact that the ELEMENTS of @_ are aliased to the caller's parameters - hence changing an ELEMENT of @_ would modify the caller's variable.

         "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

      I wanted to understand what was happening, what affected the caller and what didn't so I put a short script together. I may have missed ways to get at @_ and I would be interested if any omissions were pointed out.

      The output produced is

      At initialisation Contents are 1 2 In assignTo - assign to @_ Contents now 1 2 In listArgs - list of lexicals Contents now 1 2 In loopOver - loop over @_ Contents now 2 3 In refTo - take reference to @_ elements Contents now 3 4 In shiftArgs - lexicals via shift Contents now 3 4 In useDirect - increment elements directly Contents now 4 5

      A very interesting topic that has cleared up some misunderstandings.

      Cheers,

      JohnGG

        Looks good (++).

        Update:Ignore the rest of this node - as johngg points out, below - this code is equivalent to his assignTo sub.

        If you like, you could add what "Anon Monk" implied was possible:

        sub Modify_param_array{ print qq{In Modify_param_array - change @_\n}; @_ = qw[New contents. The caller never sees this]; }

             "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