Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

assign 2-dim array to other array - unclear behaviour 1

Status
Not open for further replies.

EfratS

MIS
Aug 4, 2004
15
CA
hello,

I'm tring to assign 2-dim array to another array with the following code:

@tmpArr = @originalArr;

The unclear behaviour has been detected with this code:
print "here: @{$originalArr[1]}\n";
${$tmpArr[1]}[0] = 111;
print "here: @{$originalArr[1]}\n";


The originalArr value in cell [1][0] has been changed to "111". why? I've changed the tmpArr!

Thanks a lot.
 
The reason this is happening is because there is technically no such thing as a 2 dimensinal array in Perl, since arrays can't contain other arrays.

@originalArr isn't an array of arrays, it's an array of references (to other arrays). Your assignment causes @tmpArr to hold the same references as @originalArr, which means that changing something in one will be reflected in the other.

To recursively copy complex datatypes, you can use the Clone module, like so:
Code:
  use Clone qw(clone);

  my @originalArr = ( [0..5], [6..10], [11..15] );
  my @tmpArr = @{ clone (\@originalArr) };

  print "here: @{$originalArr[1]}\n";
  ${$tmpArr[1]}[0] = 111;
  print "here: @{$originalArr[1]}\n";
 
you could do this manually also if Clone is not available:

Code:
my @originalArr = ( [0..5], [6..10], [11..15] );
my @tempArr = ();
for (@originalArr) {
   push @tempArr, [@{$_}];
}
$tempArr[1][0] = 'A';
print "$originalArr[1][0]\n";
print "$tempArr[1][0]";

by dereferencing the @originalArr in the 'for' loop, you make a copy of the data in the arrays into @tempArr and not just copies of the references to the arrays, which will affect both arrays as ishnid pointed out.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top