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

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.

use strict; use warnings; my @arr = (1, 2); print qq{At initialisation\n Contents are @arr\n}; assignTo(@arr); print qq{ Contents now @arr\n}; listArgs(@arr); print qq{ Contents now @arr\n}; loopOver(@arr); print qq{ Contents now @arr\n}; refTo(@arr); print qq{ Contents now @arr\n}; shiftArgs(@arr); print qq{ Contents now @arr\n}; useDirect(@arr); print qq{ Contents now @arr\n}; sub assignTo { my @temp = @_; print qq{In assignTo - assign to \@_\n}; map { $_ ++ } @temp; @_ = @temp; } sub listArgs { my ($var1, $var2) = @_; print qq{In listArgs - list of lexicals\n}; $var1 ++; $var2 ++; } sub loopOver { print qq{In loopOver - loop over \@_\n}; $_ ++ for @_; } sub refTo { my ($rsVar1, $rsVar2) = \(@_); print qq{In refTo - take reference to \@_ elements\n}; $$rsVar1 ++; $$rsVar2 ++; } sub shiftArgs { my $var1 = shift; my $var2 = shift; print qq{In shiftArgs - lexicals via shift\n}; $var1 ++; $var2 ++; } sub useDirect { print qq{In useDirect - increment elements directly\n}; $_[0] ++; $_[1] ++; }

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

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