Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the foreach statement iterate in order or it might be random order?

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?

like image 294
ablimit Avatar asked Apr 30 '10 21:04

ablimit


1 Answers

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.

like image 108
mob Avatar answered Oct 03 '22 23:10

mob