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.
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.
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.
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.
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With