in reply to dereferencing a double array
In my code, 2D arrays are arrays of references to arrays (any other way to implement them?).The answer to the question is "yes", but I wouldn't use any of the ways I can think of implementing 2D arrays other than having arrays of references to arrays.
When i pass a matrix to a subroutine, i pass the subroutine a reference to the matrix (also, any other way to pass such a 2D array?).Yes, you could use a package variable for your array, and pass a glob. But that's very Perl4ish, and buys you little in Perl5; beside from that, people will have a harder time understanding your code. Passing a reference is the standard way.
And since efficiency is quite a concern to me, i am trying to know if there's a better, more efficient way to dereference a 2D array and modify the new array without affecting the original one.It depends. If the sub you call is supposed to return a new, completely different array, the values have to be copied one way or another. I'd write it different though:
You may be able to speed it up by doing the copying in XS (or use a module that does so), but it still scales lineary with the number of elements in $array.sub foo { my $array = shift; my $copy = [map {[@$_]} @$array]; ... Changes in $copy won't affect $array ... return $copy; }
However, if you only need to make changes in the array in the subroutine, and don't need the changes when the sub is done, you could use local when modifying the array. No initial copy is needed.
As you can see, $array[0][1] has a different value in foo, but outside the sub, @array is unmodified.#!/usr/bin/perl use 5.010; use strict; use warnings; use YAML; sub foo { my $array = shift; local $array->[0][1] = "bar"; print Dump $array; } my @array = ([1, 2, 3], [4, 5, 6],); foo \@array; print Dump \@array; __END__ --- - - 1 - bar - 3 - - 4 - 5 - 6 --- - - 1 - 2 - 3 - - 4 - 5 - 6
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: dereferencing a double array
by perlrocks (Acolyte) on Oct 16, 2008 at 20:28 UTC | |
by JavaFan (Canon) on Oct 16, 2008 at 21:22 UTC | |
by perlrocks (Acolyte) on Oct 16, 2008 at 21:31 UTC | |
by JavaFan (Canon) on Oct 16, 2008 at 22:08 UTC |