How can I extract an array from a two-dimensional array in Perl?
I have once again forgot开发者_StackOverflow社区ten 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?
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;
}
for (@TWO_DIM_ARRAY) {
my @arr = @$_;
}
The $_
will be array references (not arrays), so you need to dereference it as:
my @ARRAY = @$_;
精彩评论