Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: "importing" methods?

by tobyink (Canon)
on Apr 27, 2019 at 07:50 UTC ( [id://1233032]=note: print w/replies, xml ) Need Help??


in reply to "importing" methods?

Hmmm, it's an interesting idea. I poked around CPAN searching for "curry" in hope, but nothing quite like what you wanted. Personally, I think something like this isn't too bad, for small scopes at least:

for ($object) { $_->log("blah"); }

But yeah, you could certainly implement it in probably only a few lines of code, using Exporter::Lexical and curry.

Replies are listed 'Best First'.
Re^2: "importing" methods?
by tobyink (Canon) on Apr 27, 2019 at 08:32 UTC

    This works. It actually works better without curry because then you don't need $object to be defined yet at compile-time.

    use 5.018; use strict; use warnings; BEGIN { package Foo; use Moo; sub meth { die unless ref shift; join "|", @_; } sub othermeth { die unless ref shift; join ":", @_; } $INC{'Foo.pm'} = __FILE__; }; BEGIN { package curry::lexical; use Exporter::Lexical (); use Exporter::Tiny (); sub import { my $me = shift; my $objref = shift; my $optlist = Exporter::Tiny::mkopt(\@_); for my $method (@$optlist) { my ($name, $currystuff) = @$method; my ($originalname, @args) = ref($currystuff) ? @$currystuf +f : $name; my $coderef = sub { $$objref->$originalname(@args, @_) }; Exporter::Lexical::lexical_import($name, $coderef); } } $INC{'curry/lexical.pm'} = __FILE__; }; use Test::More; sub meth { "FUNCTION" } is meth("foo"), "FUNCTION"; { my $obj = Foo->new; use curry::lexical \$obj, "meth", "meth2" => ["meth", "prefix"], " +othermeth"; is meth("foo"), "FUNCTION", "non-lexical sub wins"; is meth2("foo"), "prefix|foo"; is othermeth("foo", "bar"), "foo:bar"; } is meth("foo"), "FUNCTION"; done_testing;

    So with your example, you could do something like:

    my $app = MyApp->new; { use curry::lexical \$app, qw(log foo bar), critical_log => [log => " +CRITICAL"]; log("Hi"); # $app->log("Hi"); foo(); # $app->foo(); bar(123); # $app->bar(123); critical_log(); # $app->log("CRITICAL"); }

    The functions imported via curry::lexical cannot overwrite "normal" functions, as shown in the second test of the test script.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1233032]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (7)
As of 2024-04-26 09:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found