in reply to Re: Why does assignment change the result?
in thread Why does assignment change the result?

    "@_ 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:

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

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

Replies are listed 'Best First'.
Re^3: Why does assignment change the result?
by johngg (Canon) on May 24, 2007 at 11:54 UTC
    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

        I think I've covered that one in &assignTo by doing @_ = @temp; but I've thought of another couple of variations. Here's a revised script

        and output

        Given more time I'd refactor to use an array of code refs. and test in a loop as the script is getting quite long but I'm rushing to get ready for a holiday so it'll have to stay as it is.

        Cheers,

        JohnGG