Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / man / man3 / overload.3
CommitLineData
86530b38
AT
1.\" Automatically generated by Pod::Man v1.34, Pod::Parser v1.13
2.\"
3.\" Standard preamble:
4.\" ========================================================================
5.de Sh \" Subsection heading
6.br
7.if t .Sp
8.ne 5
9.PP
10\fB\\$1\fR
11.PP
12..
13.de Sp \" Vertical space (when we can't use .PP)
14.if t .sp .5v
15.if n .sp
16..
17.de Vb \" Begin verbatim text
18.ft CW
19.nf
20.ne \\$1
21..
22.de Ve \" End verbatim text
23.ft R
24.fi
25..
26.\" Set up some character translations and predefined strings. \*(-- will
27.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
28.\" double quote, and \*(R" will give a right double quote. | will give a
29.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
30.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
31.\" expand to `' in nroff, nothing in troff, for use with C<>.
32.tr \(*W-|\(bv\*(Tr
33.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
34.ie n \{\
35. ds -- \(*W-
36. ds PI pi
37. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
38. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
39. ds L" ""
40. ds R" ""
41. ds C` ""
42. ds C' ""
43'br\}
44.el\{\
45. ds -- \|\(em\|
46. ds PI \(*p
47. ds L" ``
48. ds R" ''
49'br\}
50.\"
51.\" If the F register is turned on, we'll generate index entries on stderr for
52.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
53.\" entries marked with X<> in POD. Of course, you'll have to process the
54.\" output yourself in some meaningful fashion.
55.if \nF \{\
56. de IX
57. tm Index:\\$1\t\\n%\t"\\$2"
58..
59. nr % 0
60. rr F
61.\}
62.\"
63.\" For nroff, turn off justification. Always turn off hyphenation; it makes
64.\" way too many mistakes in technical documents.
65.hy 0
66.if n .na
67.\"
68.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
69.\" Fear. Run. Save yourself. No user-serviceable parts.
70. \" fudge factors for nroff and troff
71.if n \{\
72. ds #H 0
73. ds #V .8m
74. ds #F .3m
75. ds #[ \f1
76. ds #] \fP
77.\}
78.if t \{\
79. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
80. ds #V .6m
81. ds #F 0
82. ds #[ \&
83. ds #] \&
84.\}
85. \" simple accents for nroff and troff
86.if n \{\
87. ds ' \&
88. ds ` \&
89. ds ^ \&
90. ds , \&
91. ds ~ ~
92. ds /
93.\}
94.if t \{\
95. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
96. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
97. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
98. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
99. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
100. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
101.\}
102. \" troff and (daisy-wheel) nroff accents
103.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
104.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
105.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
106.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
107.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
108.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
109.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
110.ds ae a\h'-(\w'a'u*4/10)'e
111.ds Ae A\h'-(\w'A'u*4/10)'E
112. \" corrections for vroff
113.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
114.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
115. \" for low resolution devices (crt and lpr)
116.if \n(.H>23 .if \n(.V>19 \
117\{\
118. ds : e
119. ds 8 ss
120. ds o a
121. ds d- d\h'-1'\(ga
122. ds D- D\h'-1'\(hy
123. ds th \o'bp'
124. ds Th \o'LP'
125. ds ae ae
126. ds Ae AE
127.\}
128.rm #[ #] #H #V #F C
129.\" ========================================================================
130.\"
131.IX Title "overload 3"
132.TH overload 3 "2002-06-01" "perl v5.8.0" "Perl Programmers Reference Guide"
133.SH "NAME"
134overload \- Package for overloading perl operations
135.SH "SYNOPSIS"
136.IX Header "SYNOPSIS"
137.Vb 1
138\& package SomeThing;
139.Ve
140.PP
141.Vb 5
142\& use overload
143\& '+' => \e&myadd,
144\& '-' => \e&mysub;
145\& # etc
146\& ...
147.Ve
148.PP
149.Vb 7
150\& package main;
151\& $a = new SomeThing 57;
152\& $b=5+$a;
153\& ...
154\& if (overload::Overloaded $b) {...}
155\& ...
156\& $strval = overload::StrVal $b;
157.Ve
158.SH "DESCRIPTION"
159.IX Header "DESCRIPTION"
160.Sh "Declaration of overloaded functions"
161.IX Subsection "Declaration of overloaded functions"
162The compilation directive
163.PP
164.Vb 4
165\& package Number;
166\& use overload
167\& "+" => \e&add,
168\& "*=" => "muas";
169.Ve
170.PP
171declares function \fINumber::add()\fR for addition, and method \fImuas()\fR in
172the \*(L"class\*(R" \f(CW\*(C`Number\*(C'\fR (or one of its base classes)
173for the assignment form \f(CW\*(C`*=\*(C'\fR of multiplication.
174.PP
175Arguments of this directive come in (key, value) pairs. Legal values
176are values legal inside a \f(CW\*(C`&{ ... }\*(C'\fR call, so the name of a
177subroutine, a reference to a subroutine, or an anonymous subroutine
178will all work. Note that values specified as strings are
179interpreted as methods, not subroutines. Legal keys are listed below.
180.PP
181The subroutine \f(CW\*(C`add\*(C'\fR will be called to execute \f(CW\*(C`$a+$b\*(C'\fR if \f(CW$a\fR
182is a reference to an object blessed into the package \f(CW\*(C`Number\*(C'\fR, or if \f(CW$a\fR is
183not an object from a package with defined mathemagic addition, but \f(CW$b\fR is a
184reference to a \f(CW\*(C`Number\*(C'\fR. It can also be called in other situations, like
185\&\f(CW\*(C`$a+=7\*(C'\fR, or \f(CW\*(C`$a++\*(C'\fR. See \*(L"\s-1MAGIC\s0 \s-1AUTOGENERATION\s0\*(R". (Mathemagical
186methods refer to methods triggered by an overloaded mathematical
187operator.)
188.PP
189Since overloading respects inheritance via the \f(CW@ISA\fR hierarchy, the
190above declaration would also trigger overloading of \f(CW\*(C`+\*(C'\fR and \f(CW\*(C`*=\*(C'\fR in
191all the packages which inherit from \f(CW\*(C`Number\*(C'\fR.
192.Sh "Calling Conventions for Binary Operations"
193.IX Subsection "Calling Conventions for Binary Operations"
194The functions specified in the \f(CW\*(C`use overload ...\*(C'\fR directive are called
195with three (in one particular case with four, see \*(L"Last Resort\*(R")
196arguments. If the corresponding operation is binary, then the first
197two arguments are the two arguments of the operation. However, due to
198general object calling conventions, the first argument should always be
199an object in the package, so in the situation of \f(CW\*(C`7+$a\*(C'\fR, the
200order of the arguments is interchanged. It probably does not matter
201when implementing the addition method, but whether the arguments
202are reversed is vital to the subtraction method. The method can
203query this information by examining the third argument, which can take
204three different values:
205.IP "\s-1FALSE\s0" 7
206.IX Item "FALSE"
207the order of arguments is as in the current operation.
208.IP "\s-1TRUE\s0" 7
209.IX Item "TRUE"
210the arguments are reversed.
211.ie n .IP """undef""" 7
212.el .IP "\f(CWundef\fR" 7
213.IX Item "undef"
214the current operation is an assignment variant (as in
215\&\f(CW\*(C`$a+=7\*(C'\fR), but the usual function is called instead. This additional
216information can be used to generate some optimizations. Compare
217\&\*(L"Calling Conventions for Mutators\*(R".
218.Sh "Calling Conventions for Unary Operations"
219.IX Subsection "Calling Conventions for Unary Operations"
220Unary operation are considered binary operations with the second
221argument being \f(CW\*(C`undef\*(C'\fR. Thus the functions that overloads \f(CW\*(C`{"++"}\*(C'\fR
222is called with arguments \f(CW\*(C`($a,undef,'')\*(C'\fR when \f(CW$a\fR++ is executed.
223.Sh "Calling Conventions for Mutators"
224.IX Subsection "Calling Conventions for Mutators"
225Two types of mutators have different calling conventions:
226.ie n .IP """++""\fR and \f(CW""\-\-""" 4
227.el .IP "\f(CW++\fR and \f(CW\-\-\fR" 4
228.IX Item "++ and --"
229The routines which implement these operators are expected to actually
230\&\fImutate\fR their arguments. So, assuming that \f(CW$obj\fR is a reference to a
231number,
232.Sp
233.Vb 1
234\& sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \e$n}
235.Ve
236.Sp
237is an appropriate implementation of overloaded \f(CW\*(C`++\*(C'\fR. Note that
238.Sp
239.Vb 1
240\& sub incr { ++$ {$_[0]} ; shift }
241.Ve
242.Sp
243is \s-1OK\s0 if used with preincrement and with postincrement. (In the case
244of postincrement a copying will be performed, see \*(L"Copy Constructor\*(R".)
245.ie n .IP """x="" and other assignment versions" 4
246.el .IP "\f(CWx=\fR and other assignment versions" 4
247.IX Item "x= and other assignment versions"
248There is nothing special about these methods. They may change the
249value of their arguments, and may leave it as is. The result is going
250to be assigned to the value in the left-hand-side if different from
251this value.
252.Sp
253This allows for the same method to be used as overloaded \f(CW\*(C`+=\*(C'\fR and
254\&\f(CW\*(C`+\*(C'\fR. Note that this is \fIallowed\fR, but not recommended, since by the
255semantic of \*(L"Fallback\*(R" Perl will call the method for \f(CW\*(C`+\*(C'\fR anyway,
256if \f(CW\*(C`+=\*(C'\fR is not overloaded.
257.PP
258\&\fBWarning.\fR Due to the presence of assignment versions of operations,
259routines which may be called in assignment context may create
260self-referential structures. Currently Perl will not free self-referential
261structures until cycles are \f(CW\*(C`explicitly\*(C'\fR broken. You may get problems
262when traversing your structures too.
263.PP
264Say,
265.PP
266.Vb 1
267\& use overload '+' => sub { bless [ \e$_[0], \e$_[1] ] };
268.Ve
269.PP
270is asking for trouble, since for code \f(CW\*(C`$obj += $foo\*(C'\fR the subroutine
271is called as \f(CW\*(C`$obj = add($obj, $foo, undef)\*(C'\fR, or \f(CW\*(C`$obj = [\e$obj,
272\&\e$foo]\*(C'\fR. If using such a subroutine is an important optimization, one
273can overload \f(CW\*(C`+=\*(C'\fR explicitly by a non\-\*(L"optimized\*(R" version, or switch
274to non-optimized version if \f(CW\*(C`not defined $_[2]\*(C'\fR (see
275\&\*(L"Calling Conventions for Binary Operations\*(R").
276.PP
277Even if no \fIexplicit\fR assignment-variants of operators are present in
278the script, they may be generated by the optimizer. Say, \f(CW",$obj,"\fR or
279\&\f(CW',' . $obj . ','\fR may be both optimized to
280.PP
281.Vb 1
282\& my $tmp = ',' . $obj; $tmp .= ',';
283.Ve
284.Sh "Overloadable Operations"
285.IX Subsection "Overloadable Operations"
286The following symbols can be specified in \f(CW\*(C`use overload\*(C'\fR directive:
287.IP "\(bu \fIArithmetic operations\fR" 5
288.IX Item "Arithmetic operations"
289.Vb 2
290\& "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
291\& "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
292.Ve
293.Sp
294For these operations a substituted non-assignment variant can be called if
295the assignment variant is not available. Methods for operations \f(CW\*(C`+\*(C'\fR,
296\&\f(CW\*(C`\-\*(C'\fR, \f(CW\*(C`+=\*(C'\fR, and \f(CW\*(C`\-=\*(C'\fR can be called to automatically generate
297increment and decrement methods. The operation \f(CW\*(C`\-\*(C'\fR can be used to
298autogenerate missing methods for unary minus or \f(CW\*(C`abs\*(C'\fR.
299.Sp
300See \*(L"\s-1MAGIC\s0 \s-1AUTOGENERATION\s0\*(R", \*(L"Calling Conventions for Mutators\*(R" and
301\&\*(L"Calling Conventions for Binary Operations\*(R") for details of these
302substitutions.
303.IP "\(bu \fIComparison operations\fR" 5
304.IX Item "Comparison operations"
305.Vb 2
306\& "<", "<=", ">", ">=", "==", "!=", "<=>",
307\& "lt", "le", "gt", "ge", "eq", "ne", "cmp",
308.Ve
309.Sp
310If the corresponding \*(L"spaceship\*(R" variant is available, it can be
311used to substitute for the missing operation. During \f(CW\*(C`sort\*(C'\fRing
312arrays, \f(CW\*(C`cmp\*(C'\fR is used to compare values subject to \f(CW\*(C`use overload\*(C'\fR.
313.IP "\(bu \fIBit operations\fR" 5
314.IX Item "Bit operations"
315.Vb 1
316\& "&", "^", "|", "neg", "!", "~",
317.Ve
318.Sp
319\&\f(CW\*(C`neg\*(C'\fR stands for unary minus. If the method for \f(CW\*(C`neg\*(C'\fR is not
320specified, it can be autogenerated using the method for
321subtraction. If the method for \f(CW\*(C`!\*(C'\fR is not specified, it can be
322autogenerated using the methods for \f(CW\*(C`bool\*(C'\fR, or \f(CW""\fR, or \f(CW\*(C`0+\*(C'\fR.
323.IP "\(bu \fIIncrement and decrement\fR" 5
324.IX Item "Increment and decrement"
325.Vb 1
326\& "++", "--",
327.Ve
328.Sp
329If undefined, addition and subtraction methods can be
330used instead. These operations are called both in prefix and
331postfix form.
332.IP "\(bu \fITranscendental functions\fR" 5
333.IX Item "Transcendental functions"
334.Vb 1
335\& "atan2", "cos", "sin", "exp", "abs", "log", "sqrt", "int"
336.Ve
337.Sp
338If \f(CW\*(C`abs\*(C'\fR is unavailable, it can be autogenerated using methods
339for "<\*(L" or \*(R"<=>" combined with either unary minus or subtraction.
340.Sp
341Note that traditionally the Perl function int rounds to 0, thus for
342floating-point-like types one should follow the same semantic. If
343\&\f(CW\*(C`int\*(C'\fR is unavailable, it can be autogenerated using the overloading of
344\&\f(CW\*(C`0+\*(C'\fR.
345.IP "\(bu \fIBoolean, string and numeric conversion\fR" 5
346.IX Item "Boolean, string and numeric conversion"
347.Vb 1
348\& 'bool', '""', '0+',
349.Ve
350.Sp
351If one or two of these operations are not overloaded, the remaining ones can
352be used instead. \f(CW\*(C`bool\*(C'\fR is used in the flow control operators
353(like \f(CW\*(C`while\*(C'\fR) and for the ternary \f(CW\*(C`?:\*(C'\fR operation. These functions can
354return any arbitrary Perl value. If the corresponding operation for this value
355is overloaded too, that operation will be called again with this value.
356.Sp
357As a special case if the overload returns the object itself then it will
358be used directly. An overloaded conversion returning the object is
359probably a bug, because you're likely to get something that looks like
360\&\f(CW\*(C`YourPackage=HASH(0x8172b34)\*(C'\fR.
361.IP "\(bu \fIIteration\fR" 5
362.IX Item "Iteration"
363.Vb 1
364\& "<>"
365.Ve
366.Sp
367If not overloaded, the argument will be converted to a filehandle or
368glob (which may require a stringification). The same overloading
369happens both for the \fIread-filehandle\fR syntax \f(CW\*(C`<$var>\*(C'\fR and
370\&\fIglobbing\fR syntax \f(CW\*(C`<${var}>\*(C'\fR.
371.Sp
372\&\fB\s-1BUGS\s0\fR Even in list context, the iterator is currently called only
373once and with scalar context.
374.IP "\(bu \fIDereferencing\fR" 5
375.IX Item "Dereferencing"
376.Vb 1
377\& '${}', '@{}', '%{}', '&{}', '*{}'.
378.Ve
379.Sp
380If not overloaded, the argument will be dereferenced \fIas is\fR, thus
381should be of correct type. These functions should return a reference
382of correct type, or another object with overloaded dereferencing.
383.Sp
384As a special case if the overload returns the object itself then it
385will be used directly (provided it is the correct type).
386.Sp
387The dereference operators must be specified explicitly they will not be passed to
388\&\*(L"nomethod\*(R".
389.IP "\(bu \fISpecial\fR" 5
390.IX Item "Special"
391.Vb 1
392\& "nomethod", "fallback", "=",
393.Ve
394.Sp
395see "\s-1SPECIAL\s0 \s-1SYMBOLS\s0 \s-1FOR\s0 \f(CW\*(C`use overload\*(C'\fR".
396.PP
397See \*(L"Fallback\*(R" for an explanation of when a missing method can be
398autogenerated.
399.PP
400A computer-readable form of the above table is available in the hash
401\&\f(CW%overload::ops\fR, with values being space-separated lists of names:
402.PP
403.Vb 13
404\& with_assign => '+ - * / % ** << >> x .',
405\& assign => '+= -= *= /= %= **= <<= >>= x= .=',
406\& num_comparison => '< <= > >= == !=',
407\& '3way_comparison'=> '<=> cmp',
408\& str_comparison => 'lt le gt ge eq ne',
409\& binary => '& | ^',
410\& unary => 'neg ! ~',
411\& mutators => '++ --',
412\& func => 'atan2 cos sin exp abs log sqrt',
413\& conversion => 'bool "" 0+',
414\& iterators => '<>',
415\& dereferencing => '${} @{} %{} &{} *{}',
416\& special => 'nomethod fallback ='
417.Ve
418.Sh "Inheritance and overloading"
419.IX Subsection "Inheritance and overloading"
420Inheritance interacts with overloading in two ways.
421.ie n .IP "Strings as values of ""use overload"" directive" 4
422.el .IP "Strings as values of \f(CWuse overload\fR directive" 4
423.IX Item "Strings as values of use overload directive"
424If \f(CW\*(C`value\*(C'\fR in
425.Sp
426.Vb 1
427\& use overload key => value;
428.Ve
429.Sp
430is a string, it is interpreted as a method name.
431.IP "Overloading of an operation is inherited by derived classes" 4
432.IX Item "Overloading of an operation is inherited by derived classes"
433Any class derived from an overloaded class is also overloaded. The
434set of overloaded methods is the union of overloaded methods of all
435the ancestors. If some method is overloaded in several ancestor, then
436which description will be used is decided by the usual inheritance
437rules:
438.Sp
439If \f(CW\*(C`A\*(C'\fR inherits from \f(CW\*(C`B\*(C'\fR and \f(CW\*(C`C\*(C'\fR (in this order), \f(CW\*(C`B\*(C'\fR overloads
440\&\f(CW\*(C`+\*(C'\fR with \f(CW\*(C`\e&D::plus_sub\*(C'\fR, and \f(CW\*(C`C\*(C'\fR overloads \f(CW\*(C`+\*(C'\fR by \f(CW"plus_meth"\fR,
441then the subroutine \f(CW\*(C`D::plus_sub\*(C'\fR will be called to implement
442operation \f(CW\*(C`+\*(C'\fR for an object in package \f(CW\*(C`A\*(C'\fR.
443.PP
444Note that since the value of the \f(CW\*(C`fallback\*(C'\fR key is not a subroutine,
445its inheritance is not governed by the above rules. In the current
446implementation, the value of \f(CW\*(C`fallback\*(C'\fR in the first overloaded
447ancestor is used, but this is accidental and subject to change.
448.ie n .SH "SPECIAL SYMBOLS FOR ""use overload"""
449.el .SH "SPECIAL SYMBOLS FOR \f(CWuse overload\fP"
450.IX Header "SPECIAL SYMBOLS FOR use overload"
451Three keys are recognized by Perl that are not covered by the above
452description.
453.Sh "Last Resort"
454.IX Subsection "Last Resort"
455\&\f(CW"nomethod"\fR should be followed by a reference to a function of four
456parameters. If defined, it is called when the overloading mechanism
457cannot find a method for some operation. The first three arguments of
458this function coincide with the arguments for the corresponding method if
459it were found, the fourth argument is the symbol
460corresponding to the missing method. If several methods are tried,
461the last one is used. Say, \f(CW\*(C`1\-$a\*(C'\fR can be equivalent to
462.PP
463.Vb 1
464\& &nomethodMethod($a,1,1,"-")
465.Ve
466.PP
467if the pair \f(CW"nomethod" => "nomethodMethod"\fR was specified in the
468\&\f(CW\*(C`use overload\*(C'\fR directive.
469.PP
470The \f(CW"nomethod"\fR mechanism is \fInot\fR used for the dereference operators
471( ${} @{} %{} &{} *{} ).
472.PP
473If some operation cannot be resolved, and there is no function
474assigned to \f(CW"nomethod"\fR, then an exception will be raised via \fIdie()\fR\-\-
475unless \f(CW"fallback"\fR was specified as a key in \f(CW\*(C`use overload\*(C'\fR directive.
476.Sh "Fallback"
477.IX Subsection "Fallback"
478The key \f(CW"fallback"\fR governs what to do if a method for a particular
479operation is not found. Three different cases are possible depending on
480the value of \f(CW"fallback"\fR:
481.ie n .IP "\(bu ""undef""" 16
482.el .IP "\(bu \f(CWundef\fR" 16
483.IX Item "undef"
484Perl tries to use a
485substituted method (see \*(L"\s-1MAGIC\s0 \s-1AUTOGENERATION\s0\*(R"). If this fails, it
486then tries to calls \f(CW"nomethod"\fR value; if missing, an exception
487will be raised.
488.IP "\(bu \s-1TRUE\s0" 16
489.IX Item "TRUE"
490The same as for the \f(CW\*(C`undef\*(C'\fR value, but no exception is raised. Instead,
491it silently reverts to what it would have done were there no \f(CW\*(C`use overload\*(C'\fR
492present.
493.IP "\(bu defined, but \s-1FALSE\s0" 16
494.IX Item "defined, but FALSE"
495No autogeneration is tried. Perl tries to call
496\&\f(CW"nomethod"\fR value, and if this is missing, raises an exception.
497.PP
498\&\fBNote.\fR \f(CW"fallback"\fR inheritance via \f(CW@ISA\fR is not carved in stone
499yet, see \*(L"Inheritance and overloading\*(R".
500.Sh "Copy Constructor"
501.IX Subsection "Copy Constructor"
502The value for \f(CW"="\fR is a reference to a function with three
503arguments, i.e., it looks like the other values in \f(CW\*(C`use
504overload\*(C'\fR. However, it does not overload the Perl assignment
505operator. This would go against Camel hair.
506.PP
507This operation is called in the situations when a mutator is applied
508to a reference that shares its object with some other reference, such
509as
510.PP
511.Vb 2
512\& $a=$b;
513\& ++$a;
514.Ve
515.PP
516To make this change \f(CW$a\fR and not change \f(CW$b\fR, a copy of \f(CW$$a\fR is made,
517and \f(CW$a\fR is assigned a reference to this new object. This operation is
518done during execution of the \f(CW\*(C`++$a\*(C'\fR, and not during the assignment,
519(so before the increment \f(CW$$a\fR coincides with \f(CW$$b\fR). This is only
520done if \f(CW\*(C`++\*(C'\fR is expressed via a method for \f(CW'++'\fR or \f(CW'+='\fR (or
521\&\f(CW\*(C`nomethod\*(C'\fR). Note that if this operation is expressed via \f(CW'+'\fR
522a nonmutator, i.e., as in
523.PP
524.Vb 2
525\& $a=$b;
526\& $a=$a+1;
527.Ve
528.PP
529then \f(CW$a\fR does not reference a new copy of \f(CW$$a\fR, since $$a does not
530appear as lvalue when the above code is executed.
531.PP
532If the copy constructor is required during the execution of some mutator,
533but a method for \f(CW'='\fR was not specified, it can be autogenerated as a
534string copy if the object is a plain scalar.
535.IP "\fBExample\fR" 5
536.IX Item "Example"
537The actually executed code for
538.Sp
539.Vb 3
540\& $a=$b;
541\& Something else which does not modify $a or $b....
542\& ++$a;
543.Ve
544.Sp
545may be
546.Sp
547.Vb 4
548\& $a=$b;
549\& Something else which does not modify $a or $b....
550\& $a = $a->clone(undef,"");
551\& $a->incr(undef,"");
552.Ve
553.Sp
554if \f(CW$b\fR was mathemagical, and \f(CW'++'\fR was overloaded with \f(CW\*(C`\e&incr\*(C'\fR,
555\&\f(CW'='\fR was overloaded with \f(CW\*(C`\e&clone\*(C'\fR.
556.PP
557Same behaviour is triggered by \f(CW\*(C`$b = $a++\*(C'\fR, which is consider a synonym for
558\&\f(CW\*(C`$b = $a; ++$a\*(C'\fR.
559.SH "MAGIC AUTOGENERATION"
560.IX Header "MAGIC AUTOGENERATION"
561If a method for an operation is not found, and the value for \f(CW"fallback"\fR is
562\&\s-1TRUE\s0 or undefined, Perl tries to autogenerate a substitute method for
563the missing operation based on the defined operations. Autogenerated method
564substitutions are possible for the following operations:
565.IP "\fIAssignment forms of arithmetic operations\fR" 16
566.IX Item "Assignment forms of arithmetic operations"
567\&\f(CW\*(C`$a+=$b\*(C'\fR can use the method for \f(CW"+"\fR if the method for \f(CW"+="\fR
568is not defined.
569.IP "\fIConversion operations\fR" 16
570.IX Item "Conversion operations"
571String, numeric, and boolean conversion are calculated in terms of one
572another if not all of them are defined.
573.IP "\fIIncrement and decrement\fR" 16
574.IX Item "Increment and decrement"
575The \f(CW\*(C`++$a\*(C'\fR operation can be expressed in terms of \f(CW\*(C`$a+=1\*(C'\fR or \f(CW\*(C`$a+1\*(C'\fR,
576and \f(CW\*(C`$a\-\-\*(C'\fR in terms of \f(CW\*(C`$a\-=1\*(C'\fR and \f(CW\*(C`$a\-1\*(C'\fR.
577.ie n .IP """abs($a)""" 16
578.el .IP "\f(CWabs($a)\fR" 16
579.IX Item "abs($a)"
580can be expressed in terms of \f(CW\*(C`$a<0\*(C'\fR and \f(CW\*(C`\-$a\*(C'\fR (or \f(CW\*(C`0\-$a\*(C'\fR).
581.IP "\fIUnary minus\fR" 16
582.IX Item "Unary minus"
583can be expressed in terms of subtraction.
584.IP "\fINegation\fR" 16
585.IX Item "Negation"
586\&\f(CW\*(C`!\*(C'\fR and \f(CW\*(C`not\*(C'\fR can be expressed in terms of boolean conversion, or
587string or numerical conversion.
588.IP "\fIConcatenation\fR" 16
589.IX Item "Concatenation"
590can be expressed in terms of string conversion.
591.IP "\fIComparison operations\fR" 16
592.IX Item "Comparison operations"
593can be expressed in terms of its \*(L"spaceship\*(R" counterpart: either
594\&\f(CW\*(C`<=>\*(C'\fR or \f(CW\*(C`cmp\*(C'\fR:
595.Sp
596.Vb 2
597\& <, >, <=, >=, ==, != in terms of <=>
598\& lt, gt, le, ge, eq, ne in terms of cmp
599.Ve
600.IP "\fIIterator\fR" 16
601.IX Item "Iterator"
602.Vb 1
603\& <> in terms of builtin operations
604.Ve
605.IP "\fIDereferencing\fR" 16
606.IX Item "Dereferencing"
607.Vb 1
608\& ${} @{} %{} &{} *{} in terms of builtin operations
609.Ve
610.IP "\fICopy operator\fR" 16
611.IX Item "Copy operator"
612can be expressed in terms of an assignment to the dereferenced value, if this
613value is a scalar and not a reference.
614.SH "Losing overloading"
615.IX Header "Losing overloading"
616The restriction for the comparison operation is that even if, for example,
617`\f(CW\*(C`cmp\*(C'\fR' should return a blessed reference, the autogenerated `\f(CW\*(C`lt\*(C'\fR'
618function will produce only a standard logical value based on the
619numerical value of the result of `\f(CW\*(C`cmp\*(C'\fR'. In particular, a working
620numeric conversion is needed in this case (possibly expressed in terms of
621other conversions).
622.PP
623Similarly, \f(CW\*(C`.=\*(C'\fR and \f(CW\*(C`x=\*(C'\fR operators lose their mathemagical properties
624if the string conversion substitution is applied.
625.PP
626When you \fIchop()\fR a mathemagical object it is promoted to a string and its
627mathemagical properties are lost. The same can happen with other
628operations as well.
629.SH "Run-time Overloading"
630.IX Header "Run-time Overloading"
631Since all \f(CW\*(C`use\*(C'\fR directives are executed at compile\-time, the only way to
632change overloading during run-time is to
633.PP
634.Vb 1
635\& eval 'use overload "+" => \e&addmethod';
636.Ve
637.PP
638You can also use
639.PP
640.Vb 1
641\& eval 'no overload "+", "--", "<="';
642.Ve
643.PP
644though the use of these constructs during run-time is questionable.
645.SH "Public functions"
646.IX Header "Public functions"
647Package \f(CW\*(C`overload.pm\*(C'\fR provides the following public functions:
648.IP "overload::StrVal(arg)" 5
649.IX Item "overload::StrVal(arg)"
650Gives string value of \f(CW\*(C`arg\*(C'\fR as in absence of stringify overloading.
651.IP "overload::Overloaded(arg)" 5
652.IX Item "overload::Overloaded(arg)"
653Returns true if \f(CW\*(C`arg\*(C'\fR is subject to overloading of some operations.
654.IP "overload::Method(obj,op)" 5
655.IX Item "overload::Method(obj,op)"
656Returns \f(CW\*(C`undef\*(C'\fR or a reference to the method that implements \f(CW\*(C`op\*(C'\fR.
657.SH "Overloading constants"
658.IX Header "Overloading constants"
659For some application Perl parser mangles constants too much. It is possible
660to hook into this process via \fIoverload::constant()\fR and \fIoverload::remove_constant()\fR
661functions.
662.PP
663These functions take a hash as an argument. The recognized keys of this hash
664are
665.IP "integer" 8
666.IX Item "integer"
667to overload integer constants,
668.IP "float" 8
669.IX Item "float"
670to overload floating point constants,
671.IP "binary" 8
672.IX Item "binary"
673to overload octal and hexadecimal constants,
674.IP "q" 8
675.IX Item "q"
676to overload \f(CW\*(C`q\*(C'\fR\-quoted strings, constant pieces of \f(CW\*(C`qq\*(C'\fR\- and \f(CW\*(C`qx\*(C'\fR\-quoted
677strings and here\-documents,
678.IP "qr" 8
679.IX Item "qr"
680to overload constant pieces of regular expressions.
681.PP
682The corresponding values are references to functions which take three arguments:
683the first one is the \fIinitial\fR string form of the constant, the second one
684is how Perl interprets this constant, the third one is how the constant is used.
685Note that the initial string form does not
686contain string delimiters, and has backslashes in backslash-delimiter
687combinations stripped (thus the value of delimiter is not relevant for
688processing of this string). The return value of this function is how this
689constant is going to be interpreted by Perl. The third argument is undefined
690unless for overloaded \f(CW\*(C`q\*(C'\fR\- and \f(CW\*(C`qr\*(C'\fR\- constants, it is \f(CW\*(C`q\*(C'\fR in single-quote
691context (comes from strings, regular expressions, and single-quote \s-1HERE\s0
692documents), it is \f(CW\*(C`tr\*(C'\fR for arguments of \f(CW\*(C`tr\*(C'\fR/\f(CW\*(C`y\*(C'\fR operators,
693it is \f(CW\*(C`s\*(C'\fR for right-hand side of \f(CW\*(C`s\*(C'\fR\-operator, and it is \f(CW\*(C`qq\*(C'\fR otherwise.
694.PP
695Since an expression \f(CW"ab$cd,,"\fR is just a shortcut for \f(CW'ab' . $cd . ',,'\fR,
696it is expected that overloaded constant strings are equipped with reasonable
697overloaded catenation operator, otherwise absurd results will result.
698Similarly, negative numbers are considered as negations of positive constants.
699.PP
700Note that it is probably meaningless to call the functions \fIoverload::constant()\fR
701and \fIoverload::remove_constant()\fR from anywhere but \fIimport()\fR and \fIunimport()\fR methods.
702From these methods they may be called as
703.PP
704.Vb 6
705\& sub import {
706\& shift;
707\& return unless @_;
708\& die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
709\& overload::constant integer => sub {Math::BigInt->new(shift)};
710\& }
711.Ve
712.PP
713\&\fB\s-1BUGS\s0\fR Currently overloaded-ness of constants does not propagate
714into \f(CW\*(C`eval '...'\*(C'\fR.
715.SH "IMPLEMENTATION"
716.IX Header "IMPLEMENTATION"
717What follows is subject to change \s-1RSN\s0.
718.PP
719The table of methods for all operations is cached in magic for the
720symbol table hash for the package. The cache is invalidated during
721processing of \f(CW\*(C`use overload\*(C'\fR, \f(CW\*(C`no overload\*(C'\fR, new function
722definitions, and changes in \f(CW@ISA\fR. However, this invalidation remains
723unprocessed until the next \f(CW\*(C`bless\*(C'\fRing into the package. Hence if you
724want to change overloading structure dynamically, you'll need an
725additional (fake) \f(CW\*(C`bless\*(C'\fRing to update the table.
726.PP
727(Every SVish thing has a magic queue, and magic is an entry in that
728queue. This is how a single variable may participate in multiple
729forms of magic simultaneously. For instance, environment variables
730regularly have two forms at once: their \f(CW%ENV\fR magic and their taint
731magic. However, the magic which implements overloading is applied to
732the stashes, which are rarely used directly, thus should not slow down
733Perl.)
734.PP
735If an object belongs to a package using overload, it carries a special
736flag. Thus the only speed penalty during arithmetic operations without
737overloading is the checking of this flag.
738.PP
739In fact, if \f(CW\*(C`use overload\*(C'\fR is not present, there is almost no overhead
740for overloadable operations, so most programs should not suffer
741measurable performance penalties. A considerable effort was made to
742minimize the overhead when overload is used in some package, but the
743arguments in question do not belong to packages using overload. When
744in doubt, test your speed with \f(CW\*(C`use overload\*(C'\fR and without it. So far
745there have been no reports of substantial speed degradation if Perl is
746compiled with optimization turned on.
747.PP
748There is no size penalty for data if overload is not used. The only
749size penalty if overload is used in some package is that \fIall\fR the
750packages acquire a magic during the next \f(CW\*(C`bless\*(C'\fRing into the
751package. This magic is three-words-long for packages without
752overloading, and carries the cache table if the package is overloaded.
753.PP
754Copying (\f(CW\*(C`$a=$b\*(C'\fR) is shallow; however, a one-level-deep copying is
755carried out before any operation that can imply an assignment to the
756object \f(CW$a\fR (or \f(CW$b\fR) refers to, like \f(CW\*(C`$a++\*(C'\fR. You can override this
757behavior by defining your own copy constructor (see \*(L"Copy Constructor\*(R").
758.PP
759It is expected that arguments to methods that are not explicitly supposed
760to be changed are constant (but this is not enforced).
761.SH "Metaphor clash"
762.IX Header "Metaphor clash"
763One may wonder why the semantic of overloaded \f(CW\*(C`=\*(C'\fR is so counter intuitive.
764If it \fIlooks\fR counter intuitive to you, you are subject to a metaphor
765clash.
766.PP
767Here is a Perl object metaphor:
768.PP
769\&\fI object is a reference to blessed data\fR
770.PP
771and an arithmetic metaphor:
772.PP
773\&\fI object is a thing by itself\fR.
774.PP
775The \fImain\fR problem of overloading \f(CW\*(C`=\*(C'\fR is the fact that these metaphors
776imply different actions on the assignment \f(CW\*(C`$a = $b\*(C'\fR if \f(CW$a\fR and \f(CW$b\fR are
777objects. Perl-think implies that \f(CW$a\fR becomes a reference to whatever
778\&\f(CW$b\fR was referencing. Arithmetic-think implies that the value of \*(L"object\*(R"
779\&\f(CW$a\fR is changed to become the value of the object \f(CW$b\fR, preserving the fact
780that \f(CW$a\fR and \f(CW$b\fR are separate entities.
781.PP
782The difference is not relevant in the absence of mutators. After
783a Perl-way assignment an operation which mutates the data referenced by \f(CW$a\fR
784would change the data referenced by \f(CW$b\fR too. Effectively, after
785\&\f(CW\*(C`$a = $b\*(C'\fR values of \f(CW$a\fR and \f(CW$b\fR become \fIindistinguishable\fR.
786.PP
787On the other hand, anyone who has used algebraic notation knows the
788expressive power of the arithmetic metaphor. Overloading works hard
789to enable this metaphor while preserving the Perlian way as far as
790possible. Since it is not possible to freely mix two contradicting
791metaphors, overloading allows the arithmetic way to write things \fIas
792far as all the mutators are called via overloaded access only\fR. The
793way it is done is described in \*(L"Copy Constructor\*(R".
794.PP
795If some mutator methods are directly applied to the overloaded values,
796one may need to \fIexplicitly unlink\fR other values which references the
797same value:
798.PP
799.Vb 6
800\& $a = new Data 23;
801\& ...
802\& $b = $a; # $b is "linked" to $a
803\& ...
804\& $a = $a->clone; # Unlink $b from $a
805\& $a->increment_by(4);
806.Ve
807.PP
808Note that overloaded access makes this transparent:
809.PP
810.Vb 3
811\& $a = new Data 23;
812\& $b = $a; # $b is "linked" to $a
813\& $a += 4; # would unlink $b automagically
814.Ve
815.PP
816However, it would not make
817.PP
818.Vb 2
819\& $a = new Data 23;
820\& $a = 4; # Now $a is a plain 4, not 'Data'
821.Ve
822.PP
823preserve \*(L"objectness\*(R" of \f(CW$a\fR. But Perl \fIhas\fR a way to make assignments
824to an object do whatever you want. It is just not the overload, but
825\&\fItie()\fRing interface (see \*(L"tie\*(R" in perlfunc). Adding a \s-1\fIFETCH\s0()\fR method
826which returns the object itself, and \s-1\fISTORE\s0()\fR method which changes the
827value of the object, one can reproduce the arithmetic metaphor in its
828completeness, at least for variables which were \fItie()\fRd from the start.
829.PP
830(Note that a workaround for a bug may be needed, see \*(L"\s-1BUGS\s0\*(R".)
831.SH "Cookbook"
832.IX Header "Cookbook"
833Please add examples to what follows!
834.Sh "Two-face scalars"
835.IX Subsection "Two-face scalars"
836Put this in \fItwo_face.pm\fR in your Perl library directory:
837.PP
838.Vb 6
839\& package two_face; # Scalars with separate string and
840\& # numeric values.
841\& sub new { my $p = shift; bless [@_], $p }
842\& use overload '""' => \e&str, '0+' => \e&num, fallback => 1;
843\& sub num {shift->[1]}
844\& sub str {shift->[0]}
845.Ve
846.PP
847Use it as follows:
848.PP
849.Vb 4
850\& require two_face;
851\& my $seven = new two_face ("vii", 7);
852\& printf "seven=$seven, seven=%d, eight=%d\en", $seven, $seven+1;
853\& print "seven contains `i'\en" if $seven =~ /i/;
854.Ve
855.PP
856(The second line creates a scalar which has both a string value, and a
857numeric value.) This prints:
858.PP
859.Vb 2
860\& seven=vii, seven=7, eight=8
861\& seven contains `i'
862.Ve
863.Sh "Two-face references"
864.IX Subsection "Two-face references"
865Suppose you want to create an object which is accessible as both an
866array reference and a hash reference, similar to the
867pseudo-hash
868builtin Perl type. Let's make it better than a pseudo-hash by
869allowing index 0 to be treated as a normal element.
870.PP
871.Vb 12
872\& package two_refs;
873\& use overload '%{}' => \e&gethash, '@{}' => sub { $ {shift()} };
874\& sub new {
875\& my $p = shift;
876\& bless \e [@_], $p;
877\& }
878\& sub gethash {
879\& my %h;
880\& my $self = shift;
881\& tie %h, ref $self, $self;
882\& \e%h;
883\& }
884.Ve
885.PP
886.Vb 16
887\& sub TIEHASH { my $p = shift; bless \e shift, $p }
888\& my %fields;
889\& my $i = 0;
890\& $fields{$_} = $i++ foreach qw{zero one two three};
891\& sub STORE {
892\& my $self = ${shift()};
893\& my $key = $fields{shift()};
894\& defined $key or die "Out of band access";
895\& $$self->[$key] = shift;
896\& }
897\& sub FETCH {
898\& my $self = ${shift()};
899\& my $key = $fields{shift()};
900\& defined $key or die "Out of band access";
901\& $$self->[$key];
902\& }
903.Ve
904.PP
905Now one can access an object using both the array and hash syntax:
906.PP
907.Vb 3
908\& my $bar = new two_refs 3,4,5,6;
909\& $bar->[2] = 11;
910\& $bar->{two} == 11 or die 'bad hash fetch';
911.Ve
912.PP
913Note several important features of this example. First of all, the
914\&\fIactual\fR type of \f(CW$bar\fR is a scalar reference, and we do not overload
915the scalar dereference. Thus we can get the \fIactual\fR non-overloaded
916contents of \f(CW$bar\fR by just using \f(CW$$bar\fR (what we do in functions which
917overload dereference). Similarly, the object returned by the
918\&\s-1\fITIEHASH\s0()\fR method is a scalar reference.
919.PP
920Second, we create a new tied hash each time the hash syntax is used.
921This allows us not to worry about a possibility of a reference loop,
922which would lead to a memory leak.
923.PP
924Both these problems can be cured. Say, if we want to overload hash
925dereference on a reference to an object which is \fIimplemented\fR as a
926hash itself, the only problem one has to circumvent is how to access
927this \fIactual\fR hash (as opposed to the \fIvirtual\fR hash exhibited by the
928overloaded dereference operator). Here is one possible fetching routine:
929.PP
930.Vb 8
931\& sub access_hash {
932\& my ($self, $key) = (shift, shift);
933\& my $class = ref $self;
934\& bless $self, 'overload::dummy'; # Disable overloading of %{}
935\& my $out = $self->{$key};
936\& bless $self, $class; # Restore overloading
937\& $out;
938\& }
939.Ve
940.PP
941To remove creation of the tied hash on each access, one may an extra
942level of indirection which allows a non-circular structure of references:
943.PP
944.Vb 16
945\& package two_refs1;
946\& use overload '%{}' => sub { ${shift()}->[1] },
947\& '@{}' => sub { ${shift()}->[0] };
948\& sub new {
949\& my $p = shift;
950\& my $a = [@_];
951\& my %h;
952\& tie %h, $p, $a;
953\& bless \e [$a, \e%h], $p;
954\& }
955\& sub gethash {
956\& my %h;
957\& my $self = shift;
958\& tie %h, ref $self, $self;
959\& \e%h;
960\& }
961.Ve
962.PP
963.Vb 16
964\& sub TIEHASH { my $p = shift; bless \e shift, $p }
965\& my %fields;
966\& my $i = 0;
967\& $fields{$_} = $i++ foreach qw{zero one two three};
968\& sub STORE {
969\& my $a = ${shift()};
970\& my $key = $fields{shift()};
971\& defined $key or die "Out of band access";
972\& $a->[$key] = shift;
973\& }
974\& sub FETCH {
975\& my $a = ${shift()};
976\& my $key = $fields{shift()};
977\& defined $key or die "Out of band access";
978\& $a->[$key];
979\& }
980.Ve
981.PP
982Now if \f(CW$baz\fR is overloaded like this, then \f(CW$baz\fR is a reference to a
983reference to the intermediate array, which keeps a reference to an
984actual array, and the access hash. The \fItie()\fRing object for the access
985hash is a reference to a reference to the actual array, so
986.IP "\(bu" 4
987There are no loops of references.
988.IP "\(bu" 4
989Both \*(L"objects\*(R" which are blessed into the class \f(CW\*(C`two_refs1\*(C'\fR are
990references to a reference to an array, thus references to a \fIscalar\fR.
991Thus the accessor expression \f(CW\*(C`$$foo\->[$ind]\*(C'\fR involves no
992overloaded operations.
993.Sh "Symbolic calculator"
994.IX Subsection "Symbolic calculator"
995Put this in \fIsymbolic.pm\fR in your Perl library directory:
996.PP
997.Vb 2
998\& package symbolic; # Primitive symbolic calculator
999\& use overload nomethod => \e&wrap;
1000.Ve
1001.PP
1002.Vb 6
1003\& sub new { shift; bless ['n', @_] }
1004\& sub wrap {
1005\& my ($obj, $other, $inv, $meth) = @_;
1006\& ($obj, $other) = ($other, $obj) if $inv;
1007\& bless [$meth, $obj, $other];
1008\& }
1009.Ve
1010.PP
1011This module is very unusual as overloaded modules go: it does not
1012provide any usual overloaded operators, instead it provides the \*(L"Last Resort\*(R" operator \f(CW\*(C`nomethod\*(C'\fR. In this example the corresponding
1013subroutine returns an object which encapsulates operations done over
1014the objects: \f(CW\*(C`new symbolic 3\*(C'\fR contains \f(CW\*(C`['n', 3]\*(C'\fR, \f(CW\*(C`2 + new
1015symbolic 3\*(C'\fR contains \f(CW\*(C`['+', 2, ['n', 3]]\*(C'\fR.
1016.PP
1017Here is an example of the script which \*(L"calculates\*(R" the side of
1018circumscribed octagon using the above package:
1019.PP
1020.Vb 4
1021\& require symbolic;
1022\& my $iter = 1; # 2**($iter+2) = 8
1023\& my $side = new symbolic 1;
1024\& my $cnt = $iter;
1025.Ve
1026.PP
1027.Vb 4
1028\& while ($cnt--) {
1029\& $side = (sqrt(1 + $side**2) - 1)/$side;
1030\& }
1031\& print "OK\en";
1032.Ve
1033.PP
1034The value of \f(CW$side\fR is
1035.PP
1036.Vb 2
1037\& ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
1038\& undef], 1], ['n', 1]]
1039.Ve
1040.PP
1041Note that while we obtained this value using a nice little script,
1042there is no simple way to \fIuse\fR this value. In fact this value may
1043be inspected in debugger (see perldebug), but ony if
1044\&\f(CW\*(C`bareStringify\*(C'\fR \fBO\fRption is set, and not via \f(CW\*(C`p\*(C'\fR command.
1045.PP
1046If one attempts to print this value, then the overloaded operator
1047\&\f(CW""\fR will be called, which will call \f(CW\*(C`nomethod\*(C'\fR operator. The
1048result of this operator will be stringified again, but this result is
1049again of type \f(CW\*(C`symbolic\*(C'\fR, which will lead to an infinite loop.
1050.PP
1051Add a pretty-printer method to the module \fIsymbolic.pm\fR:
1052.PP
1053.Vb 8
1054\& sub pretty {
1055\& my ($meth, $a, $b) = @{+shift};
1056\& $a = 'u' unless defined $a;
1057\& $b = 'u' unless defined $b;
1058\& $a = $a->pretty if ref $a;
1059\& $b = $b->pretty if ref $b;
1060\& "[$meth $a $b]";
1061\& }
1062.Ve
1063.PP
1064Now one can finish the script by
1065.PP
1066.Vb 1
1067\& print "side = ", $side->pretty, "\en";
1068.Ve
1069.PP
1070The method \f(CW\*(C`pretty\*(C'\fR is doing object-to-string conversion, so it
1071is natural to overload the operator \f(CW""\fR using this method. However,
1072inside such a method it is not necessary to pretty-print the
1073\&\fIcomponents\fR \f(CW$a\fR and \f(CW$b\fR of an object. In the above subroutine
1074\&\f(CW"[$meth $a $b]"\fR is a catenation of some strings and components \f(CW$a\fR
1075and \f(CW$b\fR. If these components use overloading, the catenation operator
1076will look for an overloaded operator \f(CW\*(C`.\*(C'\fR; if not present, it will
1077look for an overloaded operator \f(CW""\fR. Thus it is enough to use
1078.PP
1079.Vb 7
1080\& use overload nomethod => \e&wrap, '""' => \e&str;
1081\& sub str {
1082\& my ($meth, $a, $b) = @{+shift};
1083\& $a = 'u' unless defined $a;
1084\& $b = 'u' unless defined $b;
1085\& "[$meth $a $b]";
1086\& }
1087.Ve
1088.PP
1089Now one can change the last line of the script to
1090.PP
1091.Vb 1
1092\& print "side = $side\en";
1093.Ve
1094.PP
1095which outputs
1096.PP
1097.Vb 1
1098\& side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
1099.Ve
1100.PP
1101and one can inspect the value in debugger using all the possible
1102methods.
1103.PP
1104Something is still amiss: consider the loop variable \f(CW$cnt\fR of the
1105script. It was a number, not an object. We cannot make this value of
1106type \f(CW\*(C`symbolic\*(C'\fR, since then the loop will not terminate.
1107.PP
1108Indeed, to terminate the cycle, the \f(CW$cnt\fR should become false.
1109However, the operator \f(CW\*(C`bool\*(C'\fR for checking falsity is overloaded (this
1110time via overloaded \f(CW""\fR), and returns a long string, thus any object
1111of type \f(CW\*(C`symbolic\*(C'\fR is true. To overcome this, we need a way to
1112compare an object to 0. In fact, it is easier to write a numeric
1113conversion routine.
1114.PP
1115Here is the text of \fIsymbolic.pm\fR with such a routine added (and
1116slightly modified \fIstr()\fR):
1117.PP
1118.Vb 3
1119\& package symbolic; # Primitive symbolic calculator
1120\& use overload
1121\& nomethod => \e&wrap, '""' => \e&str, '0+' => \e&num;
1122.Ve
1123.PP
1124.Vb 31
1125\& sub new { shift; bless ['n', @_] }
1126\& sub wrap {
1127\& my ($obj, $other, $inv, $meth) = @_;
1128\& ($obj, $other) = ($other, $obj) if $inv;
1129\& bless [$meth, $obj, $other];
1130\& }
1131\& sub str {
1132\& my ($meth, $a, $b) = @{+shift};
1133\& $a = 'u' unless defined $a;
1134\& if (defined $b) {
1135\& "[$meth $a $b]";
1136\& } else {
1137\& "[$meth $a]";
1138\& }
1139\& }
1140\& my %subr = ( n => sub {$_[0]},
1141\& sqrt => sub {sqrt $_[0]},
1142\& '-' => sub {shift() - shift()},
1143\& '+' => sub {shift() + shift()},
1144\& '/' => sub {shift() / shift()},
1145\& '*' => sub {shift() * shift()},
1146\& '**' => sub {shift() ** shift()},
1147\& );
1148\& sub num {
1149\& my ($meth, $a, $b) = @{+shift};
1150\& my $subr = $subr{$meth}
1151\& or die "Do not know how to ($meth) in symbolic";
1152\& $a = $a->num if ref $a eq __PACKAGE__;
1153\& $b = $b->num if ref $b eq __PACKAGE__;
1154\& $subr->($a,$b);
1155\& }
1156.Ve
1157.PP
1158All the work of numeric conversion is done in \f(CW%subr\fR and \fInum()\fR. Of
1159course, \f(CW%subr\fR is not complete, it contains only operators used in the
1160example below. Here is the extra-credit question: why do we need an
1161explicit recursion in \fInum()\fR? (Answer is at the end of this section.)
1162.PP
1163Use this module like this:
1164.PP
1165.Vb 4
1166\& require symbolic;
1167\& my $iter = new symbolic 2; # 16-gon
1168\& my $side = new symbolic 1;
1169\& my $cnt = $iter;
1170.Ve
1171.PP
1172.Vb 6
1173\& while ($cnt) {
1174\& $cnt = $cnt - 1; # Mutator `--' not implemented
1175\& $side = (sqrt(1 + $side**2) - 1)/$side;
1176\& }
1177\& printf "%s=%f\en", $side, $side;
1178\& printf "pi=%f\en", $side*(2**($iter+2));
1179.Ve
1180.PP
1181It prints (without so many line breaks)
1182.PP
1183.Vb 4
1184\& [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
1185\& [n 1]] 2]]] 1]
1186\& [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
1187\& pi=3.182598
1188.Ve
1189.PP
1190The above module is very primitive. It does not implement
1191mutator methods (\f(CW\*(C`++\*(C'\fR, \f(CW\*(C`\-=\*(C'\fR and so on), does not do deep copying
1192(not required without mutators!), and implements only those arithmetic
1193operations which are used in the example.
1194.PP
1195To implement most arithmetic operations is easy; one should just use
1196the tables of operations, and change the code which fills \f(CW%subr\fR to
1197.PP
1198.Vb 12
1199\& my %subr = ( 'n' => sub {$_[0]} );
1200\& foreach my $op (split " ", $overload::ops{with_assign}) {
1201\& $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1202\& }
1203\& my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1204\& foreach my $op (split " ", "@overload::ops{ @bins }") {
1205\& $subr{$op} = eval "sub {shift() $op shift()}";
1206\& }
1207\& foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1208\& print "defining `$op'\en";
1209\& $subr{$op} = eval "sub {$op shift()}";
1210\& }
1211.Ve
1212.PP
1213Due to \*(L"Calling Conventions for Mutators\*(R", we do not need anything
1214special to make \f(CW\*(C`+=\*(C'\fR and friends work, except filling \f(CW\*(C`+=\*(C'\fR entry of
1215\&\f(CW%subr\fR, and defining a copy constructor (needed since Perl has no
1216way to know that the implementation of \f(CW'+='\fR does not mutate
1217the argument, compare \*(L"Copy Constructor\*(R").
1218.PP
1219To implement a copy constructor, add \f(CW\*(C`'=' => \e&cpy\*(C'\fR to \f(CW\*(C`use overload\*(C'\fR
1220line, and code (this code assumes that mutators change things one level
1221deep only, so recursive copying is not needed):
1222.PP
1223.Vb 4
1224\& sub cpy {
1225\& my $self = shift;
1226\& bless [@$self], ref $self;
1227\& }
1228.Ve
1229.PP
1230To make \f(CW\*(C`++\*(C'\fR and \f(CW\*(C`\-\-\*(C'\fR work, we need to implement actual mutators,
1231either directly, or in \f(CW\*(C`nomethod\*(C'\fR. We continue to do things inside
1232\&\f(CW\*(C`nomethod\*(C'\fR, thus add
1233.PP
1234.Vb 4
1235\& if ($meth eq '++' or $meth eq '--') {
1236\& @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
1237\& return $obj;
1238\& }
1239.Ve
1240.PP
1241after the first line of \fIwrap()\fR. This is not a most effective
1242implementation, one may consider
1243.PP
1244.Vb 1
1245\& sub inc { $_[0] = bless ['++', shift, 1]; }
1246.Ve
1247.PP
1248instead.
1249.PP
1250As a final remark, note that one can fill \f(CW%subr\fR by
1251.PP
1252.Vb 13
1253\& my %subr = ( 'n' => sub {$_[0]} );
1254\& foreach my $op (split " ", $overload::ops{with_assign}) {
1255\& $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1256\& }
1257\& my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1258\& foreach my $op (split " ", "@overload::ops{ @bins }") {
1259\& $subr{$op} = eval "sub {shift() $op shift()}";
1260\& }
1261\& foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1262\& $subr{$op} = eval "sub {$op shift()}";
1263\& }
1264\& $subr{'++'} = $subr{'+'};
1265\& $subr{'--'} = $subr{'-'};
1266.Ve
1267.PP
1268This finishes implementation of a primitive symbolic calculator in
126950 lines of Perl code. Since the numeric values of subexpressions
1270are not cached, the calculator is very slow.
1271.PP
1272Here is the answer for the exercise: In the case of \fIstr()\fR, we need no
1273explicit recursion since the overloaded \f(CW\*(C`.\*(C'\fR\-operator will fall back
1274to an existing overloaded operator \f(CW""\fR. Overloaded arithmetic
1275operators \fIdo not\fR fall back to numeric conversion if \f(CW\*(C`fallback\*(C'\fR is
1276not explicitly requested. Thus without an explicit recursion \fInum()\fR
1277would convert \f(CW\*(C`['+', $a, $b]\*(C'\fR to \f(CW\*(C`$a + $b\*(C'\fR, which would just rebuild
1278the argument of \fInum()\fR.
1279.PP
1280If you wonder why defaults for conversion are different for \fIstr()\fR and
1281\&\fInum()\fR, note how easy it was to write the symbolic calculator. This
1282simplicity is due to an appropriate choice of defaults. One extra
1283note: due to the explicit recursion \fInum()\fR is more fragile than \fIsym()\fR:
1284we need to explicitly check for the type of \f(CW$a\fR and \f(CW$b\fR. If components
1285\&\f(CW$a\fR and \f(CW$b\fR happen to be of some related type, this may lead to problems.
1286.Sh "\fIReally\fP symbolic calculator"
1287.IX Subsection "Really symbolic calculator"
1288One may wonder why we call the above calculator symbolic. The reason
1289is that the actual calculation of the value of expression is postponed
1290until the value is \fIused\fR.
1291.PP
1292To see it in action, add a method
1293.PP
1294.Vb 5
1295\& sub STORE {
1296\& my $obj = shift;
1297\& $#$obj = 1;
1298\& @$obj->[0,1] = ('=', shift);
1299\& }
1300.Ve
1301.PP
1302to the package \f(CW\*(C`symbolic\*(C'\fR. After this change one can do
1303.PP
1304.Vb 3
1305\& my $a = new symbolic 3;
1306\& my $b = new symbolic 4;
1307\& my $c = sqrt($a**2 + $b**2);
1308.Ve
1309.PP
1310and the numeric value of \f(CW$c\fR becomes 5. However, after calling
1311.PP
1312.Vb 1
1313\& $a->STORE(12); $b->STORE(5);
1314.Ve
1315.PP
1316the numeric value of \f(CW$c\fR becomes 13. There is no doubt now that the module
1317symbolic provides a \fIsymbolic\fR calculator indeed.
1318.PP
1319To hide the rough edges under the hood, provide a \fItie()\fRd interface to the
1320package \f(CW\*(C`symbolic\*(C'\fR (compare with \*(L"Metaphor clash\*(R"). Add methods
1321.PP
1322.Vb 3
1323\& sub TIESCALAR { my $pack = shift; $pack->new(@_) }
1324\& sub FETCH { shift }
1325\& sub nop { } # Around a bug
1326.Ve
1327.PP
1328(the bug is described in \*(L"\s-1BUGS\s0\*(R"). One can use this new interface as
1329.PP
1330.Vb 3
1331\& tie $a, 'symbolic', 3;
1332\& tie $b, 'symbolic', 4;
1333\& $a->nop; $b->nop; # Around a bug
1334.Ve
1335.PP
1336.Vb 1
1337\& my $c = sqrt($a**2 + $b**2);
1338.Ve
1339.PP
1340Now numeric value of \f(CW$c\fR is 5. After \f(CW\*(C`$a = 12; $b = 5\*(C'\fR the numeric value
1341of \f(CW$c\fR becomes 13. To insulate the user of the module add a method
1342.PP
1343.Vb 1
1344\& sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
1345.Ve
1346.PP
1347Now
1348.PP
1349.Vb 3
1350\& my ($a, $b);
1351\& symbolic->vars($a, $b);
1352\& my $c = sqrt($a**2 + $b**2);
1353.Ve
1354.PP
1355.Vb 2
1356\& $a = 3; $b = 4;
1357\& printf "c5 %s=%f\en", $c, $c;
1358.Ve
1359.PP
1360.Vb 2
1361\& $a = 12; $b = 5;
1362\& printf "c13 %s=%f\en", $c, $c;
1363.Ve
1364.PP
1365shows that the numeric value of \f(CW$c\fR follows changes to the values of \f(CW$a\fR
1366and \f(CW$b\fR.
1367.SH "AUTHOR"
1368.IX Header "AUTHOR"
1369Ilya Zakharevich <\fIilya@math.mps.ohio\-state.edu\fR>.
1370.SH "DIAGNOSTICS"
1371.IX Header "DIAGNOSTICS"
1372When Perl is run with the \fB\-Do\fR switch or its equivalent, overloading
1373induces diagnostic messages.
1374.PP
1375Using the \f(CW\*(C`m\*(C'\fR command of Perl debugger (see perldebug) one can
1376deduce which operations are overloaded (and which ancestor triggers
1377this overloading). Say, if \f(CW\*(C`eq\*(C'\fR is overloaded, then the method \f(CW\*(C`(eq\*(C'\fR
1378is shown by debugger. The method \f(CW\*(C`()\*(C'\fR corresponds to the \f(CW\*(C`fallback\*(C'\fR
1379key (in fact a presence of this method shows that this package has
1380overloading enabled, and it is what is used by the \f(CW\*(C`Overloaded\*(C'\fR
1381function of module \f(CW\*(C`overload\*(C'\fR).
1382.PP
1383The module might issue the following warnings:
1384.IP "Odd number of arguments for overload::constant" 4
1385.IX Item "Odd number of arguments for overload::constant"
1386(W) The call to overload::constant contained an odd number of arguments.
1387The arguments should come in pairs.
1388.IP "`%s' is not an overloadable type" 4
1389.IX Item "`%s' is not an overloadable type"
1390(W) You tried to overload a constant type the overload package is unaware of.
1391.IP "`%s' is not a code reference" 4
1392.IX Item "`%s' is not a code reference"
1393(W) The second (fourth, sixth, ...) argument of overload::constant needs
1394to be a code reference. Either an anonymous subroutine, or a reference
1395to a subroutine.
1396.SH "BUGS"
1397.IX Header "BUGS"
1398Because it is used for overloading, the per-package hash \f(CW%OVERLOAD\fR now
1399has a special meaning in Perl. The symbol table is filled with names
1400looking like line\-noise.
1401.PP
1402For the purpose of inheritance every overloaded package behaves as if
1403\&\f(CW\*(C`fallback\*(C'\fR is present (possibly undefined). This may create
1404interesting effects if some package is not overloaded, but inherits
1405from two overloaded packages.
1406.PP
1407Relation between overloading and \fItie()\fRing is broken. Overloading is
1408triggered or not basing on the \fIprevious\fR class of \fItie()\fRd value.
1409.PP
1410This happens because the presence of overloading is checked too early,
1411before any \fItie()\fRd access is attempted. If the \s-1\fIFETCH\s0()\fRed class of the
1412\&\fItie()\fRd value does not change, a simple workaround is to access the value
1413immediately after \fItie()\fRing, so that after this call the \fIprevious\fR class
1414coincides with the current one.
1415.PP
1416\&\fBNeeded:\fR a way to fix this without a speed penalty.
1417.PP
1418Barewords are not covered by overloaded string constants.
1419.PP
1420This document is confusing. There are grammos and misleading language
1421used in places. It would seem a total rewrite is needed.