Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Perl offers a system called subroutine prototypes that allow you to write user subs that get parsed in a way similar to the builtin functions. The builtins that you want to emulate are <code>map</code>, <code>grep</code>, or <code>sort</code> which can each take a block as their first argument.</p> <p>To do that with prototypes, you use <code>sub name (&amp;) {...}</code> where the <code>&amp;</code> tells perl that the first argument to the function is either a block (with or without <code>sub</code>), or a literal subroutine <code>\&amp;mysub</code>. The <code>(&amp;)</code> prototype specifies one and only one argument, if you need to pass multiple arguments after the code block, you could write it as <code>(&amp;@)</code> which means, a code block followed by a list.</p> <pre><code>sub higher_order_fn (&amp;@) { my $code = \&amp;{shift @_}; # ensure we have something like CODE for (@_) { $code-&gt;($_); } } </code></pre> <p>That subroutine will run the passed in block on every element of the passed in list. The <code>\&amp;{shift @_}</code> looks a bit cryptic, but what it does is shifts off the first element of the list, which should be a code block. The <code>&amp;{...}</code> dereferences the value as a subroutine (invoking any overloading), and then the <code>\</code> immediately takes the reference to it. If the value was a CODE ref, then it is returned unchanged. If it was an overloaded object, it is turned into code. If it could not be coerced into CODE, an error is thrown.</p> <p>To call this subroutine, you would write:</p> <pre><code>higher_order_fn {$_ * 2} 1, 2, 3; # or higher_order_fn(sub {$_ * 2}, 1, 2, 3); </code></pre> <p>The <code>(&amp;@)</code> prototype that lets you write the argument as a <code>map</code>/<code>grep</code> like block only works when using the higher order function as a function. If you are using it as a method, you should omit the prototype and write it this way:</p> <pre><code>sub higher_order_method { my $self = shift; my $code = \&amp;{shift @_}; ... $code-&gt;() for @_; } ... $obj-&gt;higher_order_method(sub {...}, 'some', 'more', 'args', 'here'); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload