Have you ever wanted to redefine a subroutine while your program is running? It's possible -- and not involving closures or other manipulations. Here's a little demonstration.

Note a few things:

Note that this can be a security risk, but it may come in handy someday.
#!/usr/bin/perl -w use strict; sub my_sub { print "This is the first subroutine called my_sub\n"; } my $soft_sub = 'sub { print "This is the redefined subroutine.\\n"; };'; my $my_sub = "The scalar with the same name.\n"; my $sub_ref; eval "\$sub_ref = $soft_sub"; my_sub(); print "$my_sub\n"; undef &{ *my_sub{CODE} }; *my_sub = $sub_ref; my_sub(); print $my_sub;

Replies are listed 'Best First'.
RE: Replacing a Subroutine at Runtime
by RichardH (Sexton) on Mar 25, 2000 at 00:38 UTC
    Very intersting. Please excuse this question if it reveals my ignorance, but what does the following line mean? undef &{ *my_sub{CODE} };
      It undefines the subroutine that was previously defined as my_sub. It does so by getting the CODE ref part of the "my_sub" typeglob, then undefining the subroutine that that code ref references.

      Since the goal of this is to replace that subroutine, this prevents the warning you would otherwise get (when you have warnings enabled) that "subroutine SUB has been redefined".