1. Perl
  2. Syntax
  3. autoload

AUTOLOAD - Subroutine autoload

Perl allows you to define a subroutine called AUTOLOAD that will be called if the subroutine does not exist. This is called subroutine autoloading.

package MyModule;

aaaaiiiii (1, 2);

our $AUTOLOAD;
sub AUTOLOAD {
  # ...
}

If you define our $AUROLOAD, you can get the name of the called function.

What is autoload used for?

When programming in everyday work, there is little need to use autoloading. Also, there is no reason to actively use autoload when creating modules.

Calling autoloads is very slow and alternatives are often available.

If you want to create an accessor, you can dynamically generate it with eval or subroutine reference < Substituting/a> for typeglobs is also better in terms of performance.

Perl has the only feature that can only be achieved with autoloading. That is to give the method to the object. I don't usually use it, but if you want to achieve this functionality in a framework, it's the only way to do it.

Example program

This is an example of subroutine autoloading.

use strict;
use warnings;

# AUTOLOAD subroutine
# ・ If defined, it will be called when the name of the subroutine cannot be found.

print "1: AUTOLOAD calls a non-existent function\n";

# When you call a function that is not defined anywhere.
aaaaiiiii (1, 2);

# This is called.
sub AUTOLOAD {

  # If you define $AUROLOAD, you can get the name of the called function.
  our $AUTOLOAD;

  # You can receive the function name and arguments.
  my (@arg) = @_;
  print "AUTOLOAD has been called.\n";
  print "The function you tried to call is $AUTOLOAD.\n";
  print "The argument is" .join(',', @arg). ".\n";
}

Related Informatrion