When an Overload Handler Is Missing (nomethod and fallback)
If you apply an unoverloaded operator to an object, Perl first tries to
autogenerate a behavior from other overloaded operators using the
rules described earlier. If that fails, Perl looks for an overloading
behavior for nomethod and uses that
if available. That handler is to operators what an AUTOLOAD subroutine is to subroutines: it’s
what you do when you can’t think of what else to do.
If used, the nomethod key
should be followed by a reference to a handler that
accepts four arguments (not three as all the other handlers expect).
The first three arguments are no different than in any other handler;
the fourth is a string corresponding to the operator whose handler is
missing. This serves the same purpose as the $AUTOLOAD variable does in AUTOLOAD subroutines.
If Perl has to look for a nomethod handler but can’t find one, an
exception is raised.
If you want to prevent autogeneration from occurring, or you
want a failed autogeneration attempt to result in no overloading at
all, you can define the special fallback overloading
key. It has three useful states:
-
undef If
fallbackis not set, or is explicitly set toundef, the sequence of overloading events is unaffected: handlers are sought, autogeneration is attempted, and finally thenomethodhandler is invoked. If that fails, an exception is raised.-
false If
fallbackis set to a defined but false value (like0), autogeneration is never attempted. Perl will call thenomethod ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access