1

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?

1
  • Can you show the data you are starting with and what you want to end up with, even if in pseudocode? Oct 14, 2010 at 21:44

3 Answers 3

5

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;
}
3
  • 1
    +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
    Oct 14, 2010 at 10:27
  • Still, why doesn't this work: foreach(@TWO_DIM_ARRAY){ print join ',',@{$_}; } After all, $_ is an array reference, and @{$_} should be an array. Oct 23, 2010 at 16:57
  • @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
    Oct 23, 2010 at 19:27
4
for (@TWO_DIM_ARRAY) {
    my @arr = @$_;
}
4

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

my @ARRAY = @$_;

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.