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