-
-
Save ilmari/7918174 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package if::loaded; | |
use Module::Runtime qw(module_notional_filename use_module); | |
sub work { | |
my $method = shift() ? 'import' : 'unimport'; | |
my %args = map { $_ => [] } qw(try else args); | |
my $arg = 'try'; | |
for (@_) { | |
if (/\A-(.*)\z/) { | |
die "Invalid option '$_'\n" | |
unless exists $args{$1}; | |
$arg = $1; | |
next; | |
} | |
push $args{$arg}, $_ | |
} | |
die "Need at least one module" unless @{$args{try}}; | |
die "Only one fallback module allowed" if @{$args{else}} > 1; | |
for my $module (@{$args{try}}) { | |
if ($INC{module_notional_filename($module)}) { | |
if (my $m = $module->can($method)) { | |
@_ = ($module, @{$args{args}}); | |
goto &$m; | |
} | |
return; | |
} | |
} | |
my $module = $args{else}[0] or die "no modules loaded and no -else\n"; | |
if (my $m = use_module($module)->can($method)) { | |
@_ = ($module, @{$args{args}}); | |
goto &$m; | |
} | |
} | |
sub import { shift; unshift @_, 1; goto &work } | |
sub unimport { shift; unshift @_, 0; goto &work } | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment