in reply to Pure perl lexical sub import

Another option using two packages (inspired by Re^8: In praise of Perl's object system. (OO namespaces))
use v5.36; package Foo::Internal { use Scalar::Util 'looks_like_number'; sub check_it ($self, $num) { say 'Hoorah!' if looks_like_number($num); } } package Foo { sub new ($class) { bless {} => $class; } no warnings 'once'; *check_it = \&Foo::Internal::check_it; } my $foo = Foo->new; $foo->check_it(42); $foo->looks_like_number(42);
Then
% perl internal.pl Hoorah! Can't locate object method "looks_like_number" via package "Foo" at in +ternal.pl line 22.

Replies are listed 'Best First'.
Re^2: Pure perl lexical sub import
by NERDVANA (Priest) on Dec 22, 2024 at 20:01 UTC

    So you mean basically have a scope where they're imported be a different package than what eventually holds the object methods, by copying out the functions into that other package?

    I suppose it works, but I'm having trouble imagining how I would structure things so that it is less ugly than just calling the external function by its full name in the intended package.

      There'd be one package which is your actual clean namespace meant for end users, and another package containing the implementation details.

      It only looks ugly because I was tired and didn't use Exporter. So with Exporter it would be like this

      :::::::::::::: Foo/Internal.pm :::::::::::::: use v5.36; package Foo::Internal { use Exporter 'import'; our @EXPORT = qw[check_it]; use Scalar::Util 'looks_like_number'; sub check_it ($self, $num) { say 'Hoorah!' if looks_like_number($num); } } 1; :::::::::::::: Foo.pm :::::::::::::: use v5.36; package Foo { use Foo::Internal; sub new ($class) { bless {} => $class; } } 1; :::::::::::::: clean.pl :::::::::::::: use v5.36; use Foo; my $foo = Foo->new; $foo->check_it(42); $foo->looks_like_number(42);