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?
Asked
Active
Viewed 2,018 times
3 Answers
9
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
.

mob
- 117,087
- 18
- 149
- 283
-
1Just to be pedantic, `keys` does not change the order of the hash table - if you call `keys` repeatedly on the same hash without inserting or deleting any keys, it will return the keys in the same order every time. The order is being changed by the act of storing the data in a hash in the first place. Hashes store the data in an order which is deterministic, but unpredictable (making it effectively unordered for most practical purposes). – Dave Sherohman May 01 '10 at 10:40
-
1Just adding a link to a related question: [Is Perl guaranteed to return consistently-ordered hash keys? - Stack Overflow](http://stackoverflow.com/questions/1256502/is-perl-guaranteed-to-return-consistently-ordered-hash-keys) – sdaau Oct 31 '12 at 09:21
1
If you don't change the list in between times, it will alawys be in a consistent order.

Matthew Farwell
- 60,889
- 18
- 128
- 171