in reply to Re: "importing" methods?
in thread "importing" methods?

Sorry but I don't see how to realize my concept with roles ,especially with the modules you mentioned. (?)

Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Replies are listed 'Best First'.
Re^3: "importing" methods?
by Corion (Patriarch) on Apr 26, 2019 at 20:05 UTC

    Aaah, sorry - I misread/misunderstood what you wanted to do.

    A global version of what you seem to want to do is Object::Import, which exports some or all methods of a (default) object and makes them available as functions:

    use Object::Import $object; foo(@bar); # now means $object->foo(@bar);

    The module does not act on a lexical scope though, and I'm not sure what a good way would be to save/restore this lexical scope. I would expect parsing mishaps / parsing confusion for Perl if you redefine subroutine bindings based on the dynamic scope, and I don't see any better way to implement something like this in Perl, unless you implement something like the Javascript version of with as well. Importing dynamically is easy:

    { my $object = Foo::Bar->new(); import Object::Import $object; # Make all methods of $object avail +able as functions }

    The hard part is unimporting stuff, and you could do that by localizing your namespace every time you import an object, but that will be weird if you actually try to change your namespace:

    #!perl use strict; use warnings; package Foo::Bar; sub frobnitz { print "frobnitz in " . __PACKAGE__ . "\n"; }; package Foo::Whatever; use strict; use warnings; require Object::Import; sub frobnitz { print "frobnitz in " . __PACKAGE__ ."\n"; }; frobnitz(); { local *Foo::Whatever::frobnitz; my $object = {}; bless $object => "Foo::Bar"; Object::Import->import( $object, list => ['frobnitz'], nowarn_rede +fine => 1 ); # Make all methods of $object available as functions frobnitz(); # call $object->frobnitz(); } frobnitz(); __END__ frobnitz in Foo::Whatever frobnitz in Foo::Bar frobnitz in Foo::Whatever

    In the above, I localize frobnitz(), but the hard part will be to make that localization non-local when putting all of that in a subroutine with. Maybe namespace::autoclean has a hint on how to implement something like this.

    If you don't care that much about restoring the dynamic namespace/scope again, Object::Import should already work.