in reply to Pass by Value does not work

When you call left_triangle with what we call a List of List (LoL), you are passing a list of references to the sub, the reference to list(s) (3), (7,5), (2,4,6), (8,5,9,3). In Perl [] means reference to or address of or pointer to, basically the same idea. my @xx = ([3],[7,5],[2,4,6],[8,5,9,3]); is a list of 4 references to other lists. If you use that pointer to the list, then you are modifying the list itself.

Perl is MAGIC with lists!
How do you clone a LoL (List of List)? This is also called a "deep copy".
Easy:
my @xx_clone = map {[$_]}@xx;
Correction: my @xx_clone = map {[@$_]}@xx;
map is a transformation operator that operates on lists.
Here a list of references to lists (@xx) goes into the map. Then each list gets expanded via @$_, then enclosed within a new address (the [] operator) and a new list of those is passed to @xx_clone. So we have a new List of Lists! One line!

To do this in other languages like C, requires a lot of code! And if we are talking about "ragged arrays" like we have here with varying numbers of columns, even more code!

Replies are listed 'Best First'.
Re^2: Pass by Value does not work
by gwadej (Chaplain) on Feb 22, 2009 at 23:05 UTC

    Don't you mean:

    my @xx_clone = map { [ @{$_} ] } @xx;
    G. Wade
      I think we were both a little wrong..ooops..

       my @xx_clone = map { [ @$_ ] } @xx;

      looks like that's better.. Thanks!!!.. UpdateI corrected post above. Thanks again. In general the {} are only needed when subscripts are involved. Another situation is say: @list = @{listref_returning_fun()};

      In above posts, to get array back, my @lol = @{left_triangle(@xx)}; The above posts return reference to lists of lists. to get the LOL back, deference one time using @X= @{subroutine()} syntax.

        Although the {} are not necessary, I always use the {} when derefencing a reference and the -> when dereferencing an element.

        That approach has always seemed clearer to me.

        But, TMTOWTDI always in Perl.

        G. Wade