{
    "mode": "perldoc",
    "parameter": "overload",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/overload/json",
    "generated": "2026-06-12T06:47:05Z",
    "synopsis": "package SomeThing;\nuse overload\n'+' => \\&myadd,\n'-' => \\&mysub;\n# etc\n...\npackage main;\n$a = SomeThing->new( 57 );\n$b = 5 + $a;\n...\nif (overload::Overloaded $b) {...}\n...\n$strval = overload::StrVal $b;",
    "sections": {
        "NAME": {
            "content": "overload - Package for overloading Perl operations\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "package SomeThing;\n\nuse overload\n'+' => \\&myadd,\n'-' => \\&mysub;\n# etc\n...\n\npackage main;\n$a = SomeThing->new( 57 );\n$b = 5 + $a;\n...\nif (overload::Overloaded $b) {...}\n...\n$strval = overload::StrVal $b;\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This pragma allows overloading of Perl's operators for a class. To overload built-in functions,\nsee \"Overriding Built-in Functions\" in perlsub instead.\n",
            "subsections": [
                {
                    "name": "Fundamentals",
                    "content": "Declaration\nArguments of the \"use overload\" directive are (key, value) pairs. For the full set of legal\nkeys, see \"Overloadable Operations\" below.\n\nOperator implementations (the values) can be subroutines, references to subroutines, or\nanonymous subroutines - in other words, anything legal inside a \"&{ ... }\" call. Values\nspecified as strings are interpreted as method names. Thus\n\npackage Number;\nuse overload\n\"-\" => \"minus\",\n\"*=\" => \\&muas,\n'\"\"' => sub { ...; };\n\ndeclares that subtraction is to be implemented by method \"minus()\" in the class \"Number\" (or one\nof its base classes), and that the function \"Number::muas()\" is to be used for the assignment\nform of multiplication, \"*=\". It also defines an anonymous subroutine to implement\nstringification: this is called whenever an object blessed into the package \"Number\" is used in\na string context (this subroutine might, for example, return the number as a Roman numeral).\n\nCalling Conventions and Magic Autogeneration\nThe following sample implementation of \"minus()\" (which assumes that \"Number\" objects are simply\nblessed references to scalars) illustrates the calling conventions:\n\npackage Number;\nsub minus {\nmy ($self, $other, $swap) = @;\nmy $result = $$self - $other;         # *\n$result = -$result if $swap;\nref $result ? $result : bless \\$result;\n}\n# * may recurse once - see table below\n\nThree arguments are passed to all subroutines specified in the \"use overload\" directive (with\nexceptions - see below, particularly \"nomethod\").\n\nThe first of these is the operand providing the overloaded operator implementation - in this\ncase, the object whose \"minus()\" method is being called.\n\nThe second argument is the other operand, or \"undef\" in the case of a unary operator.\n\nThe third argument is set to TRUE if (and only if) the two operands have been swapped. Perl may\ndo this to ensure that the first argument ($self) is an object implementing the overloaded\noperation, in line with general object calling conventions. For example, if $x and $y are\n\"Number\"s:\n\noperation   |   generates a call to\n============|======================\n$x - $y     |   minus($x, $y, '')\n$x - 7      |   minus($x, 7, '')\n7 - $x      |   minus($x, 7, 1)\n\nPerl may also use \"minus()\" to implement other operators which have not been specified in the\n\"use overload\" directive, according to the rules for \"Magic Autogeneration\" described later. For\nexample, the \"use overload\" above declared no subroutine for any of the operators \"--\", \"neg\"\n(the overload key for unary minus), or \"-=\". Thus\n\noperation   |   generates a call to\n============|======================\n-$x         |   minus($x, 0, 1)\n$x--        |   minus($x, 1, undef)\n$x -= 3     |   minus($x, 3, undef)\n\nNote the \"undef\"s: where autogeneration results in the method for a standard operator which does\nnot change either of its operands, such as \"-\", being used to implement an operator which\nchanges the operand (\"mutators\": here, \"--\" and \"-=\"), Perl passes undef as the third argument.\nThis still evaluates as FALSE, consistent with the fact that the operands have not been swapped,\nbut gives the subroutine a chance to alter its behaviour in these cases.\n\nIn all the above examples, \"minus()\" is required only to return the result of the subtraction:\nPerl takes care of the assignment to $x. In fact, such methods should *not* modify their\noperands, even if \"undef\" is passed as the third argument (see \"Overloadable Operations\").\n\nThe same is not true of implementations of \"++\" and \"--\": these are expected to modify their\noperand. An appropriate implementation of \"--\" might look like\n\nuse overload '--' => \"decr\",\n# ...\nsub decr { --${$[0]}; }\n\nIf the \"bitwise\" feature is enabled (see feature), a fifth TRUE argument is passed to\nsubroutines handling \"&\", \"|\", \"^\" and \"~\". This indicates that the caller is expecting numeric\nbehaviour. The fourth argument will be \"undef\", as that position ($[3]) is reserved for use by\n\"nomethod\".\n\nMathemagic, Mutators, and Copy Constructors\nThe term 'mathemagic' describes the overloaded implementation of mathematical operators.\nMathemagical operations raise an issue. Consider the code:\n\n$a = $b;\n--$a;\n\nIf $a and $b are scalars then after these statements\n\n$a == $b - 1\n\nAn object, however, is a reference to blessed data, so if $a and $b are objects then the\nassignment \"$a = $b\" copies only the reference, leaving $a and $b referring to the same object\ndata. One might therefore expect the operation \"--$a\" to decrement $b as well as $a. However,\nthis would not be consistent with how we expect the mathematical operators to work.\n\nPerl resolves this dilemma by transparently calling a copy constructor before calling a method\ndefined to implement a mutator (\"--\", \"+=\", and so on.). In the above example, when Perl reaches\nthe decrement statement, it makes a copy of the object data in $a and assigns to $a a reference\nto the copied data. Only then does it call \"decr()\", which alters the copied data, leaving $b\nunchanged. Thus the object metaphor is preserved as far as possible, while mathemagical\noperations still work according to the arithmetic metaphor.\n\nNote: the preceding paragraph describes what happens when Perl autogenerates the copy\nconstructor for an object based on a scalar. For other cases, see \"Copy Constructor\".\n"
                },
                {
                    "name": "Overloadable Operations",
                    "content": "The complete list of keys that can be specified in the \"use overload\" directive are given,\nseparated by spaces, in the values of the hash %overload::ops:\n\nwithassign      => '+ - * / %  << >> x .',\nassign           => '+= -= *= /= %= = <<= >>= x= .=',\nnumcomparison   => '< <= > >= == !=',\n'3waycomparison'=> '<=> cmp',\nstrcomparison   => 'lt le gt ge eq ne',\nbinary           => '& &= | |= ^ ^= &. &.= |. |.= ^. ^.=',\nunary            => 'neg ! ~ ~.',\nmutators         => '++ --',\nfunc             => 'atan2 cos sin exp abs log sqrt int',\nconversion       => 'bool \"\" 0+ qr',\niterators        => '<>',\nfiletest         => '-X',\ndereferencing    => '${} @{} %{} &{} *{}',\nmatching         => '~~',\nspecial          => 'nomethod fallback ='\n\nMost of the overloadable operators map one-to-one to these keys. Exceptions, including\nadditional overloadable operations not apparent from this hash, are included in the notes which\nfollow. This list is subject to growth over time.\n\nA warning is issued if an attempt is made to register an operator not found above.\n\n*    \"not\"\n\nThe operator \"not\" is not a valid key for \"use overload\". However, if the operator \"!\" is\noverloaded then the same implementation will be used for \"not\" (since the two operators\ndiffer only in precedence).\n\n*    \"neg\"\n\nThe key \"neg\" is used for unary minus to disambiguate it from binary \"-\".\n\n*    \"++\", \"--\"\n\nAssuming they are to behave analogously to Perl's \"++\" and \"--\", overloaded implementations\nof these operators are required to mutate their operands.\n\nNo distinction is made between prefix and postfix forms of the increment and decrement\noperators: these differ only in the point at which Perl calls the associated subroutine\nwhen evaluating an expression.\n\n*    *Assignments*\n\n+=  -=  *=  /=  %=  =  <<=  >>=  x=  .=\n&=  |=  ^=  &.=  |.=  ^.=\n\nSimple assignment is not overloadable (the '=' key is used for the \"Copy Constructor\").\nPerl does have a way to make assignments to an object do whatever you want, but this\ninvolves using tie(), not overload - see \"tie\" in perlfunc and the \"COOKBOOK\" examples\nbelow.\n\nThe subroutine for the assignment variant of an operator is required only to return the\nresult of the operation. It is permitted to change the value of its operand (this is safe\nbecause Perl calls the copy constructor first), but this is optional since Perl assigns the\nreturned value to the left-hand operand anyway.\n\nAn object that overloads an assignment operator does so only in respect of assignments to\nthat object. In other words, Perl never calls the corresponding methods with the third\nargument (the \"swap\" argument) set to TRUE. For example, the operation\n\n$a *= $b\n\ncannot lead to $b's implementation of \"*=\" being called, even if $a is a scalar. (It can,\nhowever, generate a call to $b's method for \"*\").\n\n*    *Non-mutators with a mutator variant*\n\n+  -  *  /  %    <<  >>  x  .\n&  |  ^  &.  |.  ^.\n\nAs described above, Perl may call methods for operators like \"+\" and \"&\" in the course of\nimplementing missing operations like \"++\", \"+=\", and \"&=\". While these methods may detect\nthis usage by testing the definedness of the third argument, they should in all cases avoid\nchanging their operands. This is because Perl does not call the copy constructor before\ninvoking these methods.\n\n*    \"int\"\n\nTraditionally, the Perl function \"int\" rounds to 0 (see \"int\" in perlfunc), and so for\nfloating-point-like types one should follow the same semantic.\n\n*    *String, numeric, boolean, and regexp conversions*\n\n\"\"  0+  bool\n\nThese conversions are invoked according to context as necessary. For example, the\nsubroutine for '\"\"' (stringify) may be used where the overloaded object is passed as an\nargument to \"print\", and that for 'bool' where it is tested in the condition of a flow\ncontrol statement (like \"while\") or the ternary \"?:\" operation.\n\nOf course, in contexts like, for example, \"$obj + 1\", Perl will invoke $obj's\nimplementation of \"+\" rather than (in this example) converting $obj to a number using the\nnumify method '0+' (an exception to this is when no method has been provided for '+' and\n\"fallback\" is set to TRUE).\n\nThe subroutines for '\"\"', '0+', and 'bool' can return any arbitrary Perl value. If the\ncorresponding operation for this value is overloaded too, the operation will be called\nagain with this value.\n\nAs a special case if the overload returns the object itself then it will be used directly.\nAn overloaded conversion returning the object is probably a bug, because you're likely to\nget something that looks like \"YourPackage=HASH(0x8172b34)\".\n\nqr\n\nThe subroutine for 'qr' is used wherever the object is interpolated into or used as a\nregexp, including when it appears on the RHS of a \"=~\" or \"!~\" operator.\n\n\"qr\" must return a compiled regexp, or a ref to a compiled regexp (such as \"qr//\" returns),\nand any further overloading on the return value will be ignored.\n\n*    *Iteration*\n\nIf \"<>\" is overloaded then the same implementation is used for both the *read-filehandle*\nsyntax \"<$var>\" and *globbing* syntax \"<${var}>\".\n\n*    *File tests*\n\nThe key '-X' is used to specify a subroutine to handle all the filetest operators (\"-f\",\n\"-x\", and so on: see \"-X\" in perlfunc for the full list); it is not possible to overload\nany filetest operator individually. To distinguish them, the letter following the '-' is\npassed as the second argument (that is, in the slot that for binary operators is used to\npass the second operand).\n\nCalling an overloaded filetest operator does not affect the stat value associated with the\nspecial filehandle \"\". It still refers to the result of the last \"stat\", \"lstat\" or\nunoverloaded filetest.\n\nThis overload was introduced in Perl 5.12.\n\n*    *Matching*\n\nThe key \"~~\" allows you to override the smart matching logic used by the \"~~\" operator and\nthe switch construct (\"given\"/\"when\"). See \"Switch Statements\" in perlsyn and feature.\n\nUnusually, the overloaded implementation of the smart match operator does not get full\ncontrol of the smart match behaviour. In particular, in the following code:\n\npackage Foo;\nuse overload '~~' => 'match';\n\nmy $obj =  Foo->new();\n$obj ~~ [ 1,2,3 ];\n\nthe smart match does *not* invoke the method call like this:\n\n$obj->match([1,2,3],0);\n\nrather, the smart match distributive rule takes precedence, so $obj is smart matched\nagainst each array element in turn until a match is found, so you may see between one and\nthree of these calls instead:\n\n$obj->match(1,0);\n$obj->match(2,0);\n$obj->match(3,0);\n\nConsult the match table in \"Smartmatch Operator\" in perlop for details of when overloading\nis invoked.\n\n*    *Dereferencing*\n\n${}  @{}  %{}  &{}  *{}\n\nIf these operators are not explicitly overloaded then they work in the normal way, yielding\nthe underlying scalar, array, or whatever stores the object data (or the appropriate error\nmessage if the dereference operator doesn't match it). Defining a catch-all 'nomethod' (see\nbelow) makes no difference to this as the catch-all function will not be called to\nimplement a missing dereference operator.\n\nIf a dereference operator is overloaded then it must return a *reference* of the\nappropriate type (for example, the subroutine for key '${}' should return a reference to a\nscalar, not a scalar), or another object which overloads the operator: that is, the\nsubroutine only determines what is dereferenced and the actual dereferencing is left to\nPerl. As a special case, if the subroutine returns the object itself then it will not be\ncalled again - avoiding infinite recursion.\n\n*    *Special*\n\nnomethod  fallback  =\n\nSee \"Special Keys for \"use overload\"\".\n"
                },
                {
                    "name": "Magic Autogeneration",
                    "content": "If a method for an operation is not found then Perl tries to autogenerate a substitute\nimplementation from the operations that have been defined.\n\nNote: the behaviour described in this section can be disabled by setting \"fallback\" to FALSE\n(see \"fallback\").\n\nIn the following tables, numbers indicate priority. For example, the table below states that, if\nno implementation for '!' has been defined then Perl will implement it using 'bool' (that is, by\ninverting the value returned by the method for 'bool'); if boolean conversion is also\nunimplemented then Perl will use '0+' or, failing that, '\"\"'.\n\noperator | can be autogenerated from\n|\n| 0+   \"\"   bool   .   x\n=========|==========================\n0+    |       1     2\n\"\"    |  1          2\nbool  |  1    2\nint   |  1    2     3\n!     |  2    3     1\nqr    |  2    1     3\n.     |  2    1     3\nx     |  2    1     3\n.=    |  3    2     4    1\nx=    |  3    2     4        1\n<>    |  2    1     3\n-X    |  2    1     3\n\nNote: The iterator ('<>') and file test ('-X') operators work as normal: if the operand is not a\nblessed glob or IO reference then it is converted to a string (using the method for '\"\"', '0+',\nor 'bool') to be interpreted as a glob or filename.\n\noperator | can be autogenerated from\n|\n|  <   <=>   neg   -=    -\n=========|==========================\nneg   |                        1\n-=    |                        1\n--    |                   1    2\nabs   | a1    a2    b1        b2    [*]\n<     |        1\n<=    |        1\n>     |        1\n>=    |        1\n==    |        1\n!=    |        1\n\n* one from [a1, a2] and one from [b1, b2]\n\nJust as numeric comparisons can be autogenerated from the method for '<=>', string comparisons\ncan be autogenerated from that for 'cmp':\n\noperators          |  can be autogenerated from\n====================|===========================\nlt gt le ge eq ne  |  cmp\n\nSimilarly, autogeneration for keys '+=' and '++' is analogous to '-=' and '--' above:\n\noperator | can be autogenerated from\n|\n|  +=    +\n=========|==========================\n+=   |        1\n++   |   1    2\n\nAnd other assignment variations are analogous to '+=' and '-=' (and similar to '.=' and 'x='\nabove):\n\noperator ||  *= /= %= = <<= >>= &= ^= |= &.= ^.= |.=\n-------------------||-------------------------------------------\nautogenerated from ||  *  /  %    <<  >>  &  ^  |  &.  ^.  |.\n\nNote also that the copy constructor (key '=') may be autogenerated, but only for objects based\non scalars. See \"Copy Constructor\".\n\nMinimal Set of Overloaded Operations\nSince some operations can be automatically generated from others, there is a minimal set of\noperations that need to be overloaded in order to have the complete set of overloaded operations\nat one's disposal. Of course, the autogenerated operations may not do exactly what the user\nexpects. The minimal set is:\n\n+ - * / %  << >> x\n<=> cmp\n& | ^ ~ &. |. ^. ~.\natan2 cos sin exp log sqrt int\n\"\" 0+ bool\n~~\n\nOf the conversions, only one of string, boolean or numeric is needed because each can be\ngenerated from either of the other two.\n\nSpecial Keys for \"use overload\"\n\"nomethod\"\nThe 'nomethod' key is used to specify a catch-all function to be called for any operator that is\nnot individually overloaded. The specified function will be passed four parameters. The first\nthree arguments coincide with those that would have been passed to the corresponding method if\nit had been defined. The fourth argument is the \"use overload\" key for that missing method. If\nthe \"bitwise\" feature is enabled (see feature), a fifth TRUE argument is passed to subroutines\nhandling \"&\", \"|\", \"^\" and \"~\" to indicate that the caller is expecting numeric behaviour.\n\nFor example, if $a is an object blessed into a package declaring\n\nuse overload 'nomethod' => 'catchall', # ...\n\nthen the operation\n\n3 + $a\n\ncould (unless a method is specifically declared for the key '+') result in a call\n\ncatchall($a, 3, 1, '+')\n\nSee \"How Perl Chooses an Operator Implementation\".\n\n\"fallback\"\nThe value assigned to the key 'fallback' tells Perl how hard it should try to find an\nalternative way to implement a missing operator.\n\n*   defined, but FALSE\n\nuse overload \"fallback\" => 0, # ... ;\n\nThis disables \"Magic Autogeneration\".\n\n*   \"undef\"\n\nIn the default case where no value is explicitly assigned to \"fallback\", magic\nautogeneration is enabled.\n\n*   TRUE\n\nThe same as for \"undef\", but if a missing operator cannot be autogenerated then, instead of\nissuing an error message, Perl is allowed to revert to what it would have done for that\noperator if there had been no \"use overload\" directive.\n\nNote: in most cases, particularly the \"Copy Constructor\", this is unlikely to be appropriate\nbehaviour.\n\nSee \"How Perl Chooses an Operator Implementation\".\n\nCopy Constructor\nAs mentioned above, this operation is called when a mutator is applied to a reference that\nshares its object with some other reference. For example, if $b is mathemagical, and '++' is\noverloaded with 'incr', and '=' is overloaded with 'clone', then the code\n\n$a = $b;\n# ... (other code which does not modify $a or $b) ...\n++$b;\n\nwould be executed in a manner equivalent to\n\n$a = $b;\n# ...\n$b = $b->clone(undef, \"\");\n$b->incr(undef, \"\");\n\nNote:\n\n*   The subroutine for '=' does not overload the Perl assignment operator: it is used only to\nallow mutators to work as described here. (See \"Assignments\" above.)\n\n*   As for other operations, the subroutine implementing '=' is passed three arguments, though\nthe last two are always \"undef\" and ''.\n\n*   The copy constructor is called only before a call to a function declared to implement a\nmutator, for example, if \"++$b;\" in the code above is effected via a method declared for key\n'++' (or 'nomethod', passed '++' as the fourth argument) or, by autogeneration, '+='. It is\nnot called if the increment operation is effected by a call to the method for '+' since, in\nthe equivalent code,\n\n$a = $b;\n$b = $b + 1;\n\nthe data referred to by $a is unchanged by the assignment to $b of a reference to new object\ndata.\n\n*   The copy constructor is not called if Perl determines that it is unnecessary because there\nis no other reference to the data being modified.\n\n*   If 'fallback' is undefined or TRUE then a copy constructor can be autogenerated, but only\nfor objects based on scalars. In other cases it needs to be defined explicitly. Where an\nobject's data is stored as, for example, an array of scalars, the following might be\nappropriate:\n\nuse overload '=' => sub { bless [ @{$[0]} ] },  # ...\n\n*   If 'fallback' is TRUE and no copy constructor is defined then, for objects not based on\nscalars, Perl may silently fall back on simple assignment - that is, assignment of the\nobject reference. In effect, this disables the copy constructor mechanism since no new copy\nof the object data is created. This is almost certainly not what you want. (It is, however,\nconsistent: for example, Perl's fallback for the \"++\" operator is to increment the reference\nitself.)\n"
                },
                {
                    "name": "How Perl Chooses an Operator Implementation",
                    "content": "Which is checked first, \"nomethod\" or \"fallback\"? If the two operands of an operator are of\ndifferent types and both overload the operator, which implementation is used? The following are\nthe precedence rules:\n\n1.  If the first operand has declared a subroutine to overload the operator then use that\nimplementation.\n\n2.  Otherwise, if fallback is TRUE or undefined for the first operand then see if the rules for\nautogeneration allows another of its operators to be used instead.\n\n3.  Unless the operator is an assignment (\"+=\", \"-=\", etc.), repeat step (1) in respect of the\nsecond operand.\n\n4.  Repeat Step (2) in respect of the second operand.\n\n5.  If the first operand has a \"nomethod\" method then use that.\n\n6.  If the second operand has a \"nomethod\" method then use that.\n\n7.  If \"fallback\" is TRUE for both operands then perform the usual operation for the operator,\ntreating the operands as numbers, strings, or booleans as appropriate for the operator (see\nnote).\n\n8.  Nothing worked - die.\n\nWhere there is only one operand (or only one operand with overloading) the checks in respect of\nthe other operand above are skipped.\n\nThere are exceptions to the above rules for dereference operations (which, if Step 1 fails,\nalways fall back to the normal, built-in implementations - see Dereferencing), and for \"~~\"\n(which has its own set of rules - see \"Matching\" under \"Overloadable Operations\" above).\n\nNote on Step 7: some operators have a different semantic depending on the type of their\noperands. As there is no way to instruct Perl to treat the operands as, e.g., numbers instead of\nstrings, the result here may not be what you expect. See \"BUGS AND PITFALLS\".\n"
                },
                {
                    "name": "Losing Overloading",
                    "content": "The restriction for the comparison operation is that even if, for example, \"cmp\" should return a\nblessed reference, the autogenerated \"lt\" function will produce only a standard logical value\nbased on the numerical value of the result of \"cmp\". In particular, a working numeric conversion\nis needed in this case (possibly expressed in terms of other conversions).\n\nSimilarly, \".=\" and \"x=\" operators lose their mathemagical properties if the string conversion\nsubstitution is applied.\n\nWhen you chop() a mathemagical object it is promoted to a string and its mathemagical properties\nare lost. The same can happen with other operations as well.\n"
                },
                {
                    "name": "Inheritance and Overloading",
                    "content": "Overloading respects inheritance via the @ISA hierarchy. Inheritance interacts with overloading\nin two ways.\n\nMethod names in the \"use overload\" directive\nIf \"value\" in\n\nuse overload key => value;\n\nis a string, it is interpreted as a method name - which may (in the usual way) be inherited\nfrom another class.\n\nOverloading of an operation is inherited by derived classes\nAny class derived from an overloaded class is also overloaded and inherits its operator\nimplementations. If the same operator is overloaded in more than one ancestor then the\nimplementation is determined by the usual inheritance rules.\n\nFor example, if \"A\" inherits from \"B\" and \"C\" (in that order), \"B\" overloads \"+\" with\n\"\\&D::plussub\", and \"C\" overloads \"+\" by \"plusmeth\", then the subroutine \"D::plussub\"\nwill be called to implement operation \"+\" for an object in package \"A\".\n\nNote that in Perl version prior to 5.18 inheritance of the \"fallback\" key was not governed by\nthe above rules. The value of \"fallback\" in the first overloaded ancestor was used. This was\nfixed in 5.18 to follow the usual rules of inheritance.\n"
                },
                {
                    "name": "Run-time Overloading",
                    "content": "Since all \"use\" directives are executed at compile-time, the only way to change overloading\nduring run-time is to\n\neval 'use overload \"+\" => \\&addmethod';\n\nYou can also use\n\neval 'no overload \"+\", \"--\", \"<=\"';\n\nthough the use of these constructs during run-time is questionable.\n"
                },
                {
                    "name": "Public Functions",
                    "content": "Package \"overload.pm\" provides the following public functions:\n\noverload::StrVal(arg)\nGives the string value of \"arg\" as in the absence of stringify overloading. If you are\nusing this to get the address of a reference (useful for checking if two references point\nto the same thing) then you may be better off using \"Scalar::Util::refaddr()\", which is\nfaster.\n\noverload::Overloaded(arg)\nReturns true if \"arg\" is subject to overloading of some operations.\n\noverload::Method(obj,op)\nReturns \"undef\" or a reference to the method that implements \"op\".\n"
                },
                {
                    "name": "Overloading Constants",
                    "content": "For some applications, the Perl parser mangles constants too much. It is possible to hook into\nthis process via \"overload::constant()\" and \"overload::removeconstant()\" functions.\n\nThese functions take a hash as an argument. The recognized keys of this hash are:\n\ninteger to overload integer constants,\n\nfloat   to overload floating point constants,\n\nbinary  to overload octal and hexadecimal constants,\n\nq       to overload \"q\"-quoted strings, constant pieces of \"qq\"- and \"qx\"-quoted strings and\nhere-documents,\n\nqr      to overload constant pieces of regular expressions.\n\nThe corresponding values are references to functions which take three arguments: the first one\nis the *initial* string form of the constant, the second one is how Perl interprets this\nconstant, the third one is how the constant is used. Note that the initial string form does not\ncontain string delimiters, and has backslashes in backslash-delimiter combinations stripped\n(thus the value of delimiter is not relevant for processing of this string). The return value of\nthis function is how this constant is going to be interpreted by Perl. The third argument is\nundefined unless for overloaded \"q\"- and \"qr\"- constants, it is \"q\" in single-quote context\n(comes from strings, regular expressions, and single-quote HERE documents), it is \"tr\" for\narguments of \"tr\"/\"y\" operators, it is \"s\" for right-hand side of \"s\"-operator, and it is \"qq\"\notherwise.\n\nSince an expression \"ab$cd,,\" is just a shortcut for 'ab' . $cd . ',,', it is expected that\noverloaded constant strings are equipped with reasonable overloaded catenation operator,\notherwise absurd results will result. Similarly, negative numbers are considered as negations of\npositive constants.\n\nNote that it is probably meaningless to call the functions overload::constant() and\noverload::removeconstant() from anywhere but import() and unimport() methods. From these\nmethods they may be called as\n\nsub import {\nshift;\nreturn unless @;\ndie \"unknown import: @\" unless @ == 1 and $[0] eq ':constant';\noverload::constant integer => sub {Math::BigInt->new(shift)};\n}\n"
                }
            ]
        },
        "IMPLEMENTATION": {
            "content": "What follows is subject to change RSN.\n\nThe table of methods for all operations is cached in magic for the symbol table hash for the\npackage. The cache is invalidated during processing of \"use overload\", \"no overload\", new\nfunction definitions, and changes in @ISA.\n\n(Every SVish thing has a magic queue, and magic is an entry in that queue. This is how a single\nvariable may participate in multiple forms of magic simultaneously. For instance, environment\nvariables regularly have two forms at once: their %ENV magic and their taint magic. However, the\nmagic which implements overloading is applied to the stashes, which are rarely used directly,\nthus should not slow down Perl.)\n\nIf a package uses overload, it carries a special flag. This flag is also set when new functions\nare defined or @ISA is modified. There will be a slight speed penalty on the very first\noperation thereafter that supports overloading, while the overload tables are updated. If there\nis no overloading present, the flag is turned off. Thus the only speed penalty thereafter is the\nchecking of this flag.\n\nIt is expected that arguments to methods that are not explicitly supposed to be changed are\nconstant (but this is not enforced).\n",
            "subsections": []
        },
        "COOKBOOK": {
            "content": "Please add examples to what follows!\n",
            "subsections": [
                {
                    "name": "Two-face Scalars",
                    "content": "Put this in twoface.pm in your Perl library directory:\n\npackage twoface;             # Scalars with separate string and\n# numeric values.\nsub new { my $p = shift; bless [@], $p }\nuse overload '\"\"' => \\&str, '0+' => \\&num, fallback => 1;\nsub num {shift->[1]}\nsub str {shift->[0]}\n\nUse it as follows:\n\nrequire twoface;\nmy $seven = twoface->new(\"vii\", 7);\nprintf \"seven=$seven, seven=%d, eight=%d\\n\", $seven, $seven+1;\nprint \"seven contains 'i'\\n\" if $seven =~ /i/;\n\n(The second line creates a scalar which has both a string value, and a numeric value.) This\nprints:\n\nseven=vii, seven=7, eight=8\nseven contains 'i'\n"
                },
                {
                    "name": "Two-face References",
                    "content": "Suppose you want to create an object which is accessible as both an array reference and a hash\nreference.\n\npackage tworefs;\nuse overload '%{}' => \\&gethash, '@{}' => sub { $ {shift()} };\nsub new {\nmy $p = shift;\nbless \\ [@], $p;\n}\nsub gethash {\nmy %h;\nmy $self = shift;\ntie %h, ref $self, $self;\n\\%h;\n}\n\nsub TIEHASH { my $p = shift; bless \\ shift, $p }\nmy %fields;\nmy $i = 0;\n$fields{$} = $i++ foreach qw{zero one two three};\nsub STORE {\nmy $self = ${shift()};\nmy $key = $fields{shift()};\ndefined $key or die \"Out of band access\";\n$$self->[$key] = shift;\n}\nsub FETCH {\nmy $self = ${shift()};\nmy $key = $fields{shift()};\ndefined $key or die \"Out of band access\";\n$$self->[$key];\n}\n\nNow one can access an object using both the array and hash syntax:\n\nmy $bar = tworefs->new(3,4,5,6);\n$bar->[2] = 11;\n$bar->{two} == 11 or die 'bad hash fetch';\n\nNote several important features of this example. First of all, the *actual* type of $bar is a\nscalar reference, and we do not overload the scalar dereference. Thus we can get the *actual*\nnon-overloaded contents of $bar by just using $$bar (what we do in functions which overload\ndereference). Similarly, the object returned by the TIEHASH() method is a scalar reference.\n\nSecond, we create a new tied hash each time the hash syntax is used. This allows us not to worry\nabout a possibility of a reference loop, which would lead to a memory leak.\n\nBoth these problems can be cured. Say, if we want to overload hash dereference on a reference to\nan object which is *implemented* as a hash itself, the only problem one has to circumvent is how\nto access this *actual* hash (as opposed to the *virtual* hash exhibited by the overloaded\ndereference operator). Here is one possible fetching routine:\n\nsub accesshash {\nmy ($self, $key) = (shift, shift);\nmy $class = ref $self;\nbless $self, 'overload::dummy'; # Disable overloading of %{}\nmy $out = $self->{$key};\nbless $self, $class;        # Restore overloading\n$out;\n}\n\nTo remove creation of the tied hash on each access, one may an extra level of indirection which\nallows a non-circular structure of references:\n\npackage tworefs1;\nuse overload '%{}' => sub { ${shift()}->[1] },\n'@{}' => sub { ${shift()}->[0] };\nsub new {\nmy $p = shift;\nmy $a = [@];\nmy %h;\ntie %h, $p, $a;\nbless \\ [$a, \\%h], $p;\n}\nsub gethash {\nmy %h;\nmy $self = shift;\ntie %h, ref $self, $self;\n\\%h;\n}\n\nsub TIEHASH { my $p = shift; bless \\ shift, $p }\nmy %fields;\nmy $i = 0;\n$fields{$} = $i++ foreach qw{zero one two three};\nsub STORE {\nmy $a = ${shift()};\nmy $key = $fields{shift()};\ndefined $key or die \"Out of band access\";\n$a->[$key] = shift;\n}\nsub FETCH {\nmy $a = ${shift()};\nmy $key = $fields{shift()};\ndefined $key or die \"Out of band access\";\n$a->[$key];\n}\n\nNow if $baz is overloaded like this, then $baz is a reference to a reference to the intermediate\narray, which keeps a reference to an actual array, and the access hash. The tie()ing object for\nthe access hash is a reference to a reference to the actual array, so\n\n*   There are no loops of references.\n\n*   Both \"objects\" which are blessed into the class \"tworefs1\" are references to a reference to\nan array, thus references to a *scalar*. Thus the accessor expression \"$$foo->[$ind]\"\ninvolves no overloaded operations.\n"
                },
                {
                    "name": "Symbolic Calculator",
                    "content": "Put this in symbolic.pm in your Perl library directory:\n\npackage symbolic;             # Primitive symbolic calculator\nuse overload nomethod => \\&wrap;\n\nsub new { shift; bless ['n', @] }\nsub wrap {\nmy ($obj, $other, $inv, $meth) = @;\n($obj, $other) = ($other, $obj) if $inv;\nbless [$meth, $obj, $other];\n}\n\nThis module is very unusual as overloaded modules go: it does not provide any usual overloaded\noperators, instead it provides an implementation for \"nomethod\". In this example the \"nomethod\"\nsubroutine returns an object which encapsulates operations done over the objects:\n\"symbolic->new(3)\" contains \"['n', 3]\", \"2 + symbolic->new(3)\" contains \"['+', 2, ['n', 3]]\".\n\nHere is an example of the script which \"calculates\" the side of circumscribed octagon using the\nabove package:\n\nrequire symbolic;\nmy $iter = 1;                 # 2($iter+2) = 8\nmy $side = symbolic->new(1);\nmy $cnt = $iter;\n\nwhile ($cnt--) {\n$side = (sqrt(1 + $side2) - 1)/$side;\n}\nprint \"OK\\n\";\n\nThe value of $side is\n\n['/', ['-', ['sqrt', ['+', 1, ['', ['n', 1], 2]],\nundef], 1], ['n', 1]]\n\nNote that while we obtained this value using a nice little script, there is no simple way to\n*use* this value. In fact this value may be inspected in debugger (see perldebug), but only if\n\"bareStringify\" Option is set, and not via \"p\" command.\n\nIf one attempts to print this value, then the overloaded operator \"\" will be called, which will\ncall \"nomethod\" operator. The result of this operator will be stringified again, but this result\nis again of type \"symbolic\", which will lead to an infinite loop.\n\nAdd a pretty-printer method to the module symbolic.pm:\n\nsub pretty {\nmy ($meth, $a, $b) = @{+shift};\n$a = 'u' unless defined $a;\n$b = 'u' unless defined $b;\n$a = $a->pretty if ref $a;\n$b = $b->pretty if ref $b;\n\"[$meth $a $b]\";\n}\n\nNow one can finish the script by\n\nprint \"side = \", $side->pretty, \"\\n\";\n\nThe method \"pretty\" is doing object-to-string conversion, so it is natural to overload the\noperator \"\" using this method. However, inside such a method it is not necessary to pretty-print\nthe *components* $a and $b of an object. In the above subroutine \"[$meth $a $b]\" is a catenation\nof some strings and components $a and $b. If these components use overloading, the catenation\noperator will look for an overloaded operator \".\"; if not present, it will look for an\noverloaded operator \"\". Thus it is enough to use\n\nuse overload nomethod => \\&wrap, '\"\"' => \\&str;\nsub str {\nmy ($meth, $a, $b) = @{+shift};\n$a = 'u' unless defined $a;\n$b = 'u' unless defined $b;\n\"[$meth $a $b]\";\n}\n\nNow one can change the last line of the script to\n\nprint \"side = $side\\n\";\n\nwhich outputs\n\nside = [/ [- [sqrt [+ 1 [ [n 1 u] 2]] u] 1] [n 1 u]]\n\nand one can inspect the value in debugger using all the possible methods.\n\nSomething is still amiss: consider the loop variable $cnt of the script. It was a number, not an\nobject. We cannot make this value of type \"symbolic\", since then the loop will not terminate.\n\nIndeed, to terminate the cycle, the $cnt should become false. However, the operator \"bool\" for\nchecking falsity is overloaded (this time via overloaded \"\"), and returns a long string, thus\nany object of type \"symbolic\" is true. To overcome this, we need a way to compare an object to\n0. In fact, it is easier to write a numeric conversion routine.\n\nHere is the text of symbolic.pm with such a routine added (and slightly modified str()):\n\npackage symbolic;             # Primitive symbolic calculator\nuse overload\nnomethod => \\&wrap, '\"\"' => \\&str, '0+' => \\&num;\n\nsub new { shift; bless ['n', @] }\nsub wrap {\nmy ($obj, $other, $inv, $meth) = @;\n($obj, $other) = ($other, $obj) if $inv;\nbless [$meth, $obj, $other];\n}\nsub str {\nmy ($meth, $a, $b) = @{+shift};\n$a = 'u' unless defined $a;\nif (defined $b) {\n\"[$meth $a $b]\";\n} else {\n\"[$meth $a]\";\n}\n}\nmy %subr = ( n => sub {$[0]},\nsqrt => sub {sqrt $[0]},\n'-' => sub {shift() - shift()},\n'+' => sub {shift() + shift()},\n'/' => sub {shift() / shift()},\n'*' => sub {shift() * shift()},\n'' => sub {shift()  shift()},\n);\nsub num {\nmy ($meth, $a, $b) = @{+shift};\nmy $subr = $subr{$meth}\nor die \"Do not know how to ($meth) in symbolic\";\n$a = $a->num if ref $a eq PACKAGE;\n$b = $b->num if ref $b eq PACKAGE;\n$subr->($a,$b);\n}\n\nAll the work of numeric conversion is done in %subr and num(). Of course, %subr is not complete,\nit contains only operators used in the example below. Here is the extra-credit question: why do\nwe need an explicit recursion in num()? (Answer is at the end of this section.)\n\nUse this module like this:\n\nrequire symbolic;\nmy $iter = symbolic->new(2);  # 16-gon\nmy $side = symbolic->new(1);\nmy $cnt = $iter;\n\nwhile ($cnt) {\n$cnt = $cnt - 1;            # Mutator '--' not implemented\n$side = (sqrt(1 + $side2) - 1)/$side;\n}\nprintf \"%s=%f\\n\", $side, $side;\nprintf \"pi=%f\\n\", $side*(2($iter+2));\n\nIt prints (without so many line breaks)\n\n[/ [- [sqrt [+ 1 [ [/ [- [sqrt [+ 1 [ [n 1] 2]]] 1]\n[n 1]] 2]]] 1]\n[/ [- [sqrt [+ 1 [ [n 1] 2]]] 1] [n 1]]]=0.198912\npi=3.182598\n\nThe above module is very primitive. It does not implement mutator methods (\"++\", \"-=\" and so\non), does not do deep copying (not required without mutators!), and implements only those\narithmetic operations which are used in the example.\n\nTo implement most arithmetic operations is easy; one should just use the tables of operations,\nand change the code which fills %subr to\n\nmy %subr = ( 'n' => sub {$[0]} );\nforeach my $op (split \" \", $overload::ops{withassign}) {\n$subr{$op} = $subr{\"$op=\"} = eval \"sub {shift() $op shift()}\";\n}\nmy @bins = qw(binary 3waycomparison numcomparison strcomparison);\nforeach my $op (split \" \", \"@overload::ops{ @bins }\") {\n$subr{$op} = eval \"sub {shift() $op shift()}\";\n}\nforeach my $op (split \" \", \"@overload::ops{qw(unary func)}\") {\nprint \"defining '$op'\\n\";\n$subr{$op} = eval \"sub {$op shift()}\";\n}\n\nSince subroutines implementing assignment operators are not required to modify their operands\n(see \"Overloadable Operations\" above), we do not need anything special to make \"+=\" and friends\nwork, besides adding these operators to %subr and defining a copy constructor (needed since Perl\nhas no way to know that the implementation of '+=' does not mutate the argument - see \"Copy\nConstructor\").\n\nTo implement a copy constructor, add \"'=' => \\&cpy\" to \"use overload\" line, and code (this code\nassumes that mutators change things one level deep only, so recursive copying is not needed):\n\nsub cpy {\nmy $self = shift;\nbless [@$self], ref $self;\n}\n\nTo make \"++\" and \"--\" work, we need to implement actual mutators, either directly, or in\n\"nomethod\". We continue to do things inside \"nomethod\", thus add\n\nif ($meth eq '++' or $meth eq '--') {\n@$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference\nreturn $obj;\n}\n\nafter the first line of wrap(). This is not a most effective implementation, one may consider\n\nsub inc { $[0] = bless ['++', shift, 1]; }\n\ninstead.\n\nAs a final remark, note that one can fill %subr by\n\nmy %subr = ( 'n' => sub {$[0]} );\nforeach my $op (split \" \", $overload::ops{withassign}) {\n$subr{$op} = $subr{\"$op=\"} = eval \"sub {shift() $op shift()}\";\n}\nmy @bins = qw(binary 3waycomparison numcomparison strcomparison);\nforeach my $op (split \" \", \"@overload::ops{ @bins }\") {\n$subr{$op} = eval \"sub {shift() $op shift()}\";\n}\nforeach my $op (split \" \", \"@overload::ops{qw(unary func)}\") {\n$subr{$op} = eval \"sub {$op shift()}\";\n}\n$subr{'++'} = $subr{'+'};\n$subr{'--'} = $subr{'-'};\n\nThis finishes implementation of a primitive symbolic calculator in 50 lines of Perl code. Since\nthe numeric values of subexpressions are not cached, the calculator is very slow.\n\nHere is the answer for the exercise: In the case of str(), we need no explicit recursion since\nthe overloaded \".\"-operator will fall back to an existing overloaded operator \"\". Overloaded\narithmetic operators *do not* fall back to numeric conversion if \"fallback\" is not explicitly\nrequested. Thus without an explicit recursion num() would convert \"['+', $a, $b]\" to \"$a + $b\",\nwhich would just rebuild the argument of num().\n\nIf you wonder why defaults for conversion are different for str() and num(), note how easy it\nwas to write the symbolic calculator. This simplicity is due to an appropriate choice of\ndefaults. One extra note: due to the explicit recursion num() is more fragile than sym(): we\nneed to explicitly check for the type of $a and $b. If components $a and $b happen to be of some\nrelated type, this may lead to problems.\n\n*Really* Symbolic Calculator\nOne may wonder why we call the above calculator symbolic. The reason is that the actual\ncalculation of the value of expression is postponed until the value is *used*.\n\nTo see it in action, add a method\n\nsub STORE {\nmy $obj = shift;\n$#$obj = 1;\n@$obj->[0,1] = ('=', shift);\n}\n\nto the package \"symbolic\". After this change one can do\n\nmy $a = symbolic->new(3);\nmy $b = symbolic->new(4);\nmy $c = sqrt($a2 + $b2);\n\nand the numeric value of $c becomes 5. However, after calling\n\n$a->STORE(12);  $b->STORE(5);\n\nthe numeric value of $c becomes 13. There is no doubt now that the module symbolic provides a\n*symbolic* calculator indeed.\n\nTo hide the rough edges under the hood, provide a tie()d interface to the package \"symbolic\".\nAdd methods\n\nsub TIESCALAR { my $pack = shift; $pack->new(@) }\nsub FETCH { shift }\nsub nop {  }          # Around a bug\n\n(the bug, fixed in Perl 5.14, is described in \"BUGS\"). One can use this new interface as\n\ntie $a, 'symbolic', 3;\ntie $b, 'symbolic', 4;\n$a->nop;  $b->nop;    # Around a bug\n\nmy $c = sqrt($a2 + $b2);\n\nNow numeric value of $c is 5. After \"$a = 12; $b = 5\" the numeric value of $c becomes 13. To\ninsulate the user of the module add a method\n\nsub vars { my $p = shift; tie($, $p), $->nop foreach @; }\n\nNow\n\nmy ($a, $b);\nsymbolic->vars($a, $b);\nmy $c = sqrt($a2 + $b2);\n\n$a = 3; $b = 4;\nprintf \"c5  %s=%f\\n\", $c, $c;\n\n$a = 12; $b = 5;\nprintf \"c13  %s=%f\\n\", $c, $c;\n\nshows that the numeric value of $c follows changes to the values of $a and $b.\n"
                }
            ]
        },
        "AUTHOR": {
            "content": "Ilya Zakharevich <ilya@math.mps.ohio-state.edu>.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "The \"overloading\" pragma can be used to enable or disable overloaded operations within a lexical\nscope - see overloading.\n",
            "subsections": []
        },
        "DIAGNOSTICS": {
            "content": "When Perl is run with the -Do switch or its equivalent, overloading induces diagnostic messages.\n\nUsing the \"m\" command of Perl debugger (see perldebug) one can deduce which operations are\noverloaded (and which ancestor triggers this overloading). Say, if \"eq\" is overloaded, then the\nmethod \"(eq\" is shown by debugger. The method \"()\" corresponds to the \"fallback\" key (in fact a\npresence of this method shows that this package has overloading enabled, and it is what is used\nby the \"Overloaded\" function of module \"overload\").\n\nThe module might issue the following warnings:\n\nOdd number of arguments for overload::constant\n(W) The call to overload::constant contained an odd number of arguments. The arguments\nshould come in pairs.\n\n'%s' is not an overloadable type\n(W) You tried to overload a constant type the overload package is unaware of.\n\n'%s' is not a code reference\n(W) The second (fourth, sixth, ...) argument of overload::constant needs to be a code\nreference. Either an anonymous subroutine, or a reference to a subroutine.\n\noverload arg '%s' is invalid\n(W) \"use overload\" was passed an argument it did not recognize. Did you mistype an operator?\n",
            "subsections": []
        },
        "BUGS AND PITFALLS": {
            "content": "*   A pitfall when fallback is TRUE and Perl resorts to a built-in implementation of an operator\nis that some operators have more than one semantic, for example \"|\":\n\nuse overload '0+' => sub { $[0]->{n}; },\nfallback => 1;\nmy $x = bless { n => 4 }, \"main\";\nmy $y = bless { n => 8 }, \"main\";\nprint $x | $y, \"\\n\";\n\nYou might expect this to output \"12\". In fact, it prints \"<\": the ASCII result of treating\n\"|\" as a bitwise string operator - that is, the result of treating the operands as the\nstrings \"4\" and \"8\" rather than numbers. The fact that numify (\"0+\") is implemented but\nstringify (\"\") isn't makes no difference since the latter is simply autogenerated from the\nformer.\n\nThe only way to change this is to provide your own subroutine for '|'.\n\n*   Magic autogeneration increases the potential for inadvertently creating self-referential\nstructures. Currently Perl will not free self-referential structures until cycles are\nexplicitly broken. For example,\n\nuse overload '+' => 'add';\nsub add { bless [ \\$[0], \\$[1] ] };\n\nis asking for trouble, since\n\n$obj += $y;\n\nwill effectively become\n\n$obj = add($obj, $y, undef);\n\nwith the same result as\n\n$obj = [\\$obj, \\$foo];\n\nEven if no *explicit* assignment-variants of operators are present in the script, they may\nbe generated by the optimizer. For example,\n\n\"obj = $obj\\n\"\n\nmay be optimized to\n\nmy $tmp = 'obj = ' . $obj;  $tmp .= \"\\n\";\n\n*   The symbol table is filled with names looking like line-noise.\n\n*   This bug was fixed in Perl 5.18, but may still trip you up if you are using older versions:\n\nFor the purpose of inheritance every overloaded package behaves as if \"fallback\" is present\n(possibly undefined). This may create interesting effects if some package is not overloaded,\nbut inherits from two overloaded packages.\n\n*   Before Perl 5.14, the relation between overloading and tie()ing was broken. Overloading was\ntriggered or not based on the *previous* class of the tie()d variable.\n\nThis happened because the presence of overloading was checked too early, before any tie()d\naccess was attempted. If the class of the value FETCH()ed from the tied variable does not\nchange, a simple workaround for code that is to run on older Perl versions is to access the\nvalue (via \"() = $foo\" or some such) immediately after tie()ing, so that after this call the\n*previous* class coincides with the current one.\n\n*   Barewords are not covered by overloaded string constants.\n\n*   The range operator \"..\" cannot be overloaded.\n",
            "subsections": []
        }
    },
    "summary": "overload - Package for overloading Perl operations",
    "flags": [],
    "examples": [],
    "see_also": []
}