Profile of /usr/local/lib/perl5/5.10.1/overload.pm

← Index
NYTProf Performance Profile «block view•line view•sub view»
For 01.HTTP.t
Run on Tue May 4 15:25:55 2010
Reported on Tue May 4 15:26:10 2010

File | /usr/local/lib/perl5/5.10.1/overload.pm
Statements Executed | 112
Statement Execution Time | 674µs

Subroutines — ordered by exclusive time
Calls | P | F | Exclusive Time | Inclusive Time | Subroutine
--- | --- | --- | --- | --- | ---
6 | 1 | 1 | 212µs | 214µs | overload::::OVERLOADoverload::OVERLOAD
6 | 6 | 6 | 81µs | 295µs | overload::::importoverload::import
1 | 1 | 1 | 25µs | 140µs | overload::::BEGIN@139overload::BEGIN@139
1 | 1 | 2 | 2µs | 2µs | overload::::CORE:matchoverload::CORE:match (opcode)
0 | 0 | 0 | 0s | 0s | overload::::AddrRefoverload::AddrRef
0 | 0 | 0 | 0s | 0s | overload::::Methodoverload::Method
0 | 0 | 0 | 0s | 0s | overload::::Overloadedoverload::Overloaded
0 | 0 | 0 | 0s | 0s | overload::::OverloadedStringifyoverload::OverloadedStringify
0 | 0 | 0 | 0s | 0s | overload::::constantoverload::constant
0 | 0 | 0 | 0s | 0s | overload::::mycanoverload::mycan
0 | 0 | 0 | 0s | 0s | overload::::niloverload::nil
0 | 0 | 0 | 0s | 0s | overload::::ov_methodoverload::ov_method
0 | 0 | 0 | 0s | 0s | overload::::remove_constantoverload::remove_constant
0 | 0 | 0 | 0s | 0s | overload::::unimportoverload::unimport

Call graph for these subroutines as a Graphviz dot language file.

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