alpha has asked for the wisdom of the Perl Monks concerning the following question:

I am looking for a way to unload (and after that, reload) a module at run time. I have found this code: https://metacpan.org/source/ALEXMV/Module-Refresh-0.17/lib/Module/Refresh.pm and am using bits of it:
# class.pm package class; use 5.014; use strict; use warnings; use autodie; sub new {bless {}, 'class'} sub talk {print "111513\n"} # code.pl #!/usr/bin/env perl use strict; use warnings; use autodie; use 5.014; use Data::Dumper; BEGIN { $^P |= 0x10; eval 'sub DB::sub' if $] < 5.008007; } sub _unload_subs { my $file = shift || return; for my $sym ( grep { index( $_, "$file:" ) == 0 } keys %DB::sub ) +{ eval { undef &$sym }; warn "$sym: $@\n" if $@; delete $DB::sub{$sym}; } return 1; } do './class.pm'; my $obj = class->new(); $obj->talk; delete $INC{'./class.pm'}; _unload_subs('class'); #say Dumper \%DB::sub; my $dummy = <>; # we change class.pm meanwhile do './class.pm'; say $@ if $@; $obj = class->new(); $obj->talk; # results: # $ ./code.pl # 111513 # # panic: attempt to copy freed scalar 12dcbf0 to 1414870 at ./class.pm + line 3, <> line 1. # # Undefined subroutine &class::new called at ./code.pl line 38, <> lin +e 1. # Removing "use 5.014" from class.pm fixes the panic but is there a be +tter fix? # Also, why is this panic error happening?

Replies are listed 'Best First'.
Re: Reloading a module at run time
by tobyink (Canon) on Jan 16, 2013 at 09:45 UTC

    Do you have any good reason for avoiding using Module::Refresh itself? I don't have any experience with it, but the review on CPAN ratings seems positive, it has good results on CPAN testers, its authors include Jesse Vincent and Audrey Tang (both of whom have good reputations for putting out decent quality code), and it is used in Moose development, so all signs point to it being a good module.

    Why steal random chunks from it; why not just use it?

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
      Thanks. Using Module::Refresh directly fixed my issue.
      $ cat class.pm package class; use 5.014; use strict; use warnings; use autodie; sub new {bless {}, 'class'} sub talk {print "6111513\n"} 1; $ cat module_refresh_code.pl #!/usr/bin/env perl use strict; use warnings; use autodie; use 5.014; use Data::Dumper; use Module::Refresh; my $refresher = Module::Refresh->new; do './class.pm'; class->new->talk; my $dummy = <>; # we change class.pm meanwhile $refresher->refresh_module('./class.pm'); class->new->talk; $ ./module_refresh_code.pl 6111513 8111513