Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Getting module to call importer's function

by ikegami (Patriarch)
on Sep 22, 2004 at 21:05 UTC ( [id://393048]=note: print w/replies, xml ) Need Help??


in reply to Getting module to call importer's function

Like this?

sub x { my $func = do { no strict 'refs'; *{caller() . '::_x'}{CODE} }; die() unless defined $func; &$func; # or &$func(...); }

Test code:

package M; use strict; use warnings; BEGIN { our ISA 'Exporter'; our EXPORT_OK qw ( x ); require Exporter; *import = \&Exporter::import; } sub x { my $func = do { no strict 'refs'; *{caller() . '::_x'}{CODE} }; die() unless defined $func; &$func; # or &$func(...); } 1; ^^^ M.pm ^^^ vvv script.pl vvv use strict; use warnings; use M qw( x ); sub _x { print("main::_x(" . join(', ', @_) . ")\n"); } x('a', 'b'); __END__ outputs ======= main::_x(a, b)

But you know what, it would be much cleaner if you did:

package M; use strict; use warnings; BEGIN { our ISA 'Exporter'; our EXPORT_OK qw ( x ); require Exporter; *import = \&Exporter::import; } sub x { my $callback = shift(@_); &$callback; # or &$callback(...); } 1; ^^^ M.pm ^^^ vvv script.pl vvv use strict; use warnings; use M qw( x ); sub _x { print("main::_x(" . join(', ', @_) . ")\n"); } x(\&_x, 'a', 'b'); __END__ outputs ======= main::_x(a, b)

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2024-04-23 23:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found