Remember that

sub foo(&); foo { ... };
is syntax sugar for
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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.