While answering this question, I came to realize that I was not sure whether Perl\'s map
can be considered a loop or not?
On one hand, it quacks/walks l
From an academic standpoint, a case can be made for both depending on how map is defined. If it always iterates in order, then a foreach
loop could be emulated by map
making the two equivalent. Some other definitions of map may allow out of order execution of the list for performance (dividing the work amongst threads or even separate computers). The same could be done with the foreach
construct.
But as far as Perl 5 is concerned, map
is always executed in order, making it equivalent to a loop. The internal structure of the expression map $_*2, 1, 2, 3
results in the following execution order opcodes which show that map
is built internally as a while
-like control structure:
OP enter
COP nextstate
OP pushmark
SVOP const IV 1
SVOP const IV 2
SVOP const IV 3
LISTOP mapstart
LOGOP (0x2f96150) mapwhile <-- while still has items, shift one off into $_
PADOP gvsv GV *_
SVOP const IV 2 loop body
BINOP multiply
goto LOGOP (0x2f96150) <-- jump back to the top of the loop
LISTOP leave