Skip to content

Instantly share code, notes, and snippets.

@mechairoi
Created June 16, 2011 16:42
Show Gist options
  • Save mechairoi/1029656 to your computer and use it in GitHub Desktop.
Save mechairoi/1029656 to your computer and use it in GitHub Desktop.
# SEE ALSO Devel::TraceLoad::Hook
# %INCにちゃんともとのパスが入ってるのはなんでだろう?
package Hook::EndOfRequire;
use warnings;
use strict;
use Carp qw( croak );
use Exporter::Lite;
use Module::Locate qw( get_source );
use B::Hooks::EndOfScope;
our @EXPORT = our @EXPORT_OK = qw( add_end_of_require_hook );
my %Hook;
unshift @INC, sub {
my ($code, $filename) = @_;
$Hook{$filename} or return;
my $package = __PACKAGE__;
local @INC = grep { ref $_ ne 'CODE' || $_ != $code } @INC;
my $data = "use B::Hooks::EndOfScope; on_scope_end { ${package}::__run(q($filename)) };"
. get_source($filename);
open(my $fh, '<', \$data);
return $fh;
};
sub __run {
$_->() for (@{delete $Hook{$_[0]} || []});
}
sub add_end_of_require_hook (&$) {
my ($code, $module, %args) = @_;
my $filename = $module . ".pm";
$filename =~ s/::/\//g;
if($INC{$filename}) {
croak "$filename is already loaded" if ($args{strict});
warn "$filename is already loaded";
$code->();
} else {
$Hook{$filename} ||= [];
push @{$Hook{$filename}}, $code;
}
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment