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?
views:
165answers:
3
+1
A:
If you don't change the list in between times, it will alawys be in a consistent order.
MatthieuF
2010-04-30 21:35:25
+8
A:
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
.
mobrule
2010-04-30 21:37:55
Thanks mobrule.
ablimit
2010-04-30 21:39:14
Just 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
2010-05-01 10:40:16