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