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