tags:

views:

67

answers:

3

I have once again forgotten how to get $_ to represent an array when it is in a loop of a two dimensional array.

foreach(@TWO_DIM_ARRAY){
   my @ARRAY = $_;
}

That's the intention, but that doesn't work. What's the correct way to do this?

+3  A: 
for (@TWO_DIM_ARRAY) {
    my @arr = @$_;
}
zakovyrya
+3  A: 

The $_ will be array references (not arrays), so you need to dereference it as:

my @ARRAY = @$_;
codaddict
+5  A: 

The line my @ARRAY = @$_; (instead of = $_;) is what you're looking for, but unless you explicitly want to make a copy of the referenced array, I would use @$_ directly.

Well, actually I wouldn't use $_ at all, especially since you're likely to want to iterate through @$_, and then you use implicit $_ in the inner loop too, and then you could have a mess figuring out which $_ is which, or if that's even legal. Which may have been why you were copying into @ARRAY in the first place.

Anyway, here's what I would do:

for my $array_ref (@TWO_DIM_ARRAY) {

    # You can iterate through the array:
    for my $element (@$array_ref) {
        # do whatever to $element
    }

    # Or you can access the array directly using arrow notation:
    $array_ref->[0] = 1;
}
Jander
+1 for the for my $var syntax. Seems like a lot of people don't bother with this, though it improves readability quite a lot.
Sorpigal
Still, why doesn't this work: foreach(@TWO_DIM_ARRAY){ print join ',',@{$_}; } After all, $_ is an array reference, and @{$_} should be an array.
Michael Goldshteyn
@Michael Goldshteyn: That will work too. `@{$_}` is the same as `@$_`. For example, I just tried this: `my @A=([1,2,3],[4,5,6],[7,8,9]); foreach(@A) { print join(",", @{$_}), "\n"; }`
Jander