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