Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 284
Alceu Costa Avatar asked Aug 27 '09 16:08

Alceu Costa


People also ask

Is it possible to iterate over arrays?

Iterating over an arrayYou can iterate over an array using for loop or forEach loop. Using the for loop − Instead on printing element by element, you can iterate the index using for loop starting from 0 to length of the array (ArrayName. length) and access elements at each index.

Which method is used to iterate over arrays and objects?

Use Array#forEach method for array iteration.

How do I slice an array in Perl?

Array slicing can be done by passing multiple index values from the array whose values are to be accessed. These values are passed to the array name as the argument. Perl will access these values on the specified indices and perform the required action on these values. print "Extracted elements: " .


1 Answers

I believe that:

$self->{myArray} returns a reference.

You want to return the array:

@{$self->{myArray}}
like image 61
chollida Avatar answered Sep 28 '22 03:09

chollida