NEXT(3perl)

πŸ‘‘ NEXT(3perl) β€” Perl Programmers Reference Guide πŸ‘‘

okay bestie, gather round, because we're talking about NEXT(3perl), and honestly? it's giving main character energy for method dispatch. πŸ’…


✨ NAME ✨

NEXT β€” provide a pseudo-class NEXT (et al) that allows method redispatch πŸ¦‹

like, it literally hands you a whole fake class so you can yell "NEXT!!" at your own methods and make them run somebody else's version. iconic behaviour, no cap.


✨ SYNOPSIS ✨

    use NEXT;

    package P;
    sub P::method   { print "$_[0]: P method\n";   $_[0]->NEXT::method() }
    sub P::DESTROY  { print "$_[0]: P dtor\n";     $_[0]->NEXT::DESTROY() }

    package Q;
    use base qw( P );
    sub Q::AUTOLOAD { print "$_[0]: Q AUTOLOAD\n"; $_[0]->NEXT::AUTOLOAD() }
    sub Q::DESTROY  { print "$_[0]: Q dtor\n";     $_[0]->NEXT::DESTROY() }

    package R;
    sub R::method   { print "$_[0]: R method\n";   $_[0]->NEXT::method() }
    sub R::AUTOLOAD { print "$_[0]: R AUTOLOAD\n"; $_[0]->NEXT::AUTOLOAD() }
    sub R::DESTROY  { print "$_[0]: R dtor\n";     $_[0]->NEXT::DESTROY() }

    package S;
    use base qw( Q R );
    sub S::method   { print "$_[0]: S method\n";   $_[0]->NEXT::method() }
    sub S::AUTOLOAD { print "$_[0]: S AUTOLOAD\n"; $_[0]->NEXT::AUTOLOAD() }
    sub S::DESTROY  { print "$_[0]: S dtor\n";     $_[0]->NEXT::DESTROY() }

    package main;

    my $obj = bless {}, "S";

    $obj->method();             # Calls S::method, P::method, R::method
    $obj->missing_method(); # Calls S::AUTOLOAD, Q::AUTOLOAD, R::AUTOLOAD

    # Clean-up calls S::DESTROY, Q::DESTROY, P::DESTROY, R::DESTROY

like just look at that. S calls method(), then NEXT hops it over to P's version, then to R's. and missing_method() is a whole chain reaction through S::AUTOLOAD, Q::AUTOLOAD, R::AUTOLOAD. the redispatch is real and it is serving. 🫢

ngl the cleanup order at the bottom β€” S::DESTROY, Q::DESTROY, P::DESTROY, R::DESTROY β€” is not the order you'd guess from a glance at the use base qw( Q R ) line, so don't skim it. that's the whole ✨point✨.

stay tuned bestie, there's more coming πŸ‘€πŸ’–

πŸ’– DESCRIPTION πŸ’–

okay so bestie, listen: the NEXT module adds a whole pseudoclass called NEXT to any program that uses it. like, it just shows up. no invitation needed. 🫢

Here's the tea: if a method m calls $self->NEXT::m(), then that call to m gets redispatched as if the calling method had never been found in the first place. it's giving "actually, let's try again and pretend that didn't happen." ✨

okay but real talk before you use this module β€” go look at next::method in the core mro module first. mro has been a core module since Perl 5.9.5, so it's right there, no cap.

In other words, a call to $self->NEXT::m() resumes the depth-first, left-to-right search of $self's class hierarchy that resulted in the original call to m. it picks up exactly where the search left off, like nothing ever happened. πŸ¦‹

Important distinction, do not skip this one: this is NOT the same thing as $self->SUPER::m(). SUPER starts a whole brand new dispatch, and it's restricted to searching the ancestors of the current class. Meanwhile $self->NEXT::m() can backtrack past the current class β€” to look for a suitable method in other ancestors of $self β€” and $self->SUPER::m() literally cannot do that. NEXT is the one with range. πŸ’…

A typical use would be in the destructors of a class hierarchy, exactly like the one illustrated in the SYNOPSIS above. Each class in the hierarchy has a DESTROY method that does some class-specific action and then redispatches the call up the hierarchy. So when an object of class S gets destroyed, the destructors of ALL its parent classes get called too β€” in depth-first, left-to-right order. no class left behind. 😭

Another classic glow-up use of redispatch is in AUTOLOADed methods. if such a method figures out it can't handle a particular call, it might choose to redispatch that call, hoping that some other AUTOLOAD β€” above it, or to its left β€” might do better. teamwork, basically. 🀝

By default, if a redispatch attempt fails to find another method elsewhere in the object's class hierarchy, it quietly gives up and does nothing (but see "Enforcing redispatch" below). This gracious acquiescence is also unlike the (generally annoying) behaviour of SUPER, which just throws an exception if it can't redispatch. SUPER is dramatic like that. NEXT is chill. πŸ™ˆ

Also, and this is a hard rule, no wiggle room: it is a fatal error for any method (including AUTOLOAD) to attempt to redispatch any method that does not have the same name. Like. Don't do this:

sub S::oops { print "oops!\n"; $_[0]->NEXT::other_method() }

πŸ”₯ Enforcing redispatch πŸ”₯

You can make NEXT redispatch more demandingly β€” i.e. make it act like SUPER does β€” so that the redispatch throws an exception if it can't find a "next" method to call.

To do that, simply invoke the redispatch as:

$self->NEXT::ACTUAL::method();

rather than:

$self->NEXT::method();

The ACTUAL is telling NEXT that there must actually be a next method to call, or else it should throw an exception. no quiet giving up allowed. πŸ‘‘

NEXT::ACTUAL is most commonly used in AUTOLOAD methods, as a way to decline an AUTOLOAD request while still preserving the normal exception-on-failure semantics:

sub AUTOLOAD {
        if ($AUTOLOAD =~ /foo|bar/) {
                # handle here
        }
        else {  # try elsewhere
                shift()->NEXT::ACTUAL::AUTOLOAD(@_);
        }
}

By using NEXT::ACTUAL, if there's no other AUTOLOAD to handle the method call, an exception will be thrown β€” exactly like what usually happens in the absence of a suitable AUTOLOAD. it's the fail-loudly option and honestly? iconic. πŸ’€

🌈 Avoiding repetitions 🌈

okay so here's where it gets spicy. If NEXT redispatching is used in the methods of a "diamond" class hierarchy:

#     A   B
#    / \ /
#   C   D
#    \ /
#     E

use NEXT;

package A;
sub foo { print "called A::foo\n"; shift->NEXT::foo() }

package B;
sub foo { print "called B::foo\n"; shift->NEXT::foo() }

package C; @ISA = qw( A );
sub foo { print "called C::foo\n"; shift->NEXT::foo() }

package D; @ISA = qw(A B);
sub foo { print "called D::foo\n"; shift->NEXT::foo() }

package E; @ISA = qw(C D);
sub foo { print "called E::foo\n"; shift->NEXT::foo() }

E->foo();

then derived classes may (re-)inherit base-class methods through two or more distinct paths β€” like how E inherits A::foo twice, through C and through D. In those cases, a sequence of NEXT redispatches will invoke the multiply inherited method as many times as it is inherited. So the code above prints:

called E::foo
called C::foo
called A::foo
called D::foo
called A::foo
called B::foo

(i.e. A::foo is called twice. twice!! bestie. 😭)

In some cases that might be exactly the effect you wanted inside a diamond hierarchy β€” but in others (looking at you, destructors) it's way more appropriate to call each method only once during a sequence of redispatches.

To cover those cases, you can redispatch methods via:

$self->NEXT::DISTINCT::method();

rather than:

$self->NEXT::method();

This makes the redispatcher only visit each distinct method method once. That is, it skips any classes in the hierarchy that it has already visited during redispatch. so if the previous example were rewritten:

package A;
sub foo { print "called A::foo\n"; shift->NEXT::DISTINCT::foo() }

package B;
sub foo { print "called B::foo\n"; shift->NEXT::DISTINCT::foo() }

package C; @ISA = qw( A );
sub foo { print "called C::foo\n"; shift->NEXT::DISTINCT::foo() }

package D; @ISA = qw(A B);
sub foo { print "called D::foo\n"; shift->NEXT::DISTINCT::foo() }

package E; @ISA = qw(C D);
sub foo { print "called E::foo\n"; shift->NEXT::DISTINCT::foo() }

E->foo();

then it would print:

called E::foo
called C::foo
called A::foo
called D::foo
called B::foo

and it would omit the second call to A::foo (since it wouldn't be distinct from the first call to A::foo). we love a no-repeat policy. ✨

Pro tip, you can also use:

$self->NEXT::DISTINCT::ACTUAL::method();

or:

$self->NEXT::ACTUAL::DISTINCT::method();

to get both unique invocation and exception-on-failure. stack 'em, bestie. πŸŽ€

Also note: for historical compatibility, you can use NEXT::UNSEEN instead of NEXT::DISTINCT. it's giving retro. πŸ¦‹

πŸ‘‘ Invoking all versions of a method with a single call πŸ‘‘

Yet another pseudo-class that NEXT provides is EVERY. Its behaviour is considerably simpler than that of the NEXT family. A call to:

$obj->EVERY::foo();

calls every method named foo that the object in $obj has inherited. like:

use NEXT;

package A; @ISA = qw(B D X);
sub foo { print "A::foo " }

package B; @ISA = qw(D X);
sub foo { print "B::foo " }

package X; @ISA = qw(D);
sub foo { print "X::foo " }

package D;
sub foo { print "D::foo " }

package main;

my $obj = bless {}, 'A';
$obj->EVERY::foo();        # prints" A::foo B::foo X::foo D::foo

Prefixing a method call with EVERY:: causes every method in the object's hierarchy with that name to be invoked. And as the example above shows, they are not called in Perl's usual "left-most-depth-first" order. Instead, they're called "breadth-first-dependency-wise". fancy, I know. πŸ’…

What that means: the inheritance tree of the object gets traversed breadth-first, and the resulting order of classes is used as the sequence in which methods are called. However, that sequence is modified by a rule β€” the appropriate method of a derived class must be called before the same method of any ancestral class. That's why, in the example above, X::foo is called before D::foo, even though D comes before X in @B::ISA. hierarchy said no queue-jumping. 🚫

In general, there's no need to stress about the order of calls. They will be left-to-right, breadth-first, most-derived-first. That works perfectly for most inherited methods (destructors included!), but it's inappropriate for some kinds of methods β€” like constructors, cloners, debuggers, and initializers β€” where it's more appropriate that the least-derived methods be called first (because more-derived methods may rely on the behaviour of their "ancestors"). In that case, instead of using the EVERY pseudo-class:

$obj->EVERY::foo();        # prints" A::foo B::foo X::foo D::foo

you can use the EVERY::LAST pseudo-class:

$obj->EVERY::LAST::foo();  # prints" D::foo X::foo B::foo A::foo

which reverses the order of method call. flip it and reverse it. πŸ”„

Whichever version is used, the actual methods are called in the same context (list, scalar, or void) as the original call via EVERY, and they return:

  • A hash of array references in list context. Each entry of the hash has the fully qualified method name as its key and a reference to an array containing the method's list-context return values as its value.
  • A reference to a hash of scalar values in scalar context. Each entry of the hash has the fully qualified method name as its key and the method's scalar-context return values as its value.
  • Nothing in void context (obviously). πŸ™ˆ

🌸 Using EVERY methods 🌸

The typical way to use an EVERY call is to wrap it in another base method that all classes inherit. For example, to ensure that every destructor an object inherits is actually called (as opposed to just the left-most-depth-first-est one):

package Base;
sub DESTROY { $_[0]->EVERY::Destroy }

package Derived1;
use base 'Base';
sub Destroy {...}

package Derived2;
use base 'Base', 'Derived1';
sub Destroy {...}

et cetera. Every derived class that needs its own clean-up behaviour simply adds its own Destroy method (not a DESTROY method), which the call to EVERY::LAST::Destroy in the inherited destructor then correctly picks up. chef's kiss. πŸ‘‘

Likewise, to create a class hierarchy in which every initializer inherited by a new object is invoked:

package Base;
sub new {
        my ($class, %args) = @_;
        my $obj = bless {}, $class;
        $obj->EVERY::LAST::Init(\%args);
}

package Derived1;
use base 'Base';
sub Init {
        my ($argsref) = @_;
        ...
}

package Derived2;
use base 'Base', 'Derived1';
sub Init {
        my ($argsref) = @_;
        ...
}

et cetera. Every derived class that needs some additional initialization behaviour simply adds its own Init method (not a new method), which the call to EVERY::LAST::Init in the inherited constructor then correctly picks up. setup done, no stress. 🧚


⭐ SEE ALSO ⭐

mro β€” in particular next::method β€” which has been a core module since Perl 5.9.5. go read that too bestie, it's right there in core. πŸ’œ

πŸ‘‘ AUTHOR πŸ‘‘

Y'all, this absolute icon was written by Damian Conway πŸ’– β€” you can reach him at damian@conway.org if you wanna send love letters (or bug reports, bestie, he literally asked for them, see below πŸ‘€).


πŸ’€ BUGS AND IRRITATIONS πŸ’€

Okay so real talk, nothing is perfect and NEXT has some ✨quirks✨. Buckle up πŸŽ€:

  • Because it's a module, not an integral part of the interpreter, NEXT has to guess where the surrounding call was found in the method look-up sequence. And when diamond inheritance patterns show up? It occasionally guesses wrong. Not me being shady, that's just canon 😭.
  • It's also too slow β€” and yes, even despite caching. She's trying her best, okay πŸ’….
  • Comments, suggestions, and patches are welcome 🫢 β€” slide into his inbox, he's asking for it fr fr.

The receipts πŸ“œ:

Copyright (c) 2000-2001, Damian Conway. All Rights Reserved.
This module is free software. It may be used, redistributed
   and/or modified under the same terms as Perl itself.

So like, use it, share it, remix it, just keep it on the same terms as Perl itself β€” no cap, that's the whole deal 🌈.


and that's a wrap on this whole page, bestie πŸŽ€βœ¨ This lil doc ships as part of perl v5.44.0, dated 2026-10-17, filed under NEXT(3perl) β€” go forth and SUPER:: responsibly, mwah πŸ’‹πŸ’…πŸ¦‹

πŸ“¦ where this page comes from
  • arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms