Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl, foreach order

Tags:

foreach

perl

Does Perl's foreach loop operator require that the list items be presented in order?

For example

my @a=(1,2,3);

foreach my $item (@a) {
 print $item;
}

will always print 1 2 3?

I suspect so, but I can't find it documented.

like image 541
Mike Avatar asked Jun 15 '10 16:06

Mike


People also ask

What is Perl foreach?

A foreach loop runs a block of code for each element of a list. No big whoop, “perl foreach” continues to be one of the most popular on Google searches for the language.

Which can be correct syntax of foreach in Perl?

A foreach loop is used to iterate over a list and the variable holds the value of the elements of the list one at a time. It is majorly used when we have a set of data in a list and we want to iterate over the elements of the list instead of iterating over its range.

What is the difference between for and foreach in Perl?

There is no difference. From perldoc perlsyn: The foreach keyword is actually a synonym for the for keyword, so you can use foreach for readability or for for brevity.


1 Answers

Yes.

Some apparent complexity (arrays are in order, but hashes are not--WTF?) comes from the fact that most answers are ignoring the importance of context.

Perl variables, functions, operators and subroutines may evaluate to different values depending on context. Context can either be scalar or list.

In scalar context, we want only one value. For example my $count = @array; assigns the number of elements in @array to $count, because assignment to a scalar provides a scalar context.

In list context we are looking for multiple values. For example, my @merged = @left, @right;. Assignment to an array provides list context, so @left and @right are expanded into a lists of their elements. Since lists are flat structures, we have one long list that combines elements from both arrays. Finally, the list of values is assigned to @merged.

The reason that most of the answers gloss over this is that, even though context seems strange at first, 99% of the time context works transparently and does what you'd expect.

The for loop provides a list context. This means that whatever is inside the parenthesis is interpreted in list context. The resulting list is then iterated over in order.

What this means is that:

  • for (@array) {} expands the array into list of elements, preserving the order of the array.
  • for (%hash) {} expands the hash into a random ordered list of key/value pairs.
  • for ( <FILEHANDLE> ) {} reads all the lines available from the filehandle and presents them in order.
  • for ( some_subroutine() ) {} evaluates some_subroutine() in list context and iterates over the results.
like image 140
daotoad Avatar answered Sep 25 '22 01:09

daotoad