use v5.12; use warnings; use lib "."; ReUse::reuse("My" => 1,2,3); My::Run("normal"); eval 'My::Run("eval")'; ReUse::reuse("My" => 1,2,3); My::Run("normal"); eval 'My::Run("eval")'; package Test; my $data = [1..5]; say "\n\n---- ReImporting from module"; ReUse::reuse("Data::Dump" => qw/pp/); pp($data); # test import say "\n\n---- ReImporting from module"; ReUse::reuse("Data::Dump" => qw/pp/); pp($data); # test import exit; # --- this should probably be a proper CPAN Module package ReUse; sub reuse { my ($module, @imports) = @_; # --- purge %INC my $inc_key = "$module.pm"; $inc_key =~ s(::)(/)g; my $oldpath = delete $INC{$inc_key}; # --- build code # --- require at runtime my $PACKAGE = (caller)[0]; my $REQUIRE = $inc_key; eval <<"__CODE__"; package $PACKAGE; require "$REQUIRE"; __CODE__ if ($@) { die qq(REQUIRE of "$module" failed with: <$@>); } # --- import at runtime my $IMPORTS = join ",", map {"'$_'"} @imports; eval <<"__CODE__"; package $PACKAGE; $module->import($IMPORTS); __CODE__ if ($@) { die qq(IMPORT OF "$module->import($IMPORTS)" failed with: <$@>); } # --- warn if module's path changed # TODO make optional if ($oldpath and $oldpath ne $INC{$inc_key}) { # untested TODO warn "Path of $module changed"; } }