| [3181] | 1 | package autouse;
|
|---|
| 2 |
|
|---|
| 3 | #use strict; # debugging only
|
|---|
| 4 | use 5.003_90; # ->can, for my $var
|
|---|
| 5 |
|
|---|
| 6 | $autouse::VERSION = '1.05';
|
|---|
| 7 |
|
|---|
| 8 | $autouse::DEBUG ||= 0;
|
|---|
| 9 |
|
|---|
| 10 | sub vet_import ($);
|
|---|
| 11 |
|
|---|
| 12 | sub croak {
|
|---|
| 13 | require Carp;
|
|---|
| 14 | Carp::croak(@_);
|
|---|
| 15 | }
|
|---|
| 16 |
|
|---|
| 17 | sub import {
|
|---|
| 18 | my $class = @_ ? shift : 'autouse';
|
|---|
| 19 | croak "usage: use $class MODULE [,SUBS...]" unless @_;
|
|---|
| 20 | my $module = shift;
|
|---|
| 21 |
|
|---|
| 22 | (my $pm = $module) =~ s{::}{/}g;
|
|---|
| 23 | $pm .= '.pm';
|
|---|
| 24 | if (exists $INC{$pm}) {
|
|---|
| 25 | vet_import $module;
|
|---|
| 26 | local $Exporter::ExportLevel = $Exporter::ExportLevel + 1;
|
|---|
| 27 | # $Exporter::Verbose = 1;
|
|---|
| 28 | return $module->import(map { (my $f = $_) =~ s/\(.*?\)$//; $f } @_);
|
|---|
| 29 | }
|
|---|
| 30 |
|
|---|
| 31 | # It is not loaded: need to do real work.
|
|---|
| 32 | my $callpkg = caller(0);
|
|---|
| 33 | print "autouse called from $callpkg\n" if $autouse::DEBUG;
|
|---|
| 34 |
|
|---|
| 35 | my $index;
|
|---|
| 36 | for my $f (@_) {
|
|---|
| 37 | my $proto;
|
|---|
| 38 | $proto = $1 if (my $func = $f) =~ s/\((.*)\)$//;
|
|---|
| 39 |
|
|---|
| 40 | my $closure_import_func = $func; # Full name
|
|---|
| 41 | my $closure_func = $func; # Name inside package
|
|---|
| 42 | my $index = rindex($func, '::');
|
|---|
| 43 | if ($index == -1) {
|
|---|
| 44 | $closure_import_func = "${callpkg}::$func";
|
|---|
| 45 | } else {
|
|---|
| 46 | $closure_func = substr $func, $index + 2;
|
|---|
| 47 | croak "autouse into different package attempted"
|
|---|
| 48 | unless substr($func, 0, $index) eq $module;
|
|---|
| 49 | }
|
|---|
| 50 |
|
|---|
| 51 | my $load_sub = sub {
|
|---|
| 52 | unless ($INC{$pm}) {
|
|---|
| 53 | require $pm;
|
|---|
| |
|---|