I'm wondering if there is a way to import a sub from another package as a lexical sub without using non-core modules.

The motivation is that I like to ship CPAN modules with the fewest dependencies possible for the sake of minimalism. A common desire when authoring the module is to use functions from other packages, but not litter my method namespace with those functions. The "best practice" way to do that is:

use Scalar::Util 'looks_like_number'; use namespace::clean; ... looks_like_number($x) ...
but namespace::clean is not a core module. The most minimal of all options is to just reference the function by its full name:
use Scalar::Util (); ... Scalar::Util::looks_like_number($x) ...
but that is tedious and makes me unhappy while writing the code.

I have the option of lexical subs:

use v5.20; use experimental 'lexical_subs'; use Scalar::Util (); my sub looks_like_number { &Scalar::Util::looks_like_number } ... looks_like_number($x) ...
but I'm introducing a tiny bit of runtime inefficiency for the sake of more pleasant authoring.

What I really want is:

use v5.20; use experimental 'lexical_subs'; use Scalar::Util (); my sub looks_like_number = \&Scalar::Util::looks_like_number; ... looks_like_number($x) ...
but this gives me "Illegal declaration of subroutine looks_like_number".

Is there any way in pure-perl with only core modules to achieve a lexical sub which *is* the same coderef as the fully qualified global name?


In reply to Pure perl lexical sub import by NERDVANA

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.