I was wondering if the foreach statement in Perl iterates the items in an array in consistent order? That is, do I get different results if I use foreach multiple times on the same array or list?
Yes, items in a foreach
statement are iterated in order.
Your question might arise from confusion over iterating over the elements of a hash:
my %hash = ('a' => 1, 'b' => 2, 'c' => 3);
foreach my $key (keys %hash) { print $key } ; # output is "cab"
But the seemingly random order is an artifact of how data are stored in a Perl hash table (data in a Perl hash table are not ordered). It is the keys
statement that is "changing" the order of the hash table, not the foreach
.
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