Search code examples
perlhooksubroutine

How to lexically turn off Perl's AUTOLOAD subroutine?


I'm traped in legacy code which uses Perl's AUTOLOAD subroutine. Every unmapped/not defined subroutine will be handled by AUTOLOAD. Is it possible to disable the AUTOLOAD handling in a lexical environment?

This solution does not work:

# ENTER CODE HERE
{
  # Turn off AUTOLOAD for this block.
  local *AUTOLOAD;
  undef *AUTOLOAD;

  # ENTER CODE HERE
}
# ENTER CODE HERE

Solution

  • AUTOLOAD is specific to the package in question. So redefine the package method:

    #!/usr/bin/perl
    #
    
    {
        package autoloading;
    
        sub AUTOLOAD {
            print "YEAH ${AUTOLOAD}!\n";
        }
    
        sub new {
            return bless {}, $_[0];
        }
    }
    
    $obj = new autoloading();
    
    $obj->foo();
    
    *{autoloading::AUTOLOAD} = sub {};
    
    $obj->bar();
    

    Produces output:

    YEAH autoloading::foo!
    

    (no line for the $obj->bar() call)