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?
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.
Use Array#forEach method for array iteration.
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: " .
I believe that:
$self->{myArray} returns a reference.
You want to return the array:
@{$self->{myArray}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With