Let's say I want to wrap require
such that,
package MyModule;
use Data::Dumper;
Would output either,
MyModule -> Data::Dumper
MyModule -> Data/Dumper.pm
For all packages and all requires
/use
statements. How could I do it?
Let's say I want to wrap require
such that,
package MyModule;
use Data::Dumper;
Would output either,
MyModule -> Data::Dumper
MyModule -> Data/Dumper.pm
For all packages and all requires
/use
statements. How could I do it?
BEGIN {
unshift @INC, sub {
printf "%s -> %s\n", ( caller() )[0], $_[1];
return;
};
}
See the paragraph starting with "You can also insert hooks into the import facility" in require
's documentation.
You cannot reference the require
builtin as a subroutine such as for goto
, but you can call it from CORE.
use strict;
use warnings;
BEGIN {
*CORE::GLOBAL::require = sub {
printf "%s -> %s\n", [caller()]->[0], $_[0];
CORE::require $_[0];
}
};
use Data::Dumper;
You may also consider Devel::TraceUse which is similar to the above but more robust and informative, and can easily be invoked from the commandline.
You can look inside Devel::TraceUse to see working code for what you are trying to do. But, changing definitions isn't a good plan because you don't know who else also changed definitions and will wonder why their stuff stops working.
You don't need to (or should) override require
. Put a code reference in @INC
and return false at the end so it looks like that failed and Perl will move on to the next thing in @INC
:
#!perl
use v5.10;
# https://stackoverflow.com/a/2541138/2766176
BEGIN {
unshift @INC, sub {
my( $package, $file ) = caller(0);
say "$package -> $_[1]";
return 0;
};
}
use Data::Dumper;
say "Hello";
This outputs:
main -> Data/Dumper.pm
Data::Dumper -> constant.pm
constant -> strict.pm
constant -> warnings/register.pm
warnings::register -> warnings.pm
Data::Dumper -> Carp.pm
Carp -> overloading.pm
Carp -> Exporter.pm
Data::Dumper -> XSLoader.pm
Data::Dumper -> bytes.pm
Hello
Weird requirement needs weird solution: Use a source filter.
#!/usr/bin/perl
{ package Wrap::Use;
use Filter::Simple sub {
warn $1 while /use (.*?);/sg; # stupid SO: /
};
}
BEGIN { Wrap::Use->import }
use strict;
use warnings;
use Time::Piece;