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
fallback
is not set, or is explicitly set toundef
, the sequence of overloading events is unaffected: handlers are sought, autogeneration is attempted, and finally thenomethod
handler is invoked. If that fails, an exception is raised.- false
If
fallback
is set to a defined but false value (like0
), autogeneration is never attempted. Perl will call thenomethod ...
Get Programming Perl, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.