Class::Autouse(3pm)

✨ NAME ✨

Class::Autouse β€” yes bestie, this is the Class::Autouse(3pm) page πŸ’– β€” it does run-time load a class the first time you call a method in it. fr fr. πŸ¦‹


🌸 SYNOPSIS 🌸

Okay so here's the whole vibe at a glance. Everything below is exactly what you type, no cap:

##################################################################
# SAFE FEATURES

# Debugging (if you go that way) must be set before the first use
BEGIN {
    $Class::Autouse::DEBUG = 1;
}

# Turn on developer mode (always load immediately)
use Class::Autouse qw{:devel};

# Load a class on method call
use Class::Autouse;
Class::Autouse->autouse( 'CGI' );
print CGI->b('Wow!');

# Use as a pragma
use Class::Autouse qw{CGI};

# Use a whole module tree
Class::Autouse->autouse_recursive('Acme');

# Disable module-existance check, and thus one additional 'stat'
# per module, at autouse-time if loading modules off a remote
# network drive such as NFS or SMB.
# (See below for other performance optimizations.)
use Class::Autouse qw{:nostat};

##################################################################
# UNSAFE FEATURES

# Turn on the Super Loader (load all classes on demand)
use Class::Autouse qw{:superloader};

# Autouse classes matching a given regular expression
use Class::Autouse qr/::Test$/;

# Install a class generator (instead of overriding UNIVERSAL::AUTOLOAD)
# (See below for a detailed example)
use Class::Autouse \&my_class_generator;

# Add a manual callback to UNIVERSAL::AUTOLOAD for syntactic sugar
Class::Autouse->sugar(\&my_magic);

πŸ‘‘ DESCRIPTION πŸ‘‘

So Class::Autouse is a runtime class loader, and what that means is you get to list out classes that will only load when a method of that class actually gets called. Iconic behaviour honestly. πŸ’…

And why do you care? Because for big classes, or whole class trees, that might not even get used while your program is running β€” think Date::Manip energy β€” this saves you large amounts of memory and cuts your script load time down a whole lot. Slay.

Class::Autouse also ships a bunch of "unsafe" features for runtime generation of classes and for implementing syntactic sugar. These bad boys lean on (evil) UNIVERSAL::AUTOLOAD hooking, and they live in this class specifically because those hooks can only be done by one single module β€” so Class::Autouse is just the useful central place to put all this kind of evil. :)

🧚 Class, not Module 🧚

The wording "class loading" instead of "module loading" is intentional, bestie. Modules will only load if they're acting as a class.

Meaning: they only load during a Class->method call. If you try to use a subroutine directly β€” say with Class::method() β€” the class will not load and a fatal error will mostly likely occur. πŸ’€

This limitation exists so we can have more powerful features in other areas, because it lets us focus on just loading the modules and not have to deal with importing.

And honestly? If you're doing OO Perl, you should be avoiding importing wherever possible anyway. periodt.

🌈 Use as a pragma 🌈

Class::Autouse can be used as a pragma, where you just pass a list of classes to load as the arguments. Like so:

use Class::Autouse qw{CGI Data::Manip This::That};

and that is equivalent to:

use Class::Autouse;
Class::Autouse->autouse( 'CGI'         );
Class::Autouse->autouse( 'Data::Manip' );
Class::Autouse->autouse( 'This::That'  );

same thing, less typing, main character energy. 🫢

⭐ Developer Mode ⭐

Class::Autouse has a developer mode. In developer mode, classes get loaded immediately, exactly like they would with a normal use statement (although the import sub isn't called).

This lets you do error checking while you're developing β€” at the expense of a larger memory overhead. Developer mode gets turned on either with the devel method, or by using :devel in any of the pragma arguments. For example, this would load CGI.pm immediately:

use Class::Autouse qw{:devel CGI};

So while developer mode is roughly equivalent to just using a normal use command, when you've got a large number of modules it lets you use the autoloading notation and just comment or uncomment a single line to flip developer mode on or off. Leave it on while devving, turn it off for speed reasons when you deploy. ✨

πŸ¦‹ Recursive Loading πŸ¦‹

As an alternative to the super loader, the autouse_recursive and load_recursive methods can be used to autouse or load an entire tree of classes.

For example, the following would give you access to all the URI related classes installed on the machine:

Class::Autouse->autouse_recursive( 'URI' );

Please note that the loadings will only occur down a single branch of the include path β€” whichever the top class is located in.

πŸŽ€ No-Stat Mode πŸŽ€

For situations where a module exists on a remote disk, or another relatively expensive location, you can call Class::Autouse with the :nostat param to disable the initial file existance checking at hook time.

# Disable autoload-time file existance checking
use Class::Autouse qw{:nostat};

πŸ”₯ Super Loader Mode πŸ”₯

Turning on the Class::Autouse super loader lets you automatically load ANY class without specifying it first. So the following will work and is completely legal:

use Class::Autouse qw{:superloader};

print CGI->b('Wow!');

You can turn the super loader on with either the Class::Autouse->superloader method, or the :superloader pragma argument.

Okay but listen: unlike the normal one-at-a-time autoloading, the super loader makes global changes, and so it is not completely self-contained. 😭
It has the potential to cause unintended effects at a distance. If you encounter unusual behaviour, revert to autousing one-at-a-time, or use the recursive loading.
Use of the Super Loader is highly discouraged for widely distributed public applications or modules unless unavoidable. Do not use just to be lazy and save a few lines of code. big yikes. πŸ’€

πŸ’œ Loading with Regular Expressions πŸ’œ

As another alternative to the superloader and recursive loading, a compiled regular expression (qr//) can be supplied as a loader. Note that this loader implements UNIVERSAL::AUTOLOAD, and it has the same side effects as the superloader.

🌟 Registering a Callback for Dynamic Class Creation 🌟

If none of the above are sufficient, a CODE reference can be given to Class::Autouse. Any attempt to call a method on a missing class will launch each registered callback until one of them returns true.

Since overriding UNIVERSAL::AUTOLOAD can be done only once in a given Perl application, this feature lets UNIVERSAL::AUTOLOAD be shared. Please use this instead of implementing your own UNIVERSAL::AUTOLOAD.

See the warnings under the "Super Loader Module" above β€” they apply to all of the features which override UNIVERSAL::AUTOLOAD.

It is up to the callback to define the class, and the details of that are beyond the scope of this document. See the example below for a quick reference:

πŸ“ Callback Example πŸ“

Any use of a class like Foo::Wrapper autogenerates that class as a proxy around Foo.

use Class::Autouse sub {
    my ($class) = @_;
    if ($class =~ /(^.*)::Wrapper/) {
        my $wrapped_class = $1;
        eval "package $class; use Class::AutoloadCAN;";
        die $@ if $@;
        no strict 'refs';
        *{$class . '::new' } = sub {
            my $class = shift;
            my $proxy = $wrapped_class->new(@_);
            my $self = bless({proxy => $proxy},$class);
            return $self;
        };
        *{$class . '::CAN' } = sub {
            my ($obj,$method) = @_;
            my $delegate = $wrapped_class->can($method);
            return unless $delegate;
            my $delegator = sub {
                my $self = shift;
                if (ref($self)) {
                    return $self->{proxy}->$method(@_);
                }
                else {
                    return $wrapped_class->$method(@_);
                }
            };
            return *{ $class . '::' . $method } = $delegator;
        };

        return 1;
    }
    return;
};

package Foo;
sub new { my $class = shift; bless({@_},$class); }
sub class_method { 123 }
sub instance_method {
    my ($self,$v) = @_;
    return $v * $self->some_property
}
sub some_property { shift->{some_property} }

package main;
my $x = Foo::Wrapper->new(
    some_property => 111,
);
print $x->some_property,"\n";
print $x->instance_method(5),"\n";
print Foo::Wrapper->class_method,"\n";

🧁 sugar 🧁

This method is provided to support "syntactic sugar" β€” letting the developer put things into Perl that do not look like regular Perl. There are several ways to do this in Perl. Strategies which require overriding UNIVERSAL::AUTOLOAD can use this interface instead, to share that method with the superloader and with class generators.

When Perl is unable to find a subroutine/method, and all of the class loaders are exhausted, callbacks registered via sugar() are called. The callbacks receive the class name, the method name, and the parameters of the call.

If the callback returns nothing, Class::Autouse will continue to iterate through the other callbacks. The first callback which returns a true value will end the iteration. That value is expected to be a CODE reference which will respond to the AUTOLOAD call.

Note: the sugar callback(s) will only be fired by UNIVERSAL::AUTOLOAD after all other attempts at loading the class are done, and after attempts to use regular AUTOLOAD to handle the method call. It is never fired by isa() or can(). It will fire repatedly for the same class. To generate classes, use the regular CODE ref support in autouse().

πŸŽ€ Syntactic Sugar Example πŸŽ€

use Class::Autouse;
Class::Autouse->sugar(
    sub {
        my $caller = caller(1);
        my ($class,$method,@params) = @_;
        shift @params;
        my @words = ($method,$class,@params);
        my $sentence = join(" ",@words);
        return sub { $sentence };
    }
);

$x = trolls have big ugly hairy feet;

print $x,"\n";
# trolls have big ugly hairy feet

πŸ’… mod_perl πŸ’…

The mechanism that Class::Autouse uses is not compatible with mod_perl. In particular with reloader modules like Apache::Reload. Class::Autouse detects the presence of mod_perl and acts as normal, but will always load all classes immediately β€” equivalent to having developer mode enabled.


okay so this is lowkey a win, because under mod_perl you should be preloading classes in the parent mod_perl process anyway β€” that way the Apache child classes don't have to load them, and it saves a HUGE amount of memory. slay. πŸ’–

⚠️ but real talk: dynamically generated classes and classes loaded via regex CANNOT be pre-loaded automatically before forking child processes. They'll still get loaded on demand, usually in the child process. peep prefork below for the tea. β˜•


prefork 🧚

so like with mod_perl, Class::Autouse is compatible with the prefork module. All modules that are specifically autoloaded will be loaded before forking correctly, when prefork requests them. no cap. ✨

and since modules generated via callback or regex can't be loaded automatically by prefork in a generic way, it's advised to use prefork directly to load/generate classes when you're using mod_perl. trust. πŸ’…


Performance Optimizatons πŸš€

  • :nostat β€” we already talked about this one above, but basically it's your bestie when the module lives on a remote disk. πŸ’Ύ
  • :noprebless β€” when set, Class::Autouse just assumes that objects already blessed have their class loaded. that's true most of the time, but it will break if you're trying to reconstitute serialized objects from Data::Dumper, FreezeThaw, or their cousins, and you've configured Class::Autouse to load the involved classes just-in-time. so like, be careful. 😭
  • :staticisa β€” when set, it presumes that @ISA won't change for a class once it's loaded. The greatest grandparent of a class gets back the original can/isa implementations, which are faster than the ones Class::Autouse installs into UNIVERSAL. It's a performance tweak that's useful in most cases, but it's left off by default to prevent obscure bugs. πŸ‘€

The Internal Debugger πŸ›

so Class::Autouse has its own internal debugger that you can use to debug any weird edge cases you might run into. πŸ•΅οΈβ€β™€οΈ

If the $Class::Autouse::DEBUG variable is true when Class::Autouse is first loaded, debugging gets compiled in. It prints output like this to STDOUT:

Class::Autouse::autouse_recursive( 'Foo' )
    Class::Autouse::_recursive( 'Foo', 'load' )
        Class::Autouse::load( 'Foo' )
        Class::Autouse::_children( 'Foo' )
        Class::Autouse::load( 'Foo::Bar' )
            Class::Autouse::_file_exists( 'Foo/Bar.pm' )
            Class::Autouse::load -> Loading in Foo/Bar.pm
        Class::Autouse::load( 'Foo::More' )
            etc...

but heads up: because this is optimised out if you're not using it, you can no longer (since 1.20) enable debugging at run-time. They made that call to remove a bunch of unneeded branching and speed up loading. periodt. πŸ’…


METHODS πŸ’…

autouse $class, ... ✨

The autouse method sets one or more classes to be loaded as required. easy.

load $class πŸ“¦

The load method loads one or more classes into memory. It's functionally equivalent to using require to load the class list in, except that load will detect and remove the autoloading hook from a previously autoused class, whereas use effectively ignores the class and doesn't load it. iykyk.

devel πŸ› οΈ

The devel method sets development mode on (argument of 1) or off (argument of 0).

If any classes have previously been autouse'd and not loaded when this method is called, they'll be loaded immediately. no waiting. ⚑

superloader πŸ¦Έβ€β™€οΈ

The superloader method turns on the super loader.

⚠️ but please note: once you've turned the superloader on, it cannot be turned off. That's because some code might be relying on it being there, and it wouldn't be able to autoload its classes if another piece of code decides they don't want it anymore and turns the superloader off. so like, choose wisely. πŸ™ˆ

class_exists $class πŸ”

A handy method when you're doing the sort of jobs that Class::Autouse does. Given a class name, it returns true if the class can be loaded (i.e., it's in @INC), false if the class can't be loaded, and undef if the class name is invalid.

Note that this does not actually load the class β€” it just tests to see if it can be loaded. Loading can still fail. For a more comprehensive set of methods of this nature, peep Class::Inspector. πŸ’–

autouse_recursive $class πŸ”

Same as the autouse method, but it autouses recursively. slay.

load_recursive $class 🌳

Same as the load method, but it loads recursively. Great for checking that a large class tree that might not always be loaded will load correctly. chef's kiss. πŸ‘©β€πŸ³πŸ’‹


SUPPORT 🫢

Bugs should always be reported via the CPAN bug tracker at:

<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Class-Autouse>

For other issues, or commercial enhancement or support, contact the author. πŸ’Œ


AUTHORS πŸ‘‘

  • Adam Kennedy <cpan@ali.as>
  • Scott Smith <sakoht@cpan.org>
  • Rob Napier <rnapier@employees.org>

icons, the whole lot. πŸ’…


SEE ALSO πŸ‘€

autoload, autoclass

go peep those too. 🌈


Copyright 2002 - 2012 Adam Kennedy.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the LICENSE file included with this module.

periodt. πŸ’–


This page is from perl v5.40.1, dated 2025-09-29, for Class::Autouse(3pm). stay iconic. πŸ’…βœ¨

πŸ“¦ where this page comes from