You are viewing the version of this documentation from Perl 5.8.5. View the latest version

CONTENTS

NAME

overload - Package for overloading perl operations

SYNOPSIS

    package SomeThing;

    use overload
	'+' => \&myadd,
	'-' => \&mysub;
	# etc
    ...

    package main;
    $a = new SomeThing 57;
    $b=5+$a;
    ...
    if (overload::Overloaded $b) {...}
    ...
    $strval = overload::StrVal $b;

DESCRIPTION

Declaration of overloaded functions

The compilation directive

    package Number;
    use overload
	"+" => \&add,
	"*=" => "muas";

declares function Number::add() for addition, and method muas() in the "class" Number (or one of its base classes) for the assignment form *= of multiplication.

Arguments of this directive come in (key, value) pairs. Legal values are values legal inside a &{ ... } call, so the name of a subroutine, a reference to a subroutine, or an anonymous subroutine will all work. Note that values specified as strings are interpreted as methods, not subroutines. Legal keys are listed below.

The subroutine add will be called to execute $a+$b if $a is a reference to an object blessed into the package Number, or if $a is not an object from a package with defined mathemagic addition, but $b is a reference to a Number. It can also be called in other situations, like $a+=7, or $a++. See "MAGIC AUTOGENERATION". (Mathemagical methods refer to methods triggered by an overloaded mathematical operator.)

Since overloading respects inheritance via the @ISA hierarchy, the above declaration would also trigger overloading of + and *= in all the packages which inherit from Number.

Calling Conventions for Binary Operations

The functions specified in the use overload ... directive are called with three (in one particular case with four, see "Last Resort") arguments. If the corresponding operation is binary, then the first two arguments are the two arguments of the operation. However, due to general object calling conventions, the first argument should always be an object in the package, so in the situation of 7+$a, the order of the arguments is interchanged. It probably does not matter when implementing the addition method, but whether the arguments are reversed is vital to the subtraction method. The method can query this information by examining the third argument, which can take three different values:

FALSE

the order of arguments is as in the current operation.

TRUE

the arguments are reversed.

undef

the current operation is an assignment variant (as in $a+=7), but the usual function is called instead. This additional information can be used to generate some optimizations. Compare "Calling Conventions for Mutators".

Calling Conventions for Unary Operations

Unary operation are considered binary operations with the second argument being undef. Thus the functions that overloads {"++"} is called with arguments ($a,undef,'') when $a++ is executed.