Remember that
is syntax sugar forsub foo(&); foo { ... };
foo(sub { ... });
On the other hand, the block for map is no more a sub than the block for for.
use strict; use warnings; sub my_map(&@) { my $cb = shift; my @rv; push @rv, $cb->($_) for @_; return @rv; } sub map_tester { print("pre\n"); map { print("in\n"); return 1 } 1; print("post\n"); } sub my_map_tester { print("pre\n"); my_map { print("in\n"); return 1 } 1; print("post\n"); } map_tester(); print("\n"); my_map_tester();
pre in pre in post
Why the difference in behavior?
The only existing means of calling a detached (e.g. referenced) opcode tree is a sub.
That's true even at a very low level. That's why map isn't implemented as a function that takes the block as an argument. map is truly a flow control structure.
For example, @b = map { foo() } @a compiles into something like the following:
my @anon_list; for (@a) { push @anon_list, foo(); } @b = @anon_list;
There's obviously no way to compile a call my_map into a loop, so differences are to be expected.
In reply to Re: map and return
by ikegami
in thread map and return
by ELISHEVA
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |