Alceu Costa
Alceu Costa

Reputation: 9899

How can I iterate over a Perl array reference?

I have an array that is a member of a structure:

$self->{myArray} = ["value1", "value2"];

And I'm trying to iterate over it using the following code:

my @myArray = $self->{myArray};
foreach my $foo (@myArray){
    #Do something with the using $foo
    ...
}

The problem is that the 'foreach' loop is executed only once (when I would expect it to execute twice, since @myArray has two elements: "value1" and "value2").

When I check the @myArray array size, I get that its size is 1. What am I doing wrong in this code?

Upvotes: 22

Views: 26548

Answers (3)

Chris Simmons
Chris Simmons

Reputation: 1853

$self->{myArray} is an array reference, not an array - you can't store actual arrays inside a hash, only references. Try this:

my $myArray = $self->{myArray};
for my $foo (@$myArray){
   # do something with $foo
}

You also may want to have a look at perldoc perlref.

Upvotes: 7

FMc
FMc

Reputation: 42421

$self->{myArray} is an array reference. You need to dereference it.

my @myArray = @{ $self->{myArray} };

In situations like this, the Data::Dumper module is very helpful. For example, if @myArray were not behaving as expected, you could run this code to reveal the problem.

use Data::Dumper;
print Dumper(\@myArray);

Upvotes: 11

chollida
chollida

Reputation: 7894

I believe that:

$self->{myArray} returns a reference.

You want to return the array:

@{$self->{myArray}}

Upvotes: 34

Related Questions