Commit | Line | Data |
---|---|---|
4633a7c4 LW |
1 | package overload; |
2 | ||
da60b1cb | 3 | our $VERSION = '1.18'; |
9d51dcee JK |
4 | |
5 | %ops = ( | |
6 | with_assign => "+ - * / % ** << >> x .", | |
7 | assign => "+= -= *= /= %= **= <<= >>= x= .=", | |
8 | num_comparison => "< <= > >= == !=", | |
9 | '3way_comparison' => "<=> cmp", | |
10 | str_comparison => "lt le gt ge eq ne", | |
11 | binary => '& &= | |= ^ ^=', | |
12 | unary => "neg ! ~", | |
13 | mutators => '++ --', | |
14 | func => "atan2 cos sin exp abs log sqrt int", | |
15 | conversion => 'bool "" 0+ qr', | |
16 | iterators => '<>', | |
17 | filetest => "-X", | |
18 | dereferencing => '${} @{} %{} &{} *{}', | |
19 | matching => '~~', | |
20 | special => 'nomethod fallback =', | |
21 | ); | |
22 | ||
e2a78392 | 23 | my %ops_seen; |
9d51dcee JK |
24 | for $category (keys %ops) { |
25 | $ops_seen{$_}++ for (split /\s+/, $ops{$category}); | |
26 | } | |
b75c8c73 | 27 | |
a6006777 | 28 | sub nil {} |
29 | ||
4633a7c4 LW |
30 | sub OVERLOAD { |
31 | $package = shift; | |
32 | my %arg = @_; | |
a6006777 | 33 | my ($sub, $fb); |
34 | $ {$package . "::OVERLOAD"}{dummy}++; # Register with magic by touching. | |
c989e6a3 | 35 | $fb = ${$package . "::()"}; # preserve old fallback value RT#68196 |
a6006777 | 36 | *{$package . "::()"} = \&nil; # Make it findable via fetchmethod. |
4633a7c4 | 37 | for (keys %arg) { |
a6006777 | 38 | if ($_ eq 'fallback') { |
39 | $fb = $arg{$_}; | |
40 | } else { | |
4e1d8790 FC |
41 | warnings::warnif("overload arg '$_' is invalid") |
42 | unless $ops_seen{$_}; | |
a6006777 | 43 | $sub = $arg{$_}; |
44 | if (not ref $sub and $sub !~ /::/) { | |
44a8e56a | 45 | $ {$package . "::(" . $_} = $sub; |
46 | $sub = \&nil; | |
a6006777 | 47 | } |
1f874cb6 | 48 | #print STDERR "Setting '$ {'package'}::\cO$_' to \\&'$sub'.\n"; |
a6006777 | 49 | *{$package . "::(" . $_} = \&{ $sub }; |
50 | } | |
4633a7c4 | 51 | } |
a6006777 | 52 | ${$package . "::()"} = $fb; # Make it findable too (fallback only). |
4633a7c4 LW |
53 | } |
54 | ||
55 | sub import { | |
56 | $package = (caller())[0]; | |
57 | # *{$package . "::OVERLOAD"} = \&OVERLOAD; | |
58 | shift; | |
59 | $package->overload::OVERLOAD(@_); | |
60 | } | |
61 | ||
62 | sub unimport { | |
63 | $package = (caller())[0]; | |
a6006777 | 64 | ${$package . "::OVERLOAD"}{dummy}++; # Upgrade the table |
4633a7c4 LW |
65 | shift; |
66 | for (@_) { | |
a6006777 | 67 | if ($_ eq 'fallback') { |
68 | undef $ {$package . "::()"}; | |
69 | } else { | |
70 | delete $ {$package . "::"}{"(" . $_}; | |
71 | } | |
4633a7c4 LW |
72 | } |
73 | } | |
74 | ||
75 | sub Overloaded { | |
a6006777 | 76 | my $package = shift; |
77 | $package = ref $package if ref $package; | |
e6bb0a40 | 78 | mycan ($package, '()'); |
4633a7c4 LW |
79 | } |
80 | ||
44a8e56a | 81 | sub ov_method { |
82 | my $globref = shift; | |
83 | return undef unless $globref; | |
84 | my $sub = \&{*$globref}; | |
ca610257 FC |
85 | no overloading; |
86 | return $sub if !ref $sub or $sub != \&nil; | |
44a8e56a | 87 | return shift->can($ {*$globref}); |
88 | } | |
89 | ||
4633a7c4 | 90 | sub OverloadedStringify { |
a6006777 | 91 | my $package = shift; |
92 | $package = ref $package if ref $package; | |
44a8e56a | 93 | #$package->can('(""') |
ee239bfe IZ |
94 | ov_method mycan($package, '(""'), $package |
95 | or ov_method mycan($package, '(0+'), $package | |
96 | or ov_method mycan($package, '(bool'), $package | |
97 | or ov_method mycan($package, '(nomethod'), $package; | |
4633a7c4 LW |
98 | } |
99 | ||
100 | sub Method { | |
a6006777 | 101 | my $package = shift; |
05a4b9b1 | 102 | if(ref $package) { |
4de05ceb RGS |
103 | local $@; |
104 | local $!; | |
105 | require Scalar::Util; | |
05a4b9b1 BB |
106 | $package = Scalar::Util::blessed($package); |
107 | return undef if !defined $package; | |
108 | } | |
44a8e56a | 109 | #my $meth = $package->can('(' . shift); |
110 | ov_method mycan($package, '(' . shift), $package; | |
111 | #return $meth if $meth ne \&nil; | |
112 | #return $ {*{$meth}}; | |
4633a7c4 LW |
113 | } |
114 | ||
115 | sub AddrRef { | |
4403f043 FC |
116 | no overloading; |
117 | "$_[0]"; | |
4633a7c4 LW |
118 | } |
119 | ||
1b1d102f | 120 | *StrVal = *AddrRef; |
4633a7c4 | 121 | |
44a8e56a | 122 | sub mycan { # Real can would leave stubs. |
123 | my ($package, $meth) = @_; | |
e1a479c5 | 124 | |
1e9bd118 NC |
125 | local $@; |
126 | local $!; | |
127 | require mro; | |
128 | ||
e1a479c5 BB |
129 | my $mro = mro::get_linear_isa($package); |
130 | foreach my $p (@$mro) { | |
131 | my $fqmeth = $p . q{::} . $meth; | |
132 | return \*{$fqmeth} if defined &{$fqmeth}; | |
44a8e56a | 133 | } |
e1a479c5 | 134 | |
44a8e56a | 135 | return undef; |
136 | } | |
137 | ||
b3ac6de7 | 138 | %constants = ( |
9cfe5470 RGS |
139 | 'integer' => 0x1000, # HINT_NEW_INTEGER |
140 | 'float' => 0x2000, # HINT_NEW_FLOAT | |
141 | 'binary' => 0x4000, # HINT_NEW_BINARY | |
142 | 'q' => 0x8000, # HINT_NEW_STRING | |
143 | 'qr' => 0x10000, # HINT_NEW_RE | |
b3ac6de7 IZ |
144 | ); |
145 | ||
6b82e2f5 | 146 | use warnings::register; |
b3ac6de7 IZ |
147 | sub constant { |
148 | # Arguments: what, sub | |
149 | while (@_) { | |
6b82e2f5 | 150 | if (@_ == 1) { |
4498a751 | 151 | warnings::warnif ("Odd number of arguments for overload::constant"); |
6b82e2f5 A |
152 | last; |
153 | } | |
154 | elsif (!exists $constants {$_ [0]}) { | |
1f874cb6 | 155 | warnings::warnif ("'$_[0]' is not an overloadable type"); |
6b82e2f5 | 156 | } |
1e70e886 | 157 | elsif (!ref $_ [1] || "$_[1]" !~ /(^|=)CODE\(0x[0-9a-f]+\)$/) { |
6b82e2f5 A |
158 | # Can't use C<ref $_[1] eq "CODE"> above as code references can be |
159 | # blessed, and C<ref> would return the package the ref is blessed into. | |
160 | if (warnings::enabled) { | |
6b82e2f5 | 161 | $_ [1] = "undef" unless defined $_ [1]; |
1f874cb6 | 162 | warnings::warn ("'$_[1]' is not a code reference"); |
6b82e2f5 A |
163 | } |
164 | } | |
165 | else { | |
166 | $^H{$_[0]} = $_[1]; | |
f22a2069 | 167 | $^H |= $constants{$_[0]}; |
6b82e2f5 | 168 | } |
b3ac6de7 IZ |
169 | shift, shift; |
170 | } | |
171 | } | |
172 | ||
173 | sub remove_constant { | |
174 | # Arguments: what, sub | |
175 | while (@_) { | |
176 | delete $^H{$_[0]}; | |
177 | $^H &= ~ $constants{$_[0]}; | |
178 | shift, shift; | |
179 | } | |
180 | } | |
181 | ||
4633a7c4 LW |
182 | 1; |
183 | ||
184 | __END__ | |
185 | ||
b267980d | 186 | =head1 NAME |
4633a7c4 | 187 | |
7adf7a02 | 188 | overload - Package for overloading Perl operations |
4633a7c4 LW |
189 | |
190 | =head1 SYNOPSIS | |
191 | ||
192 | package SomeThing; | |
193 | ||
b267980d | 194 | use overload |
4633a7c4 LW |
195 | '+' => \&myadd, |
196 | '-' => \&mysub; | |
197 | # etc | |
198 | ... | |
199 | ||
200 | package main; | |
2b393bf4 | 201 | $a = SomeThing->new( 57 ); |
0e0f0835 | 202 | $b = 5 + $a; |
4633a7c4 LW |
203 | ... |
204 | if (overload::Overloaded $b) {...} | |
205 | ... | |
206 | $strval = overload::StrVal $b; | |
207 | ||
4633a7c4 LW |
208 | =head1 DESCRIPTION |
209 | ||
caf82a01 YST |
210 | This pragma allows overloading of Perl's operators for a class. |
211 | To overload built-in functions, see L<perlsub/Overriding Built-in Functions> instead. | |
212 | ||
0e0f0835 | 213 | =head2 Fundamentals |
4633a7c4 | 214 | |
0e0f0835 | 215 | =head3 Declaration |
4633a7c4 | 216 | |
0e0f0835 MB |
217 | Arguments of the C<use overload> directive are (key, value) pairs. |
218 | For the full set of legal keys, see L<Overloadable Operations> below. | |
ee239bfe | 219 | |
0e0f0835 MB |
220 | Operator implementations (the values) can be subroutines, |
221 | references to subroutines, or anonymous subroutines | |
222 | - in other words, anything legal inside a C<&{ ... }> call. | |
223 | Values specified as strings are interpreted as method names. | |
224 | Thus | |
ee239bfe | 225 | |
0e0f0835 MB |
226 | package Number; |
227 | use overload | |
228 | "-" => "minus", | |
229 | "*=" => \&muas, | |
230 | '""' => sub { ...; }; | |
ee239bfe | 231 | |
0e0f0835 MB |
232 | declares that subtraction is to be implemented by method C<minus()> |
233 | in the class C<Number> (or one of its base classes), | |
234 | and that the function C<Number::muas()> is to be used for the | |
235 | assignment form of multiplication, C<*=>. | |
236 | It also defines an anonymous subroutine to implement stringification: | |
237 | this is called whenever an object blessed into the package C<Number> | |
238 | is used in a string context (this subroutine might, for example, | |
239 | return the number as a Roman numeral). | |
ee239bfe | 240 | |
0e0f0835 | 241 | =head3 Calling Conventions and Magic Autogeneration |
ee239bfe | 242 | |
0e0f0835 MB |
243 | The following sample implementation of C<minus()> (which assumes |
244 | that C<Number> objects are simply blessed references to scalars) | |
245 | illustrates the calling conventions: | |
ee239bfe | 246 | |
0e0f0835 MB |
247 | package Number; |
248 | sub minus { | |
249 | my ($self, $other, $swap) = @_; | |
250 | my $result = $$self - $other; # * | |
251 | $result = -$result if $swap; | |
252 | ref $result ? $result : bless \$result; | |
253 | } | |
254 | # * may recurse once - see table below | |
255 | ||
256 | Three arguments are passed to all subroutines specified in the | |
257 | C<use overload> directive (with one exception - see L</nomethod>). | |
258 | The first of these is the operand providing the overloaded | |
259 | operator implementation - | |
260 | in this case, the object whose C<minus()> method is being called. | |
261 | ||
262 | The second argument is the other operand, or C<undef> in the | |
263 | case of a unary operator. | |
264 | ||
265 | The third argument is set to TRUE if (and only if) the two | |
406f8c25 | 266 | operands have been swapped. Perl may do this to ensure that the |
0e0f0835 MB |
267 | first argument (C<$self>) is an object implementing the overloaded |
268 | operation, in line with general object calling conventions. | |
269 | For example, if C<$x> and C<$y> are C<Number>s: | |
270 | ||
271 | operation | generates a call to | |
272 | ============|====================== | |
273 | $x - $y | minus($x, $y, '') | |
274 | $x - 7 | minus($x, 7, '') | |
275 | 7 - $x | minus($x, 7, 1) | |
276 | ||
277 | Perl may also use C<minus()> to implement other operators which | |
278 | have not been specified in the C<use overload> directive, | |
279 | according to the rules for L<Magic Autogeneration> described later. | |
280 | For example, the C<use overload> above declared no subroutine | |
281 | for any of the operators C<-->, C<neg> (the overload key for | |
406f8c25 | 282 | unary minus), or C<-=>. Thus |
0e0f0835 MB |
283 | |
284 | operation | generates a call to | |
285 | ============|====================== | |
286 | -$x | minus($x, 0, 1) | |
287 | $x-- | minus($x, 1, undef) | |
288 | $x -= 3 | minus($x, 3, undef) | |
289 | ||
290 | Note the C<undef>s: | |
291 | where autogeneration results in the method for a standard | |
292 | operator which does not change either of its operands, such | |
293 | as C<->, being used to implement an operator which changes | |
294 | the operand ("mutators": here, C<--> and C<-=>), | |
295 | Perl passes undef as the third argument. | |
296 | This still evaluates as FALSE, consistent with the fact that | |
297 | the operands have not been swapped, but gives the subroutine | |
298 | a chance to alter its behaviour in these cases. | |
299 | ||
300 | In all the above examples, C<minus()> is required | |
301 | only to return the result of the subtraction: | |
302 | Perl takes care of the assignment to $x. | |
303 | In fact, such methods should I<not> modify their operands, | |
304 | even if C<undef> is passed as the third argument | |
305 | (see L<Overloadable Operations>). | |
306 | ||
307 | The same is not true of implementations of C<++> and C<-->: | |
308 | these are expected to modify their operand. | |
309 | An appropriate implementation of C<--> might look like | |
310 | ||
311 | use overload '--' => "decr", | |
312 | # ... | |
313 | sub decr { --${$_[0]}; } | |
314 | ||
315 | =head3 Mathemagic, Mutators, and Copy Constructors | |
316 | ||
317 | The term 'mathemagic' describes the overloaded implementation | |
318 | of mathematical operators. | |
319 | Mathemagical operations raise an issue. | |
320 | Consider the code: | |
321 | ||
322 | $a = $b; | |
323 | --$a; | |
324 | ||
325 | If C<$a> and C<$b> are scalars then after these statements | |
326 | ||
327 | $a == $b - 1 | |
328 | ||
329 | An object, however, is a reference to blessed data, so if | |
330 | C<$a> and C<$b> are objects then the assignment C<$a = $b> | |
331 | copies only the reference, leaving C<$a> and C<$b> referring | |
332 | to the same object data. | |
333 | One might therefore expect the operation C<--$a> to decrement | |
334 | C<$b> as well as C<$a>. | |
335 | However, this would not be consistent with how we expect the | |
336 | mathematical operators to work. | |
337 | ||
338 | Perl resolves this dilemma by transparently calling a copy | |
339 | constructor before calling a method defined to implement | |
340 | a mutator (C<-->, C<+=>, and so on.). | |
341 | In the above example, when Perl reaches the decrement | |
342 | statement, it makes a copy of the object data in C<$a> and | |
343 | assigns to C<$a> a reference to the copied data. | |
344 | Only then does it call C<decr()>, which alters the copied | |
345 | data, leaving C<$b> unchanged. | |
346 | Thus the object metaphor is preserved as far as possible, | |
347 | while mathemagical operations still work according to the | |
348 | arithmetic metaphor. | |
349 | ||
350 | Note: the preceding paragraph describes what happens when | |
351 | Perl autogenerates the copy constructor for an object based | |
352 | on a scalar. | |
353 | For other cases, see L<Copy Constructor>. | |
ee239bfe | 354 | |
0e0f0835 | 355 | =head2 Overloadable Operations |
ee239bfe | 356 | |
0e0f0835 MB |
357 | The complete list of keys that can be specified in the C<use overload> |
358 | directive are given, separated by spaces, in the values of the | |
359 | hash C<%overload::ops>: | |
ee239bfe | 360 | |
0e0f0835 MB |
361 | with_assign => '+ - * / % ** << >> x .', |
362 | assign => '+= -= *= /= %= **= <<= >>= x= .=', | |
363 | num_comparison => '< <= > >= == !=', | |
364 | '3way_comparison'=> '<=> cmp', | |
365 | str_comparison => 'lt le gt ge eq ne', | |
366 | binary => '& &= | |= ^ ^=', | |
367 | unary => 'neg ! ~', | |
368 | mutators => '++ --', | |
369 | func => 'atan2 cos sin exp abs log sqrt int', | |
370 | conversion => 'bool "" 0+ qr', | |
371 | iterators => '<>', | |
372 | filetest => '-X', | |
373 | dereferencing => '${} @{} %{} &{} *{}', | |
374 | matching => '~~', | |
375 | special => 'nomethod fallback =' | |
ee239bfe | 376 | |
0e0f0835 MB |
377 | Most of the overloadable operators map one-to-one to these keys. |
378 | Exceptions, including additional overloadable operations not | |
379 | apparent from this hash, are included in the notes which follow. | |
ee239bfe | 380 | |
9d51dcee JK |
381 | A warning is issued if an attempt is made to register an operator not found |
382 | above. | |
383 | ||
0e0f0835 | 384 | =over 5 |
ee239bfe | 385 | |
0e0f0835 | 386 | =item * C<not> |
4633a7c4 | 387 | |
0e0f0835 MB |
388 | The operator C<not> is not a valid key for C<use overload>. |
389 | However, if the operator C<!> is overloaded then the same | |
390 | implementation will be used for C<not> | |
391 | (since the two operators differ only in precedence). | |
4633a7c4 | 392 | |
0e0f0835 | 393 | =item * C<neg> |
4633a7c4 | 394 | |
0e0f0835 MB |
395 | The key C<neg> is used for unary minus to disambiguate it from |
396 | binary C<->. | |
4633a7c4 | 397 | |
0e0f0835 | 398 | =item * C<++>, C<--> |
4633a7c4 | 399 | |
0e0f0835 MB |
400 | Assuming they are to behave analogously to Perl's C<++> and C<-->, |
401 | overloaded implementations of these operators are required to | |
402 | mutate their operands. | |
4633a7c4 | 403 | |
0e0f0835 MB |
404 | No distinction is made between prefix and postfix forms of the |
405 | increment and decrement operators: these differ only in the | |
406 | point at which Perl calls the associated subroutine when | |
407 | evaluating an expression. | |
ee239bfe | 408 | |
0e0f0835 | 409 | =item * I<Assignments> |
4633a7c4 | 410 | |
0e0f0835 MB |
411 | += -= *= /= %= **= <<= >>= x= .= |
412 | &= |= ^= | |
4633a7c4 | 413 | |
0e0f0835 MB |
414 | Simple assignment is not overloadable (the C<'='> key is used |
415 | for the L<Copy Constructor>). | |
416 | Perl does have a way to make assignments to an object do whatever | |
417 | you want, but this involves using tie(), not overload - | |
418 | see L<perlfunc/tie> and the L</COOKBOOK> examples below. | |
4633a7c4 | 419 | |
0e0f0835 MB |
420 | The subroutine for the assignment variant of an operator is |
421 | required only to return the result of the operation. | |
422 | It is permitted to change the value of its operand | |
423 | (this is safe because Perl calls the copy constructor first), | |
424 | but this is optional since Perl assigns the returned value to | |
425 | the left-hand operand anyway. | |
4633a7c4 | 426 | |
0e0f0835 MB |
427 | An object that overloads an assignment operator does so only in |
428 | respect of assignments to that object. | |
429 | In other words, Perl never calls the corresponding methods with | |
430 | the third argument (the "swap" argument) set to TRUE. | |
431 | For example, the operation | |
4633a7c4 | 432 | |
0e0f0835 | 433 | $a *= $b |
4633a7c4 | 434 | |
0e0f0835 MB |
435 | cannot lead to C<$b>'s implementation of C<*=> being called, |
436 | even if C<$a> is a scalar. | |
437 | (It can, however, generate a call to C<$b>'s method for C<*>). | |
6dd85743 | 438 | |
0e0f0835 | 439 | =item * I<Non-mutators with a mutator variant> |
4633a7c4 | 440 | |
0e0f0835 MB |
441 | + - * / % ** << >> x . |
442 | & | ^ | |
4633a7c4 | 443 | |
0e0f0835 MB |
444 | As described L<above|"Calling Conventions and Magic Autogeneration">, |
445 | Perl may call methods for operators like C<+> and C<&> in the course | |
446 | of implementing missing operations like C<++>, C<+=>, and C<&=>. | |
447 | While these methods may detect this usage by testing the definedness | |
448 | of the third argument, they should in all cases avoid changing their | |
449 | operands. | |
450 | This is because Perl does not call the copy constructor before | |
451 | invoking these methods. | |
4633a7c4 | 452 | |
0e0f0835 | 453 | =item * C<int> |
4633a7c4 | 454 | |
0e0f0835 MB |
455 | Traditionally, the Perl function C<int> rounds to 0 |
456 | (see L<perlfunc/int>), and so for floating-point-like types one | |
457 | should follow the same semantic. | |
4633a7c4 | 458 | |
0e0f0835 | 459 | =item * I<String, numeric, boolean, and regexp conversions> |
4633a7c4 | 460 | |
0e0f0835 | 461 | "" 0+ bool |
f216259d | 462 | |
0e0f0835 MB |
463 | These conversions are invoked according to context as necessary. |
464 | For example, the subroutine for C<'""'> (stringify) may be used | |
465 | where the overloaded object is passed as an argument to C<print>, | |
466 | and that for C<'bool'> where it is tested in the condition of a flow | |
467 | control statement (like C<while>) or the ternary C<?:> operation. | |
4633a7c4 | 468 | |
0e0f0835 MB |
469 | Of course, in contexts like, for example, C<$obj + 1>, Perl will |
470 | invoke C<$obj>'s implementation of C<+> rather than (in this | |
471 | example) converting C<$obj> to a number using the numify method | |
472 | C<'0+'> (an exception to this is when no method has been provided | |
473 | for C<'+'> and L</fallback> is set to TRUE). | |
4633a7c4 | 474 | |
0e0f0835 MB |
475 | The subroutines for C<'""'>, C<'0+'>, and C<'bool'> can return |
476 | any arbitrary Perl value. | |
477 | If the corresponding operation for this value is overloaded too, | |
478 | the operation will be called again with this value. | |
4633a7c4 | 479 | |
1554e226 | 480 | As a special case if the overload returns the object itself then it will |
406f8c25 | 481 | be used directly. An overloaded conversion returning the object is |
1554e226 DC |
482 | probably a bug, because you're likely to get something that looks like |
483 | C<YourPackage=HASH(0x8172b34)>. | |
484 | ||
0e0f0835 | 485 | qr |
f5284f61 | 486 | |
0e0f0835 MB |
487 | The subroutine for C<'qr'> is used wherever the object is |
488 | interpolated into or used as a regexp, including when it | |
489 | appears on the RHS of a C<=~> or C<!~> operator. | |
f5284f61 | 490 | |
0e0f0835 MB |
491 | C<qr> must return a compiled regexp, or a ref to a compiled regexp |
492 | (such as C<qr//> returns), and any further overloading on the return | |
493 | value will be ignored. | |
494 | ||
495 | =item * I<Iteration> | |
496 | ||
497 | If C<E<lt>E<gt>> is overloaded then the same implementation is used | |
498 | for both the I<read-filehandle> syntax C<E<lt>$varE<gt>> and | |
f5284f61 IZ |
499 | I<globbing> syntax C<E<lt>${var}E<gt>>. |
500 | ||
54f8c773 YST |
501 | B<BUGS> Even in list context, the iterator is currently called only |
502 | once and with scalar context. | |
503 | ||
e2210791 BM |
504 | =item * I<File tests> |
505 | ||
0e0f0835 MB |
506 | The key C<'-X'> is used to specify a subroutine to handle all the |
507 | filetest operators (C<-f>, C<-x>, and so on: see L<perlfunc/-X> for | |
508 | the full list); | |
509 | it is not possible to overload any filetest operator individually. | |
510 | To distinguish them, the letter following the '-' is passed as the | |
511 | second argument (that is, in the slot that for binary operators | |
512 | is used to pass the second operand). | |
e2210791 BM |
513 | |
514 | Calling an overloaded filetest operator does not affect the stat value | |
406f8c25 | 515 | associated with the special filehandle C<_>. It still refers to the |
e2210791 BM |
516 | result of the last C<stat>, C<lstat> or unoverloaded filetest. |
517 | ||
0e0f0835 | 518 | This overload was introduced in Perl 5.12. |
e2210791 | 519 | |
ae20c3aa RGS |
520 | =item * I<Matching> |
521 | ||
b3ed409d CS |
522 | The key C<"~~"> allows you to override the smart matching logic used by |
523 | the C<~~> operator and the switch construct (C<given>/C<when>). See | |
48238296 | 524 | L<perlsyn/Switch Statements> and L<feature>. |
ae20c3aa | 525 | |
0e0f0835 MB |
526 | Unusually, the overloaded implementation of the smart match operator |
527 | does not get full control of the smart match behaviour. | |
528 | In particular, in the following code: | |
0de1c906 DM |
529 | |
530 | package Foo; | |
531 | use overload '~~' => 'match'; | |
532 | ||
533 | my $obj = Foo->new(); | |
534 | $obj ~~ [ 1,2,3 ]; | |
535 | ||
536 | the smart match does I<not> invoke the method call like this: | |
537 | ||
538 | $obj->match([1,2,3],0); | |
539 | ||
540 | rather, the smart match distributive rule takes precedence, so $obj is | |
541 | smart matched against each array element in turn until a match is found, | |
542 | so you may see between one and three of these calls instead: | |
543 | ||
544 | $obj->match(1,0); | |
545 | $obj->match(2,0); | |
546 | $obj->match(3,0); | |
547 | ||
48238296 | 548 | Consult the match table in L<perlop/"Smartmatch Operator"> for |
0de1c906 DM |
549 | details of when overloading is invoked. |
550 | ||
f5284f61 IZ |
551 | =item * I<Dereferencing> |
552 | ||
0e0f0835 MB |
553 | ${} @{} %{} &{} *{} |
554 | ||
555 | If these operators are not explicitly overloaded then they | |
556 | work in the normal way, yielding the underlying scalar, | |
557 | array, or whatever stores the object data (or the appropriate | |
558 | error message if the dereference operator doesn't match it). | |
559 | Defining a catch-all C<'nomethod'> (see L<below|/nomethod>) | |
560 | makes no difference to this as the catch-all function will | |
561 | not be called to implement a missing dereference operator. | |
562 | ||
563 | If a dereference operator is overloaded then it must return a | |
564 | I<reference> of the appropriate type (for example, the | |
565 | subroutine for key C<'${}'> should return a reference to a | |
566 | scalar, not a scalar), or another object which overloads the | |
567 | operator: that is, the subroutine only determines what is | |
568 | dereferenced and the actual dereferencing is left to Perl. | |
569 | As a special case, if the subroutine returns the object itself | |
570 | then it will not be called again - avoiding infinite recursion. | |
b267980d | 571 | |
4633a7c4 LW |
572 | =item * I<Special> |
573 | ||
0e0f0835 | 574 | nomethod fallback = |
4633a7c4 | 575 | |
0e0f0835 | 576 | See L<Special Keys for C<use overload>>. |
4633a7c4 LW |
577 | |
578 | =back | |
579 | ||
0e0f0835 MB |
580 | =head2 Magic Autogeneration |
581 | ||
582 | If a method for an operation is not found then Perl tries to | |
583 | autogenerate a substitute implementation from the operations | |
584 | that have been defined. | |
585 | ||
586 | Note: the behaviour described in this section can be disabled | |
587 | by setting C<fallback> to FALSE (see L</fallback>). | |
588 | ||
589 | In the following tables, numbers indicate priority. | |
590 | For example, the table below states that, | |
591 | if no implementation for C<'!'> has been defined then Perl will | |
592 | implement it using C<'bool'> (that is, by inverting the value | |
593 | returned by the method for C<'bool'>); | |
594 | if boolean conversion is also unimplemented then Perl will | |
595 | use C<'0+'> or, failing that, C<'""'>. | |
596 | ||
597 | operator | can be autogenerated from | |
598 | | | |
599 | | 0+ "" bool . x | |
600 | =========|========================== | |
601 | 0+ | 1 2 | |
602 | "" | 1 2 | |
603 | bool | 1 2 | |
604 | int | 1 2 3 | |
605 | ! | 2 3 1 | |
606 | qr | 2 1 3 | |
607 | . | 2 1 3 | |
608 | x | 2 1 3 | |
609 | .= | 3 2 4 1 | |
610 | x= | 3 2 4 1 | |
611 | <> | 2 1 3 | |
612 | -X | 2 1 3 | |
613 | ||
614 | Note: The iterator (C<'E<lt>E<gt>'>) and file test (C<'-X'>) | |
615 | operators work as normal: if the operand is not a blessed glob or | |
616 | IO reference then it is converted to a string (using the method | |
617 | for C<'""'>, C<'0+'>, or C<'bool'>) to be interpreted as a glob | |
618 | or filename. | |
619 | ||
620 | operator | can be autogenerated from | |
621 | | | |
622 | | < <=> neg -= - | |
623 | =========|========================== | |
624 | neg | 1 | |
625 | -= | 1 | |
626 | -- | 1 2 | |
627 | abs | a1 a2 b1 b2 [*] | |
628 | < | 1 | |
629 | <= | 1 | |
630 | > | 1 | |
631 | >= | 1 | |
632 | == | 1 | |
633 | != | 1 | |
634 | ||
635 | * one from [a1, a2] and one from [b1, b2] | |
636 | ||
637 | Just as numeric comparisons can be autogenerated from the method | |
638 | for C<< '<=>' >>, string comparisons can be autogenerated from | |
639 | that for C<'cmp'>: | |
640 | ||
641 | operators | can be autogenerated from | |
642 | ====================|=========================== | |
643 | lt gt le ge eq ne | cmp | |
644 | ||
645 | Similarly, autogeneration for keys C<'+='> and C<'++'> is analogous | |
646 | to C<'-='> and C<'--'> above: | |
647 | ||
648 | operator | can be autogenerated from | |
649 | | | |
650 | | += + | |
651 | =========|========================== | |
652 | += | 1 | |
653 | ++ | 1 2 | |
654 | ||
655 | And other assignment variations are analogous to | |
656 | C<'+='> and C<'-='> (and similar to C<'.='> and C<'x='> above): | |
657 | ||
658 | operator || *= /= %= **= <<= >>= &= ^= |= | |
659 | -------------------||-------------------------------- | |
660 | autogenerated from || * / % ** << >> & ^ | | |
661 | ||
662 | Note also that the copy constructor (key C<'='>) may be | |
663 | autogenerated, but only for objects based on scalars. | |
664 | See L<Copy Constructor>. | |
665 | ||
666 | =head3 Minimal Set of Overloaded Operations | |
4633a7c4 | 667 | |
0e0f0835 MB |
668 | Since some operations can be automatically generated from others, there is |
669 | a minimal set of operations that need to be overloaded in order to have | |
670 | the complete set of overloaded operations at one's disposal. | |
671 | Of course, the autogenerated operations may not do exactly what the user | |
406f8c25 | 672 | expects. The minimal set is: |
e7ea3e70 | 673 | |
0e0f0835 MB |
674 | + - * / % ** << >> x |
675 | <=> cmp | |
676 | & | ^ ~ | |
677 | atan2 cos sin exp log sqrt int | |
678 | "" 0+ bool | |
679 | ~~ | |
e7ea3e70 | 680 | |
0e0f0835 MB |
681 | Of the conversions, only one of string, boolean or numeric is |
682 | needed because each can be generated from either of the other two. | |
e7ea3e70 | 683 | |
0e0f0835 | 684 | =head2 Special Keys for C<use overload> |
e7ea3e70 | 685 | |
0e0f0835 | 686 | =head3 C<nomethod> |
e7ea3e70 | 687 | |
0e0f0835 MB |
688 | The C<'nomethod'> key is used to specify a catch-all function to |
689 | be called for any operator that is not individually overloaded. | |
690 | The specified function will be passed four parameters. | |
691 | The first three arguments coincide with those that would have been | |
692 | passed to the corresponding method if it had been defined. | |
693 | The fourth argument is the C<use overload> key for that missing | |
694 | method. | |
e7ea3e70 | 695 | |
0e0f0835 | 696 | For example, if C<$a> is an object blessed into a package declaring |
4633a7c4 | 697 | |
0e0f0835 | 698 | use overload 'nomethod' => 'catch_all', # ... |
4633a7c4 | 699 | |
0e0f0835 | 700 | then the operation |
4633a7c4 | 701 | |
0e0f0835 | 702 | 3 + $a |
4633a7c4 | 703 | |
0e0f0835 MB |
704 | could (unless a method is specifically declared for the key |
705 | C<'+'>) result in a call | |
4633a7c4 | 706 | |
0e0f0835 | 707 | catch_all($a, 3, 1, '+') |
4633a7c4 | 708 | |
0e0f0835 | 709 | See L<How Perl Chooses an Operator Implementation>. |
b267980d | 710 | |
0e0f0835 | 711 | =head3 C<fallback> |
b267980d | 712 | |
0e0f0835 MB |
713 | The value assigned to the key C<'fallback'> tells Perl how hard |
714 | it should try to find an alternative way to implement a missing | |
715 | operator. | |
4633a7c4 | 716 | |
0e0f0835 | 717 | =over |
b267980d | 718 | |
0e0f0835 | 719 | =item * defined, but FALSE |
4633a7c4 | 720 | |
0e0f0835 | 721 | use overload "fallback" => 0, # ... ; |
4633a7c4 | 722 | |
0e0f0835 | 723 | This disables L<Magic Autogeneration>. |
4633a7c4 LW |
724 | |
725 | =item * C<undef> | |
726 | ||
0e0f0835 MB |
727 | In the default case where no value is explicitly assigned to |
728 | C<fallback>, magic autogeneration is enabled. | |
4633a7c4 LW |
729 | |
730 | =item * TRUE | |
731 | ||
0e0f0835 MB |
732 | The same as for C<undef>, but if a missing operator cannot be |
733 | autogenerated then, instead of issuing an error message, Perl | |
734 | is allowed to revert to what it would have done for that | |
735 | operator if there had been no C<use overload> directive. | |
4633a7c4 | 736 | |
0e0f0835 MB |
737 | Note: in most cases, particularly the L<Copy Constructor>, |
738 | this is unlikely to be appropriate behaviour. | |
4633a7c4 LW |
739 | |
740 | =back | |
741 | ||
0e0f0835 | 742 | See L<How Perl Chooses an Operator Implementation>. |
4633a7c4 | 743 | |
0e0f0835 | 744 | =head3 Copy Constructor |
4633a7c4 | 745 | |
0e0f0835 MB |
746 | As mentioned L<above|"Mathemagic, Mutators, and Copy Constructors">, |
747 | this operation is called when a mutator is applied to a reference | |
748 | that shares its object with some other reference. | |
749 | For example, if C<$b> is mathemagical, and C<'++'> is overloaded | |
750 | with C<'incr'>, and C<'='> is overloaded with C<'clone'>, then the | |
751 | code | |
4633a7c4 | 752 | |
0e0f0835 MB |
753 | $a = $b; |
754 | # ... (other code which does not modify $a or $b) ... | |
755 | ++$b; | |
4633a7c4 | 756 | |
0e0f0835 | 757 | would be executed in a manner equivalent to |
4633a7c4 | 758 | |
0e0f0835 MB |
759 | $a = $b; |
760 | # ... | |
761 | $b = $b->clone(undef, ""); | |
762 | $b->incr(undef, ""); | |
4633a7c4 | 763 | |
0e0f0835 | 764 | Note: |
4633a7c4 | 765 | |
0e0f0835 | 766 | =over |
4633a7c4 | 767 | |
0e0f0835 | 768 | =item * |
4633a7c4 | 769 | |
0e0f0835 MB |
770 | The subroutine for C<'='> does not overload the Perl assignment |
771 | operator: it is used only to allow mutators to work as described | |
406f8c25 | 772 | here. (See L</Assignments> above.) |
4633a7c4 | 773 | |
0e0f0835 | 774 | =item * |
4633a7c4 | 775 | |
0e0f0835 MB |
776 | As for other operations, the subroutine implementing '=' is passed |
777 | three arguments, though the last two are always C<undef> and C<''>. | |
4633a7c4 | 778 | |
0e0f0835 | 779 | =item * |
4633a7c4 | 780 | |
0e0f0835 MB |
781 | The copy constructor is called only before a call to a function |
782 | declared to implement a mutator, for example, if C<++$b;> in the | |
783 | code above is effected via a method declared for key C<'++'> | |
784 | (or 'nomethod', passed C<'++'> as the fourth argument) or, by | |
785 | autogeneration, C<'+='>. | |
786 | It is not called if the increment operation is effected by a call | |
787 | to the method for C<'+'> since, in the equivalent code, | |
4633a7c4 | 788 | |
0e0f0835 MB |
789 | $a = $b; |
790 | $b = $b + 1; | |
4633a7c4 | 791 | |
0e0f0835 MB |
792 | the data referred to by C<$a> is unchanged by the assignment to |
793 | C<$b> of a reference to new object data. | |
4633a7c4 | 794 | |
0e0f0835 | 795 | =item * |
ee239bfe | 796 | |
0e0f0835 MB |
797 | The copy constructor is not called if Perl determines that it is |
798 | unnecessary because there is no other reference to the data being | |
799 | modified. | |
4633a7c4 | 800 | |
0e0f0835 | 801 | =item * |
4633a7c4 | 802 | |
0e0f0835 MB |
803 | If C<'fallback'> is undefined or TRUE then a copy constructor |
804 | can be autogenerated, but only for objects based on scalars. | |
805 | In other cases it needs to be defined explicitly. | |
806 | Where an object's data is stored as, for example, an array of | |
807 | scalars, the following might be appropriate: | |
4633a7c4 | 808 | |
0e0f0835 | 809 | use overload '=' => sub { bless [ @{$_[0]} ] }, # ... |
4633a7c4 | 810 | |
0e0f0835 | 811 | =item * |
4633a7c4 | 812 | |
0e0f0835 MB |
813 | If C<'fallback'> is TRUE and no copy constructor is defined then, |
814 | for objects not based on scalars, Perl may silently fall back on | |
815 | simple assignment - that is, assignment of the object reference. | |
816 | In effect, this disables the copy constructor mechanism since | |
817 | no new copy of the object data is created. | |
818 | This is almost certainly not what you want. | |
819 | (It is, however, consistent: for example, Perl's fallback for the | |
820 | C<++> operator is to increment the reference itself.) | |
4633a7c4 | 821 | |
0e0f0835 | 822 | =back |
4633a7c4 | 823 | |
0e0f0835 | 824 | =head2 How Perl Chooses an Operator Implementation |
4633a7c4 | 825 | |
0e0f0835 MB |
826 | Which is checked first, C<nomethod> or C<fallback>? |
827 | If the two operands of an operator are of different types and | |
828 | both overload the operator, which implementation is used? | |
829 | The following are the precedence rules: | |
4633a7c4 | 830 | |
0e0f0835 | 831 | =over |
4633a7c4 | 832 | |
0e0f0835 | 833 | =item 1. |
4633a7c4 | 834 | |
0e0f0835 MB |
835 | If the first operand has declared a subroutine to overload the |
836 | operator then use that implementation. | |
4633a7c4 | 837 | |
0e0f0835 | 838 | =item 2. |
4633a7c4 | 839 | |
0e0f0835 MB |
840 | Otherwise, if fallback is TRUE or undefined for the |
841 | first operand then see if the | |
842 | L<rules for autogeneration|"Magic Autogeneration"> | |
843 | allows another of its operators to be used instead. | |
3bc6ec80 | 844 | |
0e0f0835 | 845 | =item 3. |
3bc6ec80 | 846 | |
0e0f0835 MB |
847 | Unless the operator is an assignment (C<+=>, C<-=>, etc.), |
848 | repeat step (1) in respect of the second operand. | |
4633a7c4 | 849 | |
0e0f0835 | 850 | =item 4. |
4633a7c4 | 851 | |
0e0f0835 | 852 | Repeat Step (2) in respect of the second operand. |
4633a7c4 | 853 | |
0e0f0835 | 854 | =item 5. |
1fef88e7 | 855 | |
0e0f0835 | 856 | If the first operand has a "nomethod" method then use that. |
4633a7c4 | 857 | |
0e0f0835 | 858 | =item 6. |
f5284f61 | 859 | |
0e0f0835 | 860 | If the second operand has a "nomethod" method then use that. |
f5284f61 | 861 | |
0e0f0835 | 862 | =item 7. |
f5284f61 | 863 | |
0e0f0835 MB |
864 | If C<fallback> is TRUE for both operands |
865 | then perform the usual operation for the operator, | |
866 | treating the operands as numbers, strings, or booleans | |
867 | as appropriate for the operator (see note). | |
f5284f61 | 868 | |
0e0f0835 | 869 | =item 8. |
4633a7c4 | 870 | |
0e0f0835 | 871 | Nothing worked - die. |
4633a7c4 LW |
872 | |
873 | =back | |
874 | ||
0e0f0835 MB |
875 | Where there is only one operand (or only one operand with |
876 | overloading) the checks in respect of the other operand above are | |
877 | skipped. | |
84fc275b | 878 | |
0e0f0835 MB |
879 | There are exceptions to the above rules for dereference operations |
880 | (which, if Step 1 fails, always fall back to the normal, built-in | |
881 | implementations - see Dereferencing), and for C<~~> (which has its | |
e846f1dc KW |
882 | own set of rules - see C<Matching> under L</Overloadable Operations> |
883 | above). | |
84fc275b | 884 | |
0e0f0835 MB |
885 | Note on Step 7: some operators have a different semantic depending |
886 | on the type of their operands. | |
887 | As there is no way to instruct Perl to treat the operands as, e.g., | |
888 | numbers instead of strings, the result here may not be what you | |
889 | expect. | |
890 | See L<BUGS AND PITFALLS>. | |
84fc275b | 891 | |
0e0f0835 | 892 | =head2 Losing Overloading |
4633a7c4 LW |
893 | |
894 | The restriction for the comparison operation is that even if, for example, | |
1f874cb6 | 895 | C<cmp> should return a blessed reference, the autogenerated C<lt> |
4633a7c4 | 896 | function will produce only a standard logical value based on the |
1f874cb6 | 897 | numerical value of the result of C<cmp>. In particular, a working |
4633a7c4 LW |
898 | numeric conversion is needed in this case (possibly expressed in terms of |
899 | other conversions). | |
900 | ||
901 | Similarly, C<.=> and C<x=> operators lose their mathemagical properties | |
902 | if the string conversion substitution is applied. | |
903 | ||
904 | When you chop() a mathemagical object it is promoted to a string and its | |
905 | mathemagical properties are lost. The same can happen with other | |
906 | operations as well. | |
907 | ||
0e0f0835 MB |
908 | =head2 Inheritance and Overloading |
909 | ||
910 | Overloading respects inheritance via the @ISA hierarchy. | |
911 | Inheritance interacts with overloading in two ways. | |
912 | ||
913 | =over | |
914 | ||
915 | =item Method names in the C<use overload> directive | |
916 | ||
917 | If C<value> in | |
918 | ||
919 | use overload key => value; | |
920 | ||
921 | is a string, it is interpreted as a method name - which may | |
922 | (in the usual way) be inherited from another class. | |
923 | ||
924 | =item Overloading of an operation is inherited by derived classes | |
925 | ||
926 | Any class derived from an overloaded class is also overloaded | |
927 | and inherits its operator implementations. | |
928 | If the same operator is overloaded in more than one ancestor | |
929 | then the implementation is determined by the usual inheritance | |
930 | rules. | |
931 | ||
932 | For example, if C<A> inherits from C<B> and C<C> (in that order), | |
933 | C<B> overloads C<+> with C<\&D::plus_sub>, and C<C> overloads | |
934 | C<+> by C<"plus_meth">, then the subroutine C<D::plus_sub> will | |
935 | be called to implement operation C<+> for an object in package C<A>. | |
936 | ||
937 | =back | |
938 | ||
939 | Note that since the value of the C<fallback> key is not a subroutine, | |
940 | its inheritance is not governed by the above rules. In the current | |
941 | implementation, the value of C<fallback> in the first overloaded | |
942 | ancestor is used, but this is accidental and subject to change. | |
943 | ||
944 | =head2 Run-time Overloading | |
4633a7c4 LW |
945 | |
946 | Since all C<use> directives are executed at compile-time, the only way to | |
947 | change overloading during run-time is to | |
948 | ||
949 | eval 'use overload "+" => \&addmethod'; | |
950 | ||
951 | You can also use | |
952 | ||
953 | eval 'no overload "+", "--", "<="'; | |
954 | ||
955 | though the use of these constructs during run-time is questionable. | |
956 | ||
0e0f0835 | 957 | =head2 Public Functions |
4633a7c4 LW |
958 | |
959 | Package C<overload.pm> provides the following public functions: | |
960 | ||
961 | =over 5 | |
962 | ||
963 | =item overload::StrVal(arg) | |
964 | ||
406f8c25 FC |
965 | Gives the string value of C<arg> as in the |
966 | absence of stringify overloading. If you | |
6a0e9e72 FD |
967 | are using this to get the address of a reference (useful for checking if two |
968 | references point to the same thing) then you may be better off using | |
969 | C<Scalar::Util::refaddr()>, which is faster. | |
4633a7c4 LW |
970 | |
971 | =item overload::Overloaded(arg) | |
972 | ||
973 | Returns true if C<arg> is subject to overloading of some operations. | |
974 | ||
975 | =item overload::Method(obj,op) | |
976 | ||
977 | Returns C<undef> or a reference to the method that implements C<op>. | |
978 | ||
979 | =back | |
980 | ||
0e0f0835 | 981 | =head2 Overloading Constants |
b3ac6de7 | 982 | |
7adf7a02 | 983 | For some applications, the Perl parser mangles constants too much. |
bfce84ec | 984 | It is possible to hook into this process via C<overload::constant()> |
7adf7a02 | 985 | and C<overload::remove_constant()> functions. |
b3ac6de7 IZ |
986 | |
987 | These functions take a hash as an argument. The recognized keys of this hash | |
7adf7a02 | 988 | are: |
b3ac6de7 IZ |
989 | |
990 | =over 8 | |
991 | ||
992 | =item integer | |
993 | ||
994 | to overload integer constants, | |
995 | ||
996 | =item float | |
997 | ||
998 | to overload floating point constants, | |
999 | ||
1000 | =item binary | |
1001 | ||
1002 | to overload octal and hexadecimal constants, | |
1003 | ||
1004 | =item q | |
1005 | ||
1006 | to overload C<q>-quoted strings, constant pieces of C<qq>- and C<qx>-quoted | |
1007 | strings and here-documents, | |
1008 | ||
1009 | =item qr | |
1010 | ||
1011 | to overload constant pieces of regular expressions. | |
1012 | ||
1013 | =back | |
1014 | ||
1015 | The corresponding values are references to functions which take three arguments: | |
1016 | the first one is the I<initial> string form of the constant, the second one | |
b267980d | 1017 | is how Perl interprets this constant, the third one is how the constant is used. |
b3ac6de7 | 1018 | Note that the initial string form does not |
b267980d | 1019 | contain string delimiters, and has backslashes in backslash-delimiter |
b3ac6de7 | 1020 | combinations stripped (thus the value of delimiter is not relevant for |
b267980d | 1021 | processing of this string). The return value of this function is how this |
b3ac6de7 IZ |
1022 | constant is going to be interpreted by Perl. The third argument is undefined |
1023 | unless for overloaded C<q>- and C<qr>- constants, it is C<q> in single-quote | |
1024 | context (comes from strings, regular expressions, and single-quote HERE | |
b267980d | 1025 | documents), it is C<tr> for arguments of C<tr>/C<y> operators, |
b3ac6de7 IZ |
1026 | it is C<s> for right-hand side of C<s>-operator, and it is C<qq> otherwise. |
1027 | ||
1028 | Since an expression C<"ab$cd,,"> is just a shortcut for C<'ab' . $cd . ',,'>, | |
1029 | it is expected that overloaded constant strings are equipped with reasonable | |
b267980d | 1030 | overloaded catenation operator, otherwise absurd results will result. |
b3ac6de7 IZ |
1031 | Similarly, negative numbers are considered as negations of positive constants. |
1032 | ||
1033 | Note that it is probably meaningless to call the functions overload::constant() | |
1034 | and overload::remove_constant() from anywhere but import() and unimport() methods. | |
1035 | From these methods they may be called as | |
1036 | ||
70f37c6e FC |
1037 | sub import { |
1038 | shift; | |
1039 | return unless @_; | |
1040 | die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant'; | |
1041 | overload::constant integer => sub {Math::BigInt->new(shift)}; | |
1042 | } | |
b3ac6de7 | 1043 | |
4633a7c4 LW |
1044 | =head1 IMPLEMENTATION |
1045 | ||
1046 | What follows is subject to change RSN. | |
1047 | ||
e7ea3e70 IZ |
1048 | The table of methods for all operations is cached in magic for the |
1049 | symbol table hash for the package. The cache is invalidated during | |
1050 | processing of C<use overload>, C<no overload>, new function | |
406f8c25 FC |
1051 | definitions, and changes in @ISA. However, this invalidation remains |
1052 | unprocessed until the next C<bless>ing into the package. Hence if you | |
e7ea3e70 IZ |
1053 | want to change overloading structure dynamically, you'll need an |
1054 | additional (fake) C<bless>ing to update the table. | |
1055 | ||
1056 | (Every SVish thing has a magic queue, and magic is an entry in that | |
1057 | queue. This is how a single variable may participate in multiple | |
1058 | forms of magic simultaneously. For instance, environment variables | |
1059 | regularly have two forms at once: their %ENV magic and their taint | |
406f8c25 | 1060 | magic. However, the magic which implements overloading is applied to |
e7ea3e70 IZ |
1061 | the stashes, which are rarely used directly, thus should not slow down |
1062 | Perl.) | |
4633a7c4 LW |
1063 | |
1064 | If an object belongs to a package using overload, it carries a special | |
1065 | flag. Thus the only speed penalty during arithmetic operations without | |
1066 | overloading is the checking of this flag. | |
1067 | ||
774d564b | 1068 | In fact, if C<use overload> is not present, there is almost no overhead |
1069 | for overloadable operations, so most programs should not suffer | |
1070 | measurable performance penalties. A considerable effort was made to | |
1071 | minimize the overhead when overload is used in some package, but the | |
1072 | arguments in question do not belong to packages using overload. When | |
1073 | in doubt, test your speed with C<use overload> and without it. So far | |
1074 | there have been no reports of substantial speed degradation if Perl is | |
1075 | compiled with optimization turned on. | |
4633a7c4 | 1076 | |
406f8c25 | 1077 | There is no size penalty for data if overload is not used. The only |
e7ea3e70 IZ |
1078 | size penalty if overload is used in some package is that I<all> the |
1079 | packages acquire a magic during the next C<bless>ing into the | |
406f8c25 | 1080 | package. This magic is three-words-long for packages without |
f610777f | 1081 | overloading, and carries the cache table if the package is overloaded. |
4633a7c4 | 1082 | |
4633a7c4 LW |
1083 | It is expected that arguments to methods that are not explicitly supposed |
1084 | to be changed are constant (but this is not enforced). | |
1085 | ||
0e0f0835 | 1086 | =head1 COOKBOOK |
ee239bfe IZ |
1087 | |
1088 | Please add examples to what follows! | |
1089 | ||
0e0f0835 | 1090 | =head2 Two-face Scalars |
ee239bfe IZ |
1091 | |
1092 | Put this in F<two_face.pm> in your Perl library directory: | |
1093 | ||
1094 | package two_face; # Scalars with separate string and | |
1095 | # numeric values. | |
1096 | sub new { my $p = shift; bless [@_], $p } | |
1097 | use overload '""' => \&str, '0+' => \&num, fallback => 1; | |
1098 | sub num {shift->[1]} | |
1099 | sub str {shift->[0]} | |
1100 | ||
1101 | Use it as follows: | |
1102 | ||
1103 | require two_face; | |
2b393bf4 | 1104 | my $seven = two_face->new("vii", 7); |
ee239bfe | 1105 | printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1; |
1f874cb6 | 1106 | print "seven contains 'i'\n" if $seven =~ /i/; |
ee239bfe IZ |
1107 | |
1108 | (The second line creates a scalar which has both a string value, and a | |
1109 | numeric value.) This prints: | |
1110 | ||
1111 | seven=vii, seven=7, eight=8 | |
1f874cb6 | 1112 | seven contains 'i' |
ee239bfe | 1113 | |
0e0f0835 | 1114 | =head2 Two-face References |
f5284f61 IZ |
1115 | |
1116 | Suppose you want to create an object which is accessible as both an | |
6d822dc4 | 1117 | array reference and a hash reference. |
f5284f61 IZ |
1118 | |
1119 | package two_refs; | |
1120 | use overload '%{}' => \&gethash, '@{}' => sub { $ {shift()} }; | |
b267980d NIS |
1121 | sub new { |
1122 | my $p = shift; | |
f5284f61 IZ |
1123 | bless \ [@_], $p; |
1124 | } | |
1125 | sub gethash { | |
1126 | my %h; | |
1127 | my $self = shift; | |
1128 | tie %h, ref $self, $self; | |
1129 | \%h; | |
1130 | } | |
1131 | ||
1132 | sub TIEHASH { my $p = shift; bless \ shift, $p } | |
1133 | my %fields; | |
1134 | my $i = 0; | |
1135 | $fields{$_} = $i++ foreach qw{zero one two three}; | |
b267980d | 1136 | sub STORE { |
f5284f61 IZ |
1137 | my $self = ${shift()}; |
1138 | my $key = $fields{shift()}; | |
1139 | defined $key or die "Out of band access"; | |
1140 | $$self->[$key] = shift; | |
1141 | } | |
b267980d | 1142 | sub FETCH { |
f5284f61 IZ |
1143 | my $self = ${shift()}; |
1144 | my $key = $fields{shift()}; | |
1145 | defined $key or die "Out of band access"; | |
1146 | $$self->[$key]; | |
1147 | } | |
1148 | ||
1149 | Now one can access an object using both the array and hash syntax: | |
1150 | ||
2b393bf4 | 1151 | my $bar = two_refs->new(3,4,5,6); |
f5284f61 IZ |
1152 | $bar->[2] = 11; |
1153 | $bar->{two} == 11 or die 'bad hash fetch'; | |
1154 | ||
1155 | Note several important features of this example. First of all, the | |
1156 | I<actual> type of $bar is a scalar reference, and we do not overload | |
1157 | the scalar dereference. Thus we can get the I<actual> non-overloaded | |
1158 | contents of $bar by just using C<$$bar> (what we do in functions which | |
1159 | overload dereference). Similarly, the object returned by the | |
1160 | TIEHASH() method is a scalar reference. | |
1161 | ||
1162 | Second, we create a new tied hash each time the hash syntax is used. | |
1163 | This allows us not to worry about a possibility of a reference loop, | |
d1be9408 | 1164 | which would lead to a memory leak. |
f5284f61 IZ |
1165 | |
1166 | Both these problems can be cured. Say, if we want to overload hash | |
1167 | dereference on a reference to an object which is I<implemented> as a | |
1168 | hash itself, the only problem one has to circumvent is how to access | |
1fd16925 | 1169 | this I<actual> hash (as opposed to the I<virtual> hash exhibited by the |
f5284f61 IZ |
1170 | overloaded dereference operator). Here is one possible fetching routine: |
1171 | ||
1172 | sub access_hash { | |
1173 | my ($self, $key) = (shift, shift); | |
1174 | my $class = ref $self; | |
b267980d | 1175 | bless $self, 'overload::dummy'; # Disable overloading of %{} |
f5284f61 IZ |
1176 | my $out = $self->{$key}; |
1177 | bless $self, $class; # Restore overloading | |
1178 | $out; | |
1179 | } | |
1180 | ||
1fd16925 | 1181 | To remove creation of the tied hash on each access, one may an extra |
f5284f61 IZ |
1182 | level of indirection which allows a non-circular structure of references: |
1183 | ||
1184 | package two_refs1; | |
1185 | use overload '%{}' => sub { ${shift()}->[1] }, | |
1186 | '@{}' => sub { ${shift()}->[0] }; | |
b267980d NIS |
1187 | sub new { |
1188 | my $p = shift; | |
f5284f61 IZ |
1189 | my $a = [@_]; |
1190 | my %h; | |
1191 | tie %h, $p, $a; | |
1192 | bless \ [$a, \%h], $p; | |
1193 | } | |
1194 | sub gethash { | |
1195 | my %h; | |
1196 | my $self = shift; | |
1197 | tie %h, ref $self, $self; | |
1198 | \%h; | |
1199 | } | |
1200 | ||
1201 | sub TIEHASH { my $p = shift; bless \ shift, $p } | |
1202 | my %fields; | |
1203 | my $i = 0; | |
1204 | $fields{$_} = $i++ foreach qw{zero one two three}; | |
b267980d | 1205 | sub STORE { |
f5284f61 IZ |
1206 | my $a = ${shift()}; |
1207 | my $key = $fields{shift()}; | |
1208 | defined $key or die "Out of band access"; | |
1209 | $a->[$key] = shift; | |
1210 | } | |
b267980d | 1211 | sub FETCH { |
f5284f61 IZ |
1212 | my $a = ${shift()}; |
1213 | my $key = $fields{shift()}; | |
1214 | defined $key or die "Out of band access"; | |
1215 | $a->[$key]; | |
1216 | } | |
1217 | ||
1fd16925 | 1218 | Now if $baz is overloaded like this, then C<$baz> is a reference to a |
f5284f61 IZ |
1219 | reference to the intermediate array, which keeps a reference to an |
1220 | actual array, and the access hash. The tie()ing object for the access | |
1fd16925 | 1221 | hash is a reference to a reference to the actual array, so |
f5284f61 | 1222 | |
88c28ceb | 1223 | =over |
f5284f61 IZ |
1224 | |
1225 | =item * | |
1226 | ||
1227 | There are no loops of references. | |
1228 | ||
1229 | =item * | |
1230 | ||
1231 | Both "objects" which are blessed into the class C<two_refs1> are | |
1232 | references to a reference to an array, thus references to a I<scalar>. | |
1233 | Thus the accessor expression C<$$foo-E<gt>[$ind]> involves no | |
1234 | overloaded operations. | |
1235 | ||
1236 | =back | |
1237 | ||
0e0f0835 | 1238 | =head2 Symbolic Calculator |
ee239bfe IZ |
1239 | |
1240 | Put this in F<symbolic.pm> in your Perl library directory: | |
1241 | ||
1242 | package symbolic; # Primitive symbolic calculator | |
1243 | use overload nomethod => \&wrap; | |
1244 | ||
1245 | sub new { shift; bless ['n', @_] } | |
1246 | sub wrap { | |
1247 | my ($obj, $other, $inv, $meth) = @_; | |
1248 | ($obj, $other) = ($other, $obj) if $inv; | |
1249 | bless [$meth, $obj, $other]; | |
1250 | } | |
1251 | ||
1252 | This module is very unusual as overloaded modules go: it does not | |
0e0f0835 MB |
1253 | provide any usual overloaded operators, instead it provides an |
1254 | implementation for L<C<nomethod>>. In this example the C<nomethod> | |
f610777f | 1255 | subroutine returns an object which encapsulates operations done over |
2b393bf4 RS |
1256 | the objects: C<< symbolic->new(3) >> contains C<['n', 3]>, C<< 2 + |
1257 | symbolic->new(3) >> contains C<['+', 2, ['n', 3]]>. | |
ee239bfe IZ |
1258 | |
1259 | Here is an example of the script which "calculates" the side of | |
1260 | circumscribed octagon using the above package: | |
1261 | ||
1262 | require symbolic; | |
1263 | my $iter = 1; # 2**($iter+2) = 8 | |
2b393bf4 | 1264 | my $side = symbolic->new(1); |
ee239bfe | 1265 | my $cnt = $iter; |
3cb6de81 | 1266 | |
ee239bfe IZ |
1267 | while ($cnt--) { |
1268 | $side = (sqrt(1 + $side**2) - 1)/$side; | |
1269 | } | |
1270 | print "OK\n"; | |
1271 | ||
1272 | The value of $side is | |
1273 | ||
1274 | ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]], | |
1275 | undef], 1], ['n', 1]] | |
1276 | ||
1277 | Note that while we obtained this value using a nice little script, | |
1278 | there is no simple way to I<use> this value. In fact this value may | |
2d3232d7 | 1279 | be inspected in debugger (see L<perldebug>), but only if |
ee239bfe IZ |
1280 | C<bareStringify> B<O>ption is set, and not via C<p> command. |
1281 | ||
1282 | If one attempts to print this value, then the overloaded operator | |
1283 | C<""> will be called, which will call C<nomethod> operator. The | |
1284 | result of this operator will be stringified again, but this result is | |
1285 | again of type C<symbolic>, which will lead to an infinite loop. | |
1286 | ||
1287 | Add a pretty-printer method to the module F<symbolic.pm>: | |
1288 | ||
1289 | sub pretty { | |
1290 | my ($meth, $a, $b) = @{+shift}; | |
1291 | $a = 'u' unless defined $a; | |
1292 | $b = 'u' unless defined $b; | |
1293 | $a = $a->pretty if ref $a; | |
1294 | $b = $b->pretty if ref $b; | |
1295 | "[$meth $a $b]"; | |
b267980d | 1296 | } |
ee239bfe IZ |
1297 | |
1298 | Now one can finish the script by | |
1299 | ||
1300 | print "side = ", $side->pretty, "\n"; | |
1301 | ||
1302 | The method C<pretty> is doing object-to-string conversion, so it | |
1303 | is natural to overload the operator C<""> using this method. However, | |
1304 | inside such a method it is not necessary to pretty-print the | |
1305 | I<components> $a and $b of an object. In the above subroutine | |
1306 | C<"[$meth $a $b]"> is a catenation of some strings and components $a | |
1307 | and $b. If these components use overloading, the catenation operator | |
1fd16925 | 1308 | will look for an overloaded operator C<.>; if not present, it will |
ee239bfe IZ |
1309 | look for an overloaded operator C<"">. Thus it is enough to use |
1310 | ||
1311 | use overload nomethod => \&wrap, '""' => \&str; | |
1312 | sub str { | |
1313 | my ($meth, $a, $b) = @{+shift}; | |
1314 | $a = 'u' unless defined $a; | |
1315 | $b = 'u' unless defined $b; | |
1316 | "[$meth $a $b]"; | |
b267980d | 1317 | } |
ee239bfe IZ |
1318 | |
1319 | Now one can change the last line of the script to | |
1320 | ||
1321 | print "side = $side\n"; | |
1322 | ||
1323 | which outputs | |
1324 | ||
1325 | side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]] | |
1326 | ||
1327 | and one can inspect the value in debugger using all the possible | |
b267980d | 1328 | methods. |
ee239bfe | 1329 | |
d1be9408 | 1330 | Something is still amiss: consider the loop variable $cnt of the |
ee239bfe IZ |
1331 | script. It was a number, not an object. We cannot make this value of |
1332 | type C<symbolic>, since then the loop will not terminate. | |
1333 | ||
1334 | Indeed, to terminate the cycle, the $cnt should become false. | |
1335 | However, the operator C<bool> for checking falsity is overloaded (this | |
1336 | time via overloaded C<"">), and returns a long string, thus any object | |
1337 | of type C<symbolic> is true. To overcome this, we need a way to | |
1338 | compare an object to 0. In fact, it is easier to write a numeric | |
1339 | conversion routine. | |
1340 | ||
1341 | Here is the text of F<symbolic.pm> with such a routine added (and | |
f610777f | 1342 | slightly modified str()): |
ee239bfe IZ |
1343 | |
1344 | package symbolic; # Primitive symbolic calculator | |
1345 | use overload | |
1346 | nomethod => \&wrap, '""' => \&str, '0+' => \# | |
1347 | ||
1348 | sub new { shift; bless ['n', @_] } | |
1349 | sub wrap { | |
1350 | my ($obj, $other, $inv, $meth) = @_; | |
1351 | ($obj, $other) = ($other, $obj) if $inv; | |
1352 | bless [$meth, $obj, $other]; | |
1353 | } | |
1354 | sub str { | |
1355 | my ($meth, $a, $b) = @{+shift}; | |
1356 | $a = 'u' unless defined $a; | |
1357 | if (defined $b) { | |
1358 | "[$meth $a $b]"; | |
1359 | } else { | |
1360 | "[$meth $a]"; | |
1361 | } | |
b267980d NIS |
1362 | } |
1363 | my %subr = ( n => sub {$_[0]}, | |
1364 | sqrt => sub {sqrt $_[0]}, | |
ee239bfe IZ |
1365 | '-' => sub {shift() - shift()}, |
1366 | '+' => sub {shift() + shift()}, | |
1367 | '/' => sub {shift() / shift()}, | |
1368 | '*' => sub {shift() * shift()}, | |
1369 | '**' => sub {shift() ** shift()}, | |
1370 | ); | |
1371 | sub num { | |
1372 | my ($meth, $a, $b) = @{+shift}; | |
b267980d | 1373 | my $subr = $subr{$meth} |
ee239bfe IZ |
1374 | or die "Do not know how to ($meth) in symbolic"; |
1375 | $a = $a->num if ref $a eq __PACKAGE__; | |
1376 | $b = $b->num if ref $b eq __PACKAGE__; | |
1377 | $subr->($a,$b); | |
1378 | } | |
1379 | ||
1380 | All the work of numeric conversion is done in %subr and num(). Of | |
f610777f | 1381 | course, %subr is not complete, it contains only operators used in the |
ee239bfe IZ |
1382 | example below. Here is the extra-credit question: why do we need an |
1383 | explicit recursion in num()? (Answer is at the end of this section.) | |
1384 | ||
1385 | Use this module like this: | |
1386 | ||
1387 | require symbolic; | |
2b393bf4 RS |
1388 | my $iter = symbolic->new(2); # 16-gon |
1389 | my $side = symbolic->new(1); | |
ee239bfe | 1390 | my $cnt = $iter; |
3cb6de81 | 1391 | |
ee239bfe | 1392 | while ($cnt) { |
1f874cb6 | 1393 | $cnt = $cnt - 1; # Mutator '--' not implemented |
ee239bfe IZ |
1394 | $side = (sqrt(1 + $side**2) - 1)/$side; |
1395 | } | |
1396 | printf "%s=%f\n", $side, $side; | |
1397 | printf "pi=%f\n", $side*(2**($iter+2)); | |
1398 | ||
1399 | It prints (without so many line breaks) | |
1400 | ||
1401 | [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] | |
1402 | [n 1]] 2]]] 1] | |
1403 | [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912 | |
1404 | pi=3.182598 | |
1405 | ||
1406 | The above module is very primitive. It does not implement | |
1407 | mutator methods (C<++>, C<-=> and so on), does not do deep copying | |
1408 | (not required without mutators!), and implements only those arithmetic | |
1409 | operations which are used in the example. | |
1410 | ||
1fd16925 | 1411 | To implement most arithmetic operations is easy; one should just use |
ee239bfe IZ |
1412 | the tables of operations, and change the code which fills %subr to |
1413 | ||
1414 | my %subr = ( 'n' => sub {$_[0]} ); | |
1415 | foreach my $op (split " ", $overload::ops{with_assign}) { | |
1416 | $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}"; | |
1417 | } | |
1418 | my @bins = qw(binary 3way_comparison num_comparison str_comparison); | |
1419 | foreach my $op (split " ", "@overload::ops{ @bins }") { | |
1420 | $subr{$op} = eval "sub {shift() $op shift()}"; | |
1421 | } | |
1422 | foreach my $op (split " ", "@overload::ops{qw(unary func)}") { | |
1f874cb6 | 1423 | print "defining '$op'\n"; |
ee239bfe IZ |
1424 | $subr{$op} = eval "sub {$op shift()}"; |
1425 | } | |
1426 | ||
0e0f0835 MB |
1427 | Since subroutines implementing assignment operators are not required |
1428 | to modify their operands (see L<Overloadable Operations> above), | |
1429 | we do not need anything special to make C<+=> and friends work, | |
1430 | besides adding these operators to %subr and defining a copy | |
1431 | constructor (needed since Perl has no way to know that the | |
1432 | implementation of C<'+='> does not mutate the argument - | |
1433 | see L<Copy Constructor>). | |
ee239bfe | 1434 | |
1fd16925 | 1435 | To implement a copy constructor, add C<< '=' => \&cpy >> to C<use overload> |
ee239bfe IZ |
1436 | line, and code (this code assumes that mutators change things one level |
1437 | deep only, so recursive copying is not needed): | |
1438 | ||
1439 | sub cpy { | |
1440 | my $self = shift; | |
1441 | bless [@$self], ref $self; | |
1442 | } | |
1443 | ||
b267980d | 1444 | To make C<++> and C<--> work, we need to implement actual mutators, |
ee239bfe IZ |
1445 | either directly, or in C<nomethod>. We continue to do things inside |
1446 | C<nomethod>, thus add | |
1447 | ||
1448 | if ($meth eq '++' or $meth eq '--') { | |
1449 | @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference | |
1450 | return $obj; | |
1451 | } | |
1452 | ||
b267980d | 1453 | after the first line of wrap(). This is not a most effective |
ee239bfe IZ |
1454 | implementation, one may consider |
1455 | ||
1456 | sub inc { $_[0] = bless ['++', shift, 1]; } | |
1457 | ||
1458 | instead. | |
1459 | ||
1460 | As a final remark, note that one can fill %subr by | |
1461 | ||
1462 | my %subr = ( 'n' => sub {$_[0]} ); | |
1463 | foreach my $op (split " ", $overload::ops{with_assign}) { | |
1464 | $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}"; | |
1465 | } | |
1466 | my @bins = qw(binary 3way_comparison num_comparison str_comparison); | |
1467 | foreach my $op (split " ", "@overload::ops{ @bins }") { | |
1468 | $subr{$op} = eval "sub {shift() $op shift()}"; | |
1469 | } | |
1470 | foreach my $op (split " ", "@overload::ops{qw(unary func)}") { | |
1471 | $subr{$op} = eval "sub {$op shift()}"; | |
1472 | } | |
1473 | $subr{'++'} = $subr{'+'}; | |
1474 | $subr{'--'} = $subr{'-'}; | |
1475 | ||
b267980d NIS |
1476 | This finishes implementation of a primitive symbolic calculator in |
1477 | 50 lines of Perl code. Since the numeric values of subexpressions | |
ee239bfe IZ |
1478 | are not cached, the calculator is very slow. |
1479 | ||
1480 | Here is the answer for the exercise: In the case of str(), we need no | |
1481 | explicit recursion since the overloaded C<.>-operator will fall back | |
1482 | to an existing overloaded operator C<"">. Overloaded arithmetic | |
1483 | operators I<do not> fall back to numeric conversion if C<fallback> is | |
1484 | not explicitly requested. Thus without an explicit recursion num() | |
1485 | would convert C<['+', $a, $b]> to C<$a + $b>, which would just rebuild | |
1486 | the argument of num(). | |
1487 | ||
1488 | If you wonder why defaults for conversion are different for str() and | |
1489 | num(), note how easy it was to write the symbolic calculator. This | |
1490 | simplicity is due to an appropriate choice of defaults. One extra | |
f610777f A |
1491 | note: due to the explicit recursion num() is more fragile than sym(): |
1492 | we need to explicitly check for the type of $a and $b. If components | |
ee239bfe IZ |
1493 | $a and $b happen to be of some related type, this may lead to problems. |
1494 | ||
0e0f0835 | 1495 | =head2 I<Really> Symbolic Calculator |
ee239bfe IZ |
1496 | |
1497 | One may wonder why we call the above calculator symbolic. The reason | |
1498 | is that the actual calculation of the value of expression is postponed | |
1499 | until the value is I<used>. | |
1500 | ||
1501 | To see it in action, add a method | |
1502 | ||
b267980d NIS |
1503 | sub STORE { |
1504 | my $obj = shift; | |
1505 | $#$obj = 1; | |
ee239bfe IZ |
1506 | @$obj->[0,1] = ('=', shift); |
1507 | } | |
1508 | ||
1509 | to the package C<symbolic>. After this change one can do | |
1510 | ||
2b393bf4 RS |
1511 | my $a = symbolic->new(3); |
1512 | my $b = symbolic->new(4); | |
ee239bfe IZ |
1513 | my $c = sqrt($a**2 + $b**2); |
1514 | ||
1515 | and the numeric value of $c becomes 5. However, after calling | |
1516 | ||
1517 | $a->STORE(12); $b->STORE(5); | |
1518 | ||
1519 | the numeric value of $c becomes 13. There is no doubt now that the module | |
1520 | symbolic provides a I<symbolic> calculator indeed. | |
1521 | ||
1522 | To hide the rough edges under the hood, provide a tie()d interface to the | |
0e0f0835 | 1523 | package C<symbolic>. Add methods |
ee239bfe IZ |
1524 | |
1525 | sub TIESCALAR { my $pack = shift; $pack->new(@_) } | |
1526 | sub FETCH { shift } | |
1527 | sub nop { } # Around a bug | |
1528 | ||
cfa5b373 FC |
1529 | (the bug, fixed in Perl 5.14, is described in L<"BUGS">). One can use this |
1530 | new interface as | |
ee239bfe IZ |
1531 | |
1532 | tie $a, 'symbolic', 3; | |
1533 | tie $b, 'symbolic', 4; | |
1534 | $a->nop; $b->nop; # Around a bug | |
1535 | ||
1536 | my $c = sqrt($a**2 + $b**2); | |
1537 | ||
1538 | Now numeric value of $c is 5. After C<$a = 12; $b = 5> the numeric value | |
1539 | of $c becomes 13. To insulate the user of the module add a method | |
1540 | ||
1541 | sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; } | |
1542 | ||
1543 | Now | |
1544 | ||
1545 | my ($a, $b); | |
1546 | symbolic->vars($a, $b); | |
1547 | my $c = sqrt($a**2 + $b**2); | |
1548 | ||
1549 | $a = 3; $b = 4; | |
1550 | printf "c5 %s=%f\n", $c, $c; | |
1551 | ||
1552 | $a = 12; $b = 5; | |
1553 | printf "c13 %s=%f\n", $c, $c; | |
1554 | ||
1555 | shows that the numeric value of $c follows changes to the values of $a | |
1556 | and $b. | |
1557 | ||
4633a7c4 LW |
1558 | =head1 AUTHOR |
1559 | ||
1fef88e7 | 1560 | Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>. |
4633a7c4 | 1561 | |
7e494759 PF |
1562 | =head1 SEE ALSO |
1563 | ||
0e0f0835 MB |
1564 | The C<overloading> pragma can be used to enable or disable overloaded |
1565 | operations within a lexical scope - see L<overloading>. | |
7e494759 | 1566 | |
4633a7c4 LW |
1567 | =head1 DIAGNOSTICS |
1568 | ||
1569 | When Perl is run with the B<-Do> switch or its equivalent, overloading | |
1570 | induces diagnostic messages. | |
1571 | ||
e7ea3e70 IZ |
1572 | Using the C<m> command of Perl debugger (see L<perldebug>) one can |
1573 | deduce which operations are overloaded (and which ancestor triggers | |
406f8c25 FC |
1574 | this overloading). Say, if C<eq> is overloaded, then the method C<(eq> |
1575 | is shown by debugger. The method C<()> corresponds to the C<fallback> | |
e7ea3e70 IZ |
1576 | key (in fact a presence of this method shows that this package has |
1577 | overloading enabled, and it is what is used by the C<Overloaded> | |
ee239bfe | 1578 | function of module C<overload>). |
e7ea3e70 | 1579 | |
6ad11d81 | 1580 | The module might issue the following warnings: |
6b82e2f5 A |
1581 | |
1582 | =over 4 | |
1583 | ||
1584 | =item Odd number of arguments for overload::constant | |
1585 | ||
1586 | (W) The call to overload::constant contained an odd number of arguments. | |
1587 | The arguments should come in pairs. | |
1588 | ||
1f874cb6 | 1589 | =item '%s' is not an overloadable type |
6b82e2f5 A |
1590 | |
1591 | (W) You tried to overload a constant type the overload package is unaware of. | |
1592 | ||
1f874cb6 | 1593 | =item '%s' is not a code reference |
6b82e2f5 A |
1594 | |
1595 | (W) The second (fourth, sixth, ...) argument of overload::constant needs | |
406f8c25 | 1596 | to be a code reference. Either an anonymous subroutine, or a reference |
6b82e2f5 A |
1597 | to a subroutine. |
1598 | ||
b877326b FC |
1599 | =item overload arg '%s' is invalid |
1600 | ||
1601 | (W) C<use overload> was passed an argument it did not | |
1602 | recognize. Did you mistype an operator? | |
1603 | ||
6b82e2f5 A |
1604 | =back |
1605 | ||
0e0f0835 MB |
1606 | =head1 BUGS AND PITFALLS |
1607 | ||
1608 | =over | |
1609 | ||
1610 | =item * | |
1611 | ||
1612 | No warning is issued for invalid C<use overload> keys. | |
1613 | Such errors are not always obvious: | |
1614 | ||
1615 | use overload "+0" => sub { ...; }, # should be "0+" | |
1616 | "not" => sub { ...; }; # should be "!" | |
1617 | ||
1618 | (Bug #74098) | |
1619 | ||
1620 | =item * | |
1621 | ||
1622 | A pitfall when fallback is TRUE and Perl resorts to a built-in | |
1623 | implementation of an operator is that some operators have more | |
1624 | than one semantic, for example C<|>: | |
1625 | ||
1626 | use overload '0+' => sub { $_[0]->{n}; }, | |
1627 | fallback => 1; | |
1628 | my $x = bless { n => 4 }, "main"; | |
1629 | my $y = bless { n => 8 }, "main"; | |
1630 | print $x | $y, "\n"; | |
1631 | ||
1632 | You might expect this to output "12". | |
1633 | In fact, it prints "<": the ASCII result of treating "|" | |
1634 | as a bitwise string operator - that is, the result of treating | |
1635 | the operands as the strings "4" and "8" rather than numbers. | |
1636 | The fact that numify (C<0+>) is implemented but stringify | |
1637 | (C<"">) isn't makes no difference since the latter is simply | |
1638 | autogenerated from the former. | |
4633a7c4 | 1639 | |
0e0f0835 MB |
1640 | The only way to change this is to provide your own subroutine |
1641 | for C<'|'>. | |
1642 | ||
1643 | =item * | |
1644 | ||
1645 | Magic autogeneration increases the potential for inadvertently | |
1646 | creating self-referential structures. | |
1647 | Currently Perl will not free self-referential | |
1648 | structures until cycles are explicitly broken. | |
1649 | For example, | |
1650 | ||
1651 | use overload '+' => 'add'; | |
1652 | sub add { bless [ \$_[0], \$_[1] ] }; | |
1653 | ||
1654 | is asking for trouble, since | |
1655 | ||
1656 | $obj += $y; | |
1657 | ||
1658 | will effectively become | |
1659 | ||
1660 | $obj = add($obj, $y, undef); | |
1661 | ||
1662 | with the same result as | |
1663 | ||
1664 | $obj = [\$obj, \$foo]; | |
1665 | ||
1666 | Even if no I<explicit> assignment-variants of operators are present in | |
1667 | the script, they may be generated by the optimizer. | |
1668 | For example, | |
1669 | ||
1670 | "obj = $obj\n" | |
1671 | ||
1672 | may be optimized to | |
1673 | ||
1674 | my $tmp = 'obj = ' . $obj; $tmp .= "\n"; | |
1675 | ||
1676 | =item * | |
1677 | ||
1678 | Because it is used for overloading, the per-package hash | |
1679 | C<%OVERLOAD> now has a special meaning in Perl. | |
1680 | The symbol table is filled with names looking like line-noise. | |
1681 | ||
1682 | =item * | |
4633a7c4 | 1683 | |
a6006777 | 1684 | For the purpose of inheritance every overloaded package behaves as if |
406f8c25 | 1685 | C<fallback> is present (possibly undefined). This may create |
a6006777 | 1686 | interesting effects if some package is not overloaded, but inherits |
1687 | from two overloaded packages. | |
4633a7c4 | 1688 | |
0e0f0835 MB |
1689 | =item * |
1690 | ||
cfa5b373 | 1691 | Before Perl 5.14, the relation between overloading and tie()ing was broken. |
0fac1cef | 1692 | Overloading was triggered or not based on the I<previous> class of the |
cfa5b373 | 1693 | tie()d variable. |
dc04e1e9 | 1694 | |
cfa5b373 FC |
1695 | This happened because the presence of overloading was checked |
1696 | too early, before any tie()d access was attempted. If the | |
1697 | class of the value FETCH()ed from the tied variable does not | |
1698 | change, a simple workaround for code that is to run on older Perl | |
1699 | versions is to access the value (via C<() = $foo> or some such) | |
dc04e1e9 FC |
1700 | immediately after tie()ing, so that after this call the I<previous> class |
1701 | coincides with the current one. | |
1702 | ||
dc04e1e9 FC |
1703 | =item * |
1704 | ||
b3ac6de7 IZ |
1705 | Barewords are not covered by overloaded string constants. |
1706 | ||
0e0f0835 | 1707 | =back |
4633a7c4 LW |
1708 | |
1709 | =cut | |
1710 |