Yevgeny Simkin
Yevgeny Simkin

Reputation: 28389

How can I extract an array from a two-dimensional array in Perl?

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?

Upvotes: 1

Views: 2925

Answers (3)

Jander
Jander

Reputation: 5677

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;
}

Upvotes: 5

codaddict
codaddict

Reputation: 455380

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

my @ARRAY = @$_;

Upvotes: 4

zakovyrya
zakovyrya

Reputation: 9689

for (@TWO_DIM_ARRAY) {
    my @arr = @$_;
}

Upvotes: 4

Related Questions