Skip to content

Instantly share code, notes, and snippets.

@ilmari
Forked from arodland/loaded.pm
Last active December 31, 2015 01:59
Show Gist options
  • Save ilmari/7918174 to your computer and use it in GitHub Desktop.
Save ilmari/7918174 to your computer and use it in GitHub Desktop.
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