views:

165

answers:

3

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?

+1  A: 

If you don't change the list in between times, it will alawys be in a consistent order.

MatthieuF
+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
Thanks mobrule.
ablimit
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
A: 

The reasoning for why Perl's foreach loop hash ordering is seemingly random is in the perlsec document, linked here

Narthring