0

I have the following code which defines a nested array and then loops through the array and outputs it. I would like to use the commented out line to extract the inner arrays but it doesn't work because it flattens out the inner arrays. I instead have to use the subsequent three lines. How can I get the commented out line to work properly?

use Data::Dumper;    
my @arr1;
for $i (0..9)
{
    my @arr2;
    my @arr3;
    for $j ('A'..'D') {
        push @arr2, $j;
        push @arr3, int(rand(100));
    }
    push @arr1, [$i, \@arr2, \@arr3]; 
}
for $linkarray (@arr1) {
    #my ($i, @arr2, @arr3) = @$linkarray;   
    my $i = @$linkarray[0];
    my @arr2 = @$linkarray[1];
    my @arr3 = @$linkarray[2];
    print "i: $i\narr2: " . Dumper(@arr2) . "\narr3: " . Dumper(@arr3) . "\n";
}
9
  • You pushed in array references, so you should collect array references when you unpack, not arrays. my ($i, $arr2_ref, $arr3_ref) = @$linkarray; Commented Jul 26, 2016 at 3:55
  • perldoc.perl.org/perldsc.html Commented Jul 26, 2016 at 3:56
  • How do I then deference those references to use them like a normal array? Commented Jul 26, 2016 at 4:03
  • my @arr2 = @$arr2_ref; or you can just use them directly: my $first = $arr2_ref->[0]; Commented Jul 26, 2016 at 4:04
  • perldoc.perl.org/perlref.html Commented Jul 26, 2016 at 4:05

1 Answer 1

1

If you're having trouble, figure how you'd do it with a named array, then replace the name with a block that returns the reference.

If it's $a[0] for an named array, it's ${REF}[0] for a reference to an array.

If it's @a for an named array, it's @{REF} for a reference to an array.

Easy!

my $i    =    ${ $linkarray }[0];
my @arr2 = @{ ${ $linkarray }[1] };
my @arr3 = @{ ${ $linkarray }[2] };

However, the following is easier to read:

my $i    =    $linkarray->[0];
my @arr2 = @{ $linkarray->[1] };
my @arr3 = @{ $linkarray->[2] };

Furthermore, you really shouldn't be making copies of those arrays like that. It's rather wasteful. Just work with the references.

my $i    = $linkarray->[0];
my $arr2 = $linkarray->[1];
my $arr3 = $linkarray->[2];

Finally, that simplifies to the following:

my ($i, $arr2, $arr3) = @$linkarray;

References:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.