in reply to Re: dereferencing a double array
in thread dereferencing a double array

Thank you very much for the elaborate reply. As you noted in your reply, the subroutines do return a new, completely different array. In that case, you mentioned: "the values have to be copied one way or another. I'd write it different though:
sub foo { my $array = shift; my $copy = [map {[@$_]} @$array]; ... Changes in $copy won't affect $array ... return $copy; }
As i can see, now $copy is a reference that points to an array of (a new set of) references, each of which contain the same elements as the corresponding reference in @original_array. It could be written in this way though.
sub foo { my $array = shift; my @copy = map {[@$_]} @$array; ... Changes in @copy won't affect @array ... return \@copy; }
right? And is the reason that you'd copy the elements this way is that it's faster? Again, thanks a lot for your tips, Hadi

Replies are listed 'Best First'.
Re^3: dereferencing a double array
by JavaFan (Canon) on Oct 16, 2008 at 21:22 UTC
    Yes, you can write it with @copy and returning it as \@copy. But I prefer using $copy, for symmetrical reasons. I start out with a reference to an array, so if I copy it, I'd like to copy to another reference. But that's just personal preference, I don't one way is significantly faster or easier to understand than the other.

    As for copying using a map instead of the double loop is mostly because it's less verbose. It's just one line and I see immediately it's a copy of a 2D array - the double loop takes more lines, and too large to immediately see what it does. I haven't benchmarked it, but if there's a difference I expect the difference to be small, and the map to be slightly faster; with the difference slowly growing if the arrays get larger. But speed isn't my main reason to copy it using a map.

      Oh i see. What if efficiency and running time are of the utmost importance? Any tips? :) Thanks
        What if efficiency and running time are of the utmost importance?

        Then your choice of Perl as a programming language is a horrible mistake.