Btw, I seriously dislike your use of the binary operators for math there. You have much better options to gain speed without obfuscating the code. F.ex, if your @_ check never fails, your indiscriminate use will have cost you much more time than those two binary ops are ever going to save. Futhermore, you're mapping in void context - another waste of effort. (What was he thinking?? -- Ed.) Here is a version that I find more self documenting and more concise - and it even gets rid of one division entirely! :^)
#!/usr/bin/perl -w use strict; sub map2 (&@) { my $code = shift; if(@_ % 2) { require Carp; Carp::croak('Odd number of values in list'); } local ($a, $b); my @r; push @r, $code->() while ($a, $b) = splice @_, 0, 2; @r; } my %hash = qw/A B C D E F G H/; # let's remove the multiple calls to print() and # make the use of a map justifiable, shall we? print map2 sub { "key $a => value $b\n" }, %hash;
Update: I can't believe I didn't think about the list being returned. However, the while loop still avoids building a 1 .. @_ / 2 list, thus still saving effort.

Makeshifts last the longest.


In reply to Re: Problem emulating built-ins like map and grep. by Aristotle
in thread Problem emulating built-ins like map and grep. by BrowserUk

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.