Tyler Kelly
Tyler Kelly

Reputation: 574

How to make a copy of a nested array in an array of array structure

I'm trying to make a copy of a nested array, and it appears that I continue to make a reference with my attempts.

To be more specific I am trying to have an array of arrays wherein each sub array builds upon the previous array. Here is my attempt:

#!/usr/bin/perl -w
use strict;
use warnings;

my @aoa=[(1)];
my $i = 2;
foreach (@aoa){
  my $temp = $_;#copy current array into $temp
  push $temp, $i++;
  push @aoa, $temp;
  last if $_->[-1] == 5;
} 
#print contents of @aoa
foreach my $row (@aoa){
  foreach my $ele (@$row){
    print "$ele  ";
  }
  print "\n";
}

My output is:

1  2  3  4  5  
1  2  3  4  5  
1  2  3  4  5  
1  2  3  4  5  
1  2  3  4  5  

And I want/expect it to be:

1
1 2
1 2 3
1 2 3 4 
1 2 3 4 5 

I'm assuming my problems lies with how I am assigning $temp, please let me know if this is not the case. Any help is appreciated.

Upvotes: 0

Views: 104

Answers (1)

zdim
zdim

Reputation: 66944

Create a new array with my, copy the contents of the array to be built upon, then add to it.

Keeping it as close as possible to your code

foreach (@aoa) {
  last if $_->[-1] == 5;
  my @temp = @$_;         #copy current array into @temp
  push @temp, $i++;
  push @aoa, \@temp;
} 

Upvotes: 4

Related Questions