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

Read the comments in the below code.
sub AUTOLOAD { # Filter out package information. (my $name = $AUTOLOAD) =~ s/.*:://; if (exists $subs{$name}) { *$AUTOLOAD = sub {$subs{$name}}; # This wont work! why? eval "sub $AUTOLOAD {$subs{$name}}"; # this will... fatalError("A compile error occurred while compiling the subro +utine $AUTOLOAD: $@") if $@; } else { fatalError("The undefined subroutine $AUTOLOAD was called."); } delete $subs{$name}; goto &$AUTOLOAD; }

Edit kudra, 2002-05-27 s/pre/code/, new title

Replies are listed 'Best First'.
Re: autoload
by chromatic (Archbishop) on May 27, 2002 at 06:03 UTC
    Without knowing what's stored in %subs, my guess is that it's a string, and not a real code reference. Anonymous subroutines are compiled at compile time, but the contents of the hash aren't created until run time.

    For future reference, "This wont work" generally leads to wild speculation as to what actually goes wrong and to what you're trying to do. You may receive more help if you elaborate.

Re: autoload
by Juerd (Abbot) on May 27, 2002 at 07:19 UTC

    *$AUTOLOAD = sub {$subs{$name}}; # This wont work! why?
    goto &$AUTOLOAD;

    Your $subs{$name} itself is not executable code, the value contained in it is. That's why the eval works (the code is literally placed in there, whereas the first line only makes the sub return the value).

    Consider:

    %subs = ( foo => sub { print "Hello, world!\n"; } ); sub AUTOLOAD { ... *$AUTOLOAD = $subs{$name}; ... }
    And:
    %subs = ( foo => 'print "Hello, world!\n";' ); sub AUTOLOAD { ... *$AUTOLOAD = eval "sub { $subs{$name} }" ... }

    - Yes, I reinvent wheels.
    - Spam: Visit eurotraQ.
    

Re: autoload
by strat (Canon) on May 27, 2002 at 10:30 UTC
Re: autoload
by Anonymous Monk on May 27, 2002 at 05:57 UTC
    I think what you are looking for is
    *$AUTOLOAD = $subs{$name};