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 TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Accessing element of array of arrays

Status
Not open for further replies.

perlqs

Programmer
Jul 4, 2008
2
US
Hi. I'm a relatively new Perl programmer, and I'd like some help working with two arrays of arrays. I want to store a value from the first one, @AoA1, into the second one, @AoA2, without changing @AoA1. At first I was trying $AoA2[foo][bar] = $AoA1[foo][bar]. Now, I don't even really understand what's happening when I use the [][] indexing - I think I end up assigning a reference instead of a value - but the effect is that when I change that value of @AoA2 again it changes the corresponding value of @AoA1, which is not what I want. So how do I dereference the value I want from @AoA1?
 
this is not even possible unless foo and bar are constants with a numeric value:

$AoA2[foo][bar] = $AoA1[foo][bar]

array indexes use numbers, starting with zero and going to whatever your computers memory can handle.

If you have @array1 and want to store a copy of the array in another array just assign it to another array:

@array2 = @array1;

Then you can change @array2 all you want without affecting the original array.

If you have some different situation you need to provide more details, some sample data is almost always helpful.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
This should demonstrate what I'm trying to do:

Code:
#!/usr/bin/perl
use strict;
use warnings;

my @AoA1 = ([1, 'a'], [2, 'b']);

my @AoA2;
push @AoA2, @AoA1;

$AoA2[0][0] = $AoA1[0][0];
print "$AoA1[0][0], $AoA2[0][0]\n";

$AoA2[0][0] ++;
print "$AoA1[0][0], $AoA2[0][0]\n";

Notice that when $AoA2[0][0] is augmented, $AoA1[0][0] is as well. The desired output would be:

1, 1
2, 1

instead of

1, 1
2, 2.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top