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

Re^2: Overriding 'use'?

by xdg (Monsignor)
on Sep 12, 2005 at 11:26 UTC ( [id://491222]=note: print w/replies, xml ) Need Help??


in reply to Re: Overriding 'use'?
in thread Overriding 'use'?

Also, depending on what you want to do, you could override the import routine of a module, either wrapping it or replacing it entirely. You still suffer the load penalties of require, but you can rejigger the part that actually does work. Not sure why you would want to do it, but just want to point out that it's possible.

# Replace Data::Dumper::import BEGIN { no warnings 'redefine'; require Data::Dumper; *Data::Dumper::import = sub { warn "Can't use Data::Dumper" }; }

Since a module is only require-ed once, any subsequent calls to use Data::Dumper should skip the require call, but will invoke your new "import" routine. I'd guess this is only really useful if you wrap it rather than replace it. E.g.

# Count times "Data::Dumper::import" is called, e.g. via use BEGIN { no warnings 'redefine'; require Data::Dumper; # initialize the counter my $dumper_counter = 0; # save the original import sub before replacing it my $dumper_import = *Data::Dumper::import{CODE}; # install import wrapper with closures *Data::Dumper::import = sub { $dumper_counter++; $dumper_import->(@_); }; }

Big warning bells should be going off in your head if you actually want to try stuff like this. (E.g. import isn't always called; import looks at caller to find what package to install into, so you may need to use Sub::Uplevel to fake it, etc.) This is fine for experimentation, but I'd warn against it for any production needs. But, nevertheless, it's instructive into just how flexible the Perl symbol table system is.

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2024-03-28 14:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found