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.


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.