Prototypes in perl5 have gotten a bit of a bad reputation, some of which is deserved. If people ask me why we should use them at all, however, I do have an example that always respond with map2, which is like the built-in map except that it accepts two arrays as arguments (instead of a single list).

=item my @result = map2 BLOCK ARRAY, ARRAY; Similar to c<map>, but operate on two lists at once. Inside the BLOCK, the value are passed in as C<$a> and C<$b> (as in C<sort>). my @a = ( 1, 2, 5, 7, ); my @b = ( 3, 4, 6, 8 ); my @sums = map2 { $a+$b } @a, @b; my @prods = map2 { $a*$b } @a, @b; One use is to initialize hashes from two arrays. You can do this in straight perl with: my %hash; @hash{@hash_keys} = @values; With this subroutine, you could also do: my %hash = map2 { ( $a => $b ) } @hash_keys, @values; If the arrays are not the same length, the shorter array is used to limit how far we go in each array. BLOCK is evaluated in list context. =cut sub map2 ( & \@ \@ ) { my ( $code_ref, $a_ref, $b_ref ) = @_; my $rv_len = ( @$a_ref < @$b_ref ) ? @$a_ref : @$b_ref; my @rv; for ( my $i = 0; $i < $rv_len; ++$i ) { local ( $a, $b ) = ( $a_ref->[$i], $b_ref->[$i] ); push @rv, $code_ref->(); } return @rv; }

I know I saw something like this from Abigail (or is that Abigail-II?) in the late '90s, but I have since reimplemented it a few times. As I said, it serves as a handy example to demonstrate how prototypes make some things possible that would otherwise be difficult to impossible to code.

Update (2004-05-02 00:15 -0700): Incorporated some suggestions from Zaxo to fix some misleading variable names. Thanks!


In reply to A classic use of prototypes: map2 by tkil

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.