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