views:

426

answers:

3

I have an array that is a member of an 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 excute 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?

+5  A: 

$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);
FM
+5  A: 

$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.

Chris Simmons
+8  A: 

I believe that:

$self->{myArray} returns a reference.

You want to return the array:

@{$self->{myArray}}
chollida
Ahh beaten to the punch by FM:)
chollida
And just in case you want to know how to do this for a hash ref:%{$self->{myHash}}
Kevin