Fixes for ext/compress
[p5sagit/p5-mst-13.2.git] / lib / overload.pm
CommitLineData
4633a7c4 1package overload;
2
1e9bd118 3our $VERSION = '1.07';
b75c8c73 4
a6006777 5sub nil {}
6
4633a7c4 7sub OVERLOAD {
8 $package = shift;
9 my %arg = @_;
a6006777 10 my ($sub, $fb);
11 $ {$package . "::OVERLOAD"}{dummy}++; # Register with magic by touching.
12 *{$package . "::()"} = \&nil; # Make it findable via fetchmethod.
4633a7c4 13 for (keys %arg) {
a6006777 14 if ($_ eq 'fallback') {
15 $fb = $arg{$_};
16 } else {
17 $sub = $arg{$_};
18 if (not ref $sub and $sub !~ /::/) {
44a8e56a 19 $ {$package . "::(" . $_} = $sub;
20 $sub = \&nil;
a6006777 21 }
22 #print STDERR "Setting `$ {'package'}::\cO$_' to \\&`$sub'.\n";
23 *{$package . "::(" . $_} = \&{ $sub };
24 }
4633a7c4 25 }
a6006777 26 ${$package . "::()"} = $fb; # Make it findable too (fallback only).
4633a7c4 27}
28
29sub import {
30 $package = (caller())[0];
31 # *{$package . "::OVERLOAD"} = \&OVERLOAD;
32 shift;
33 $package->overload::OVERLOAD(@_);
34}
35
36sub unimport {
37 $package = (caller())[0];
a6006777 38 ${$package . "::OVERLOAD"}{dummy}++; # Upgrade the table
4633a7c4 39 shift;
40 for (@_) {
a6006777 41 if ($_ eq 'fallback') {
42 undef $ {$package . "::()"};
43 } else {
44 delete $ {$package . "::"}{"(" . $_};
45 }
4633a7c4 46 }
47}
48
49sub Overloaded {
a6006777 50 my $package = shift;
51 $package = ref $package if ref $package;
52 $package->can('()');
4633a7c4 53}
54
44a8e56a 55sub ov_method {
56 my $globref = shift;
57 return undef unless $globref;
58 my $sub = \&{*$globref};
59 return $sub if $sub ne \&nil;
60 return shift->can($ {*$globref});
61}
62
4633a7c4 63sub OverloadedStringify {
a6006777 64 my $package = shift;
65 $package = ref $package if ref $package;
44a8e56a 66 #$package->can('(""')
ee239bfe 67 ov_method mycan($package, '(""'), $package
68 or ov_method mycan($package, '(0+'), $package
69 or ov_method mycan($package, '(bool'), $package
70 or ov_method mycan($package, '(nomethod'), $package;
4633a7c4 71}
72
73sub Method {
a6006777 74 my $package = shift;
05a4b9b1 75 if(ref $package) {
4de05ceb 76 local $@;
77 local $!;
78 require Scalar::Util;
05a4b9b1 79 $package = Scalar::Util::blessed($package);
80 return undef if !defined $package;
81 }
44a8e56a 82 #my $meth = $package->can('(' . shift);
83 ov_method mycan($package, '(' . shift), $package;
84 #return $meth if $meth ne \&nil;
85 #return $ {*{$meth}};
4633a7c4 86}
87
88sub AddrRef {
a6006777 89 my $package = ref $_[0];
90 return "$_[0]" unless $package;
b3c0ec7c 91
4de05ceb 92 local $@;
93 local $!;
94 require Scalar::Util;
295812e0 95 my $class = Scalar::Util::blessed($_[0]);
96 my $class_prefix = defined($class) ? "$class=" : "";
97 my $type = Scalar::Util::reftype($_[0]);
98 my $addr = Scalar::Util::refaddr($_[0]);
99 return sprintf("$class_prefix$type(0x%x)", $addr);
4633a7c4 100}
101
1b1d102f 102*StrVal = *AddrRef;
4633a7c4 103
44a8e56a 104sub mycan { # Real can would leave stubs.
105 my ($package, $meth) = @_;
e1a479c5 106
1e9bd118 107 local $@;
108 local $!;
109 require mro;
110
e1a479c5 111 my $mro = mro::get_linear_isa($package);
112 foreach my $p (@$mro) {
113 my $fqmeth = $p . q{::} . $meth;
114 return \*{$fqmeth} if defined &{$fqmeth};
44a8e56a 115 }
e1a479c5 116
44a8e56a 117 return undef;
118}
119
b3ac6de7 120%constants = (
9cfe5470 121 'integer' => 0x1000, # HINT_NEW_INTEGER
122 'float' => 0x2000, # HINT_NEW_FLOAT
123 'binary' => 0x4000, # HINT_NEW_BINARY
124 'q' => 0x8000, # HINT_NEW_STRING
125 'qr' => 0x10000, # HINT_NEW_RE
b3ac6de7 126 );
127
ee239bfe 128%ops = ( with_assign => "+ - * / % ** << >> x .",
129 assign => "+= -= *= /= %= **= <<= >>= x= .=",
2877bd81 130 num_comparison => "< <= > >= == !=",
ee239bfe 131 '3way_comparison'=> "<=> cmp",
2877bd81 132 str_comparison => "lt le gt ge eq ne",
6dd85743 133 binary => '& &= | |= ^ ^=',
ee239bfe 134 unary => "neg ! ~",
135 mutators => '++ --',
f216259d 136 func => "atan2 cos sin exp abs log sqrt int",
ee239bfe 137 conversion => 'bool "" 0+',
f5284f61 138 iterators => '<>',
139 dereferencing => '${} @{} %{} &{} *{}',
ee239bfe 140 special => 'nomethod fallback =');
141
6b82e2f5 142use warnings::register;
b3ac6de7 143sub constant {
144 # Arguments: what, sub
145 while (@_) {
6b82e2f5 146 if (@_ == 1) {
4498a751 147 warnings::warnif ("Odd number of arguments for overload::constant");
6b82e2f5 148 last;
149 }
150 elsif (!exists $constants {$_ [0]}) {
4498a751 151 warnings::warnif ("`$_[0]' is not an overloadable type");
6b82e2f5 152 }
1e70e886 153 elsif (!ref $_ [1] || "$_[1]" !~ /(^|=)CODE\(0x[0-9a-f]+\)$/) {
6b82e2f5 154 # Can't use C<ref $_[1] eq "CODE"> above as code references can be
155 # blessed, and C<ref> would return the package the ref is blessed into.
156 if (warnings::enabled) {
6b82e2f5 157 $_ [1] = "undef" unless defined $_ [1];
4498a751 158 warnings::warn ("`$_[1]' is not a code reference");
6b82e2f5 159 }
160 }
161 else {
162 $^H{$_[0]} = $_[1];
f22a2069 163 $^H |= $constants{$_[0]};
6b82e2f5 164 }
b3ac6de7 165 shift, shift;
166 }
167}
168
169sub remove_constant {
170 # Arguments: what, sub
171 while (@_) {
172 delete $^H{$_[0]};
173 $^H &= ~ $constants{$_[0]};
174 shift, shift;
175 }
176}
177
4633a7c4 1781;
179
180__END__
181
b267980d 182=head1 NAME
4633a7c4 183
7adf7a02 184overload - Package for overloading Perl operations
4633a7c4 185
186=head1 SYNOPSIS
187
188 package SomeThing;
189
b267980d 190 use overload
4633a7c4 191 '+' => \&myadd,
192 '-' => \&mysub;
193 # etc
194 ...
195
196 package main;
2b393bf4 197 $a = SomeThing->new( 57 );
4633a7c4 198 $b=5+$a;
199 ...
200 if (overload::Overloaded $b) {...}
201 ...
202 $strval = overload::StrVal $b;
203
4633a7c4 204=head1 DESCRIPTION
205
caf82a01 206This pragma allows overloading of Perl's operators for a class.
207To overload built-in functions, see L<perlsub/Overriding Built-in Functions> instead.
208
4633a7c4 209=head2 Declaration of overloaded functions
210
211The compilation directive
212
213 package Number;
214 use overload
b267980d 215 "+" => \&add,
4633a7c4 216 "*=" => "muas";
217
218declares function Number::add() for addition, and method muas() in
219the "class" C<Number> (or one of its base classes)
b267980d 220for the assignment form C<*=> of multiplication.
4633a7c4 221
222Arguments of this directive come in (key, value) pairs. Legal values
e7ea3e70 223are values legal inside a C<&{ ... }> call, so the name of a
224subroutine, a reference to a subroutine, or an anonymous subroutine
225will all work. Note that values specified as strings are
226interpreted as methods, not subroutines. Legal keys are listed below.
4633a7c4 227
228The subroutine C<add> will be called to execute C<$a+$b> if $a
229is a reference to an object blessed into the package C<Number>, or if $a is
230not an object from a package with defined mathemagic addition, but $b is a
231reference to a C<Number>. It can also be called in other situations, like
232C<$a+=7>, or C<$a++>. See L<MAGIC AUTOGENERATION>. (Mathemagical
233methods refer to methods triggered by an overloaded mathematical
234operator.)
235
774d564b 236Since overloading respects inheritance via the @ISA hierarchy, the
237above declaration would also trigger overloading of C<+> and C<*=> in
238all the packages which inherit from C<Number>.
e7ea3e70 239
4633a7c4 240=head2 Calling Conventions for Binary Operations
241
242The functions specified in the C<use overload ...> directive are called
243with three (in one particular case with four, see L<Last Resort>)
244arguments. If the corresponding operation is binary, then the first
245two arguments are the two arguments of the operation. However, due to
246general object calling conventions, the first argument should always be
247an object in the package, so in the situation of C<7+$a>, the
248order of the arguments is interchanged. It probably does not matter
249when implementing the addition method, but whether the arguments
250are reversed is vital to the subtraction method. The method can
251query this information by examining the third argument, which can take
252three different values:
253
254=over 7
255
256=item FALSE
257
258the order of arguments is as in the current operation.
259
260=item TRUE
261
262the arguments are reversed.
263
264=item C<undef>
265
266the current operation is an assignment variant (as in
267C<$a+=7>), but the usual function is called instead. This additional
ee239bfe 268information can be used to generate some optimizations. Compare
269L<Calling Conventions for Mutators>.
4633a7c4 270
271=back
272
273=head2 Calling Conventions for Unary Operations
274
275Unary operation are considered binary operations with the second
276argument being C<undef>. Thus the functions that overloads C<{"++"}>
277is called with arguments C<($a,undef,'')> when $a++ is executed.
278
ee239bfe 279=head2 Calling Conventions for Mutators
280
281Two types of mutators have different calling conventions:
282
88c28ceb 283=over
ee239bfe 284
285=item C<++> and C<-->
286
287The routines which implement these operators are expected to actually
288I<mutate> their arguments. So, assuming that $obj is a reference to a
289number,
290
291 sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \$n}
292
293is an appropriate implementation of overloaded C<++>. Note that
294
295 sub incr { ++$ {$_[0]} ; shift }
296
297is OK if used with preincrement and with postincrement. (In the case
298of postincrement a copying will be performed, see L<Copy Constructor>.)
299
300=item C<x=> and other assignment versions
301
302There is nothing special about these methods. They may change the
303value of their arguments, and may leave it as is. The result is going
304to be assigned to the value in the left-hand-side if different from
305this value.
306
f610777f 307This allows for the same method to be used as overloaded C<+=> and
ee239bfe 308C<+>. Note that this is I<allowed>, but not recommended, since by the
309semantic of L<"Fallback"> Perl will call the method for C<+> anyway,
310if C<+=> is not overloaded.
311
312=back
313
d1be9408 314B<Warning.> Due to the presence of assignment versions of operations,
b267980d 315routines which may be called in assignment context may create
316self-referential structures. Currently Perl will not free self-referential
ee239bfe 317structures until cycles are C<explicitly> broken. You may get problems
318when traversing your structures too.
319
b267980d 320Say,
ee239bfe 321
322 use overload '+' => sub { bless [ \$_[0], \$_[1] ] };
323
324is asking for trouble, since for code C<$obj += $foo> the subroutine
b267980d 325is called as C<$obj = add($obj, $foo, undef)>, or C<$obj = [\$obj,
ee239bfe 326\$foo]>. If using such a subroutine is an important optimization, one
327can overload C<+=> explicitly by a non-"optimized" version, or switch
b267980d 328to non-optimized version if C<not defined $_[2]> (see
ee239bfe 329L<Calling Conventions for Binary Operations>).
330
331Even if no I<explicit> assignment-variants of operators are present in
332the script, they may be generated by the optimizer. Say, C<",$obj,"> or
333C<',' . $obj . ','> may be both optimized to
334
335 my $tmp = ',' . $obj; $tmp .= ',';
336
4633a7c4 337=head2 Overloadable Operations
338
ee239bfe 339The following symbols can be specified in C<use overload> directive:
4633a7c4 340
341=over 5
342
343=item * I<Arithmetic operations>
344
345 "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
346 "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
347
348For these operations a substituted non-assignment variant can be called if
fa8a6580 349the assignment variant is not available. Methods for operations C<+>,
350C<->, C<+=>, and C<-=> can be called to automatically generate
351increment and decrement methods. The operation C<-> can be used to
4633a7c4 352autogenerate missing methods for unary minus or C<abs>.
353
ee239bfe 354See L<"MAGIC AUTOGENERATION">, L<"Calling Conventions for Mutators"> and
355L<"Calling Conventions for Binary Operations">) for details of these
356substitutions.
357
4633a7c4 358=item * I<Comparison operations>
359
360 "<", "<=", ">", ">=", "==", "!=", "<=>",
361 "lt", "le", "gt", "ge", "eq", "ne", "cmp",
362
363If the corresponding "spaceship" variant is available, it can be
364used to substitute for the missing operation. During C<sort>ing
365arrays, C<cmp> is used to compare values subject to C<use overload>.
366
367=item * I<Bit operations>
368
6dd85743 369 "&", "&=", "^", "^=", "|", "|=", "neg", "!", "~",
4633a7c4 370
fa8a6580 371C<neg> stands for unary minus. If the method for C<neg> is not
3bc6ec80 372specified, it can be autogenerated using the method for
fa8a6580 373subtraction. If the method for C<!> is not specified, it can be
374autogenerated using the methods for C<bool>, or C<"">, or C<0+>.
4633a7c4 375
6dd85743 376The same remarks in L<"Arithmetic operations"> about
377assignment-variants and autogeneration apply for
378bit operations C<"&">, C<"^">, and C<"|"> as well.
379
4633a7c4 380=item * I<Increment and decrement>
381
382 "++", "--",
383
384If undefined, addition and subtraction methods can be
385used instead. These operations are called both in prefix and
386postfix form.
387
388=item * I<Transcendental functions>
389
f216259d 390 "atan2", "cos", "sin", "exp", "abs", "log", "sqrt", "int"
4633a7c4 391
392If C<abs> is unavailable, it can be autogenerated using methods
1fef88e7 393for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
4633a7c4 394
f216259d 395Note that traditionally the Perl function L<int> rounds to 0, thus for
396floating-point-like types one should follow the same semantic. If
397C<int> is unavailable, it can be autogenerated using the overloading of
398C<0+>.
399
4633a7c4 400=item * I<Boolean, string and numeric conversion>
401
fa8a6580 402 'bool', '""', '0+',
4633a7c4 403
f5284f61 404If one or two of these operations are not overloaded, the remaining ones can
4633a7c4 405be used instead. C<bool> is used in the flow control operators
fa8a6580 406(like C<while>) and for the ternary C<?:> operation. These functions can
4633a7c4 407return any arbitrary Perl value. If the corresponding operation for this value
408is overloaded too, that operation will be called again with this value.
409
1554e226 410As a special case if the overload returns the object itself then it will
411be used directly. An overloaded conversion returning the object is
412probably a bug, because you're likely to get something that looks like
413C<YourPackage=HASH(0x8172b34)>.
414
f5284f61 415=item * I<Iteration>
416
417 "<>"
418
419If not overloaded, the argument will be converted to a filehandle or
420glob (which may require a stringification). The same overloading
421happens both for the I<read-filehandle> syntax C<E<lt>$varE<gt>> and
422I<globbing> syntax C<E<lt>${var}E<gt>>.
423
54f8c773 424B<BUGS> Even in list context, the iterator is currently called only
425once and with scalar context.
426
f5284f61 427=item * I<Dereferencing>
428
429 '${}', '@{}', '%{}', '&{}', '*{}'.
430
431If not overloaded, the argument will be dereferenced I<as is>, thus
432should be of correct type. These functions should return a reference
433of correct type, or another object with overloaded dereferencing.
434
b267980d 435As a special case if the overload returns the object itself then it
436will be used directly (provided it is the correct type).
437
438The dereference operators must be specified explicitly they will not be passed to
439"nomethod".
440
4633a7c4 441=item * I<Special>
442
0d863452 443 "nomethod", "fallback", "=", "~~",
4633a7c4 444
445see L<SPECIAL SYMBOLS FOR C<use overload>>.
446
447=back
448
ee239bfe 449See L<"Fallback"> for an explanation of when a missing method can be
450autogenerated.
451
452A computer-readable form of the above table is available in the hash
453%overload::ops, with values being space-separated lists of names:
454
455 with_assign => '+ - * / % ** << >> x .',
456 assign => '+= -= *= /= %= **= <<= >>= x= .=',
2877bd81 457 num_comparison => '< <= > >= == !=',
ee239bfe 458 '3way_comparison'=> '<=> cmp',
2877bd81 459 str_comparison => 'lt le gt ge eq ne',
6dd85743 460 binary => '& &= | |= ^ ^=',
ee239bfe 461 unary => 'neg ! ~',
462 mutators => '++ --',
463 func => 'atan2 cos sin exp abs log sqrt',
464 conversion => 'bool "" 0+',
f5284f61 465 iterators => '<>',
466 dereferencing => '${} @{} %{} &{} *{}',
ee239bfe 467 special => 'nomethod fallback ='
4633a7c4 468
e7ea3e70 469=head2 Inheritance and overloading
470
774d564b 471Inheritance interacts with overloading in two ways.
e7ea3e70 472
88c28ceb 473=over
e7ea3e70 474
475=item Strings as values of C<use overload> directive
476
774d564b 477If C<value> in
e7ea3e70 478
479 use overload key => value;
480
774d564b 481is a string, it is interpreted as a method name.
e7ea3e70 482
483=item Overloading of an operation is inherited by derived classes
484
774d564b 485Any class derived from an overloaded class is also overloaded. The
486set of overloaded methods is the union of overloaded methods of all
487the ancestors. If some method is overloaded in several ancestor, then
e7ea3e70 488which description will be used is decided by the usual inheritance
774d564b 489rules:
e7ea3e70 490
774d564b 491If C<A> inherits from C<B> and C<C> (in this order), C<B> overloads
492C<+> with C<\&D::plus_sub>, and C<C> overloads C<+> by C<"plus_meth">,
493then the subroutine C<D::plus_sub> will be called to implement
494operation C<+> for an object in package C<A>.
e7ea3e70 495
496=back
497
774d564b 498Note that since the value of the C<fallback> key is not a subroutine,
499its inheritance is not governed by the above rules. In the current
500implementation, the value of C<fallback> in the first overloaded
501ancestor is used, but this is accidental and subject to change.
e7ea3e70 502
4633a7c4 503=head1 SPECIAL SYMBOLS FOR C<use overload>
504
505Three keys are recognized by Perl that are not covered by the above
506description.
507
774d564b 508=head2 Last Resort
4633a7c4 509
510C<"nomethod"> should be followed by a reference to a function of four
511parameters. If defined, it is called when the overloading mechanism
512cannot find a method for some operation. The first three arguments of
513this function coincide with the arguments for the corresponding method if
514it were found, the fourth argument is the symbol
515corresponding to the missing method. If several methods are tried,
516the last one is used. Say, C<1-$a> can be equivalent to
517
518 &nomethodMethod($a,1,1,"-")
519
520if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
521C<use overload> directive.
522
b267980d 523The C<"nomethod"> mechanism is I<not> used for the dereference operators
524( ${} @{} %{} &{} *{} ).
525
526
4633a7c4 527If some operation cannot be resolved, and there is no function
528assigned to C<"nomethod">, then an exception will be raised via die()--
529unless C<"fallback"> was specified as a key in C<use overload> directive.
530
b267980d 531
532=head2 Fallback
4633a7c4 533
534The key C<"fallback"> governs what to do if a method for a particular
535operation is not found. Three different cases are possible depending on
536the value of C<"fallback">:
537
538=over 16
539
540=item * C<undef>
541
542Perl tries to use a
543substituted method (see L<MAGIC AUTOGENERATION>). If this fails, it
544then tries to calls C<"nomethod"> value; if missing, an exception
545will be raised.
546
547=item * TRUE
548
549The same as for the C<undef> value, but no exception is raised. Instead,
550it silently reverts to what it would have done were there no C<use overload>
551present.
552
553=item * defined, but FALSE
554
555No autogeneration is tried. Perl tries to call
b267980d 556C<"nomethod"> value, and if this is missing, raises an exception.
4633a7c4 557
558=back
559
e7ea3e70 560B<Note.> C<"fallback"> inheritance via @ISA is not carved in stone
561yet, see L<"Inheritance and overloading">.
562
5e68dedd 563=head2 Smart Match
564
565The key C<"~~"> allows you to override the smart matching used by
566the switch construct. See L<feature>.
567
4633a7c4 568=head2 Copy Constructor
569
570The value for C<"="> is a reference to a function with three
571arguments, i.e., it looks like the other values in C<use
572overload>. However, it does not overload the Perl assignment
573operator. This would go against Camel hair.
574
575This operation is called in the situations when a mutator is applied
576to a reference that shares its object with some other reference, such
577as
578
b267980d 579 $a=$b;
ee239bfe 580 ++$a;
4633a7c4 581
582To make this change $a and not change $b, a copy of C<$$a> is made,
583and $a is assigned a reference to this new object. This operation is
ee239bfe 584done during execution of the C<++$a>, and not during the assignment,
4633a7c4 585(so before the increment C<$$a> coincides with C<$$b>). This is only
ee239bfe 586done if C<++> is expressed via a method for C<'++'> or C<'+='> (or
587C<nomethod>). Note that if this operation is expressed via C<'+'>
588a nonmutator, i.e., as in
4633a7c4 589
b267980d 590 $a=$b;
4633a7c4 591 $a=$a+1;
592
593then C<$a> does not reference a new copy of C<$$a>, since $$a does not
594appear as lvalue when the above code is executed.
595
596If the copy constructor is required during the execution of some mutator,
597but a method for C<'='> was not specified, it can be autogenerated as a
49c95d58 598string copy if the object is a plain scalar or a simple assignment if it
599is not.
4633a7c4 600
601=over 5
602
603=item B<Example>
604
b267980d 605The actually executed code for
4633a7c4 606
b267980d 607 $a=$b;
4633a7c4 608 Something else which does not modify $a or $b....
609 ++$a;
610
611may be
612
b267980d 613 $a=$b;
4633a7c4 614 Something else which does not modify $a or $b....
615 $a = $a->clone(undef,"");
616 $a->incr(undef,"");
617
618if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
619C<'='> was overloaded with C<\&clone>.
620
621=back
622
f610777f 623Same behaviour is triggered by C<$b = $a++>, which is consider a synonym for
ee239bfe 624C<$b = $a; ++$a>.
625
4633a7c4 626=head1 MAGIC AUTOGENERATION
627
628If a method for an operation is not found, and the value for C<"fallback"> is
629TRUE or undefined, Perl tries to autogenerate a substitute method for
630the missing operation based on the defined operations. Autogenerated method
631substitutions are possible for the following operations:
632
633=over 16
634
635=item I<Assignment forms of arithmetic operations>
636
637C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
638is not defined.
639
b267980d 640=item I<Conversion operations>
4633a7c4 641
642String, numeric, and boolean conversion are calculated in terms of one
643another if not all of them are defined.
644
645=item I<Increment and decrement>
646
647The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
648and C<$a--> in terms of C<$a-=1> and C<$a-1>.
649
650=item C<abs($a)>
651
652can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
653
654=item I<Unary minus>
655
656can be expressed in terms of subtraction.
657
3bc6ec80 658=item I<Negation>
659
660C<!> and C<not> can be expressed in terms of boolean conversion, or
661string or numerical conversion.
662
4633a7c4 663=item I<Concatenation>
664
665can be expressed in terms of string conversion.
666
b267980d 667=item I<Comparison operations>
4633a7c4 668
669can be expressed in terms of its "spaceship" counterpart: either
670C<E<lt>=E<gt>> or C<cmp>:
1fef88e7 671
4633a7c4 672 <, >, <=, >=, ==, != in terms of <=>
673 lt, gt, le, ge, eq, ne in terms of cmp
674
f5284f61 675=item I<Iterator>
676
677 <> in terms of builtin operations
678
679=item I<Dereferencing>
680
681 ${} @{} %{} &{} *{} in terms of builtin operations
682
4633a7c4 683=item I<Copy operator>
684
685can be expressed in terms of an assignment to the dereferenced value, if this
49c95d58 686value is a scalar and not a reference, or simply a reference assignment
687otherwise.
4633a7c4 688
689=back
690
84fc275b 691=head1 Minimal set of overloaded operations
692
693Since some operations can be automatically generated from others, there is
694a minimal set of operations that need to be overloaded in order to have
299476e0 695the complete set of overloaded operations at one's disposal.
696Of course, the autogenerated operations may not do exactly what the user
697expects. See L<MAGIC AUTOGENERATION> above. The minimal set is:
84fc275b 698
699 + - * / % ** << >> x
700 <=> cmp
701 & | ^ ~
702 atan2 cos sin exp log sqrt int
703
704Additionally, you need to define at least one of string, boolean or
299476e0 705numeric conversions because any one can be used to emulate the others.
706The string conversion can also be used to emulate concatenation.
84fc275b 707
ee239bfe 708=head1 Losing overloading
4633a7c4 709
710The restriction for the comparison operation is that even if, for example,
711`C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
712function will produce only a standard logical value based on the
713numerical value of the result of `C<cmp>'. In particular, a working
714numeric conversion is needed in this case (possibly expressed in terms of
715other conversions).
716
717Similarly, C<.=> and C<x=> operators lose their mathemagical properties
718if the string conversion substitution is applied.
719
720When you chop() a mathemagical object it is promoted to a string and its
721mathemagical properties are lost. The same can happen with other
722operations as well.
723
724=head1 Run-time Overloading
725
726Since all C<use> directives are executed at compile-time, the only way to
727change overloading during run-time is to
728
729 eval 'use overload "+" => \&addmethod';
730
731You can also use
732
733 eval 'no overload "+", "--", "<="';
734
735though the use of these constructs during run-time is questionable.
736
737=head1 Public functions
738
739Package C<overload.pm> provides the following public functions:
740
741=over 5
742
743=item overload::StrVal(arg)
744
6a0e9e72 745Gives string value of C<arg> as in absence of stringify overloading. If you
746are using this to get the address of a reference (useful for checking if two
747references point to the same thing) then you may be better off using
748C<Scalar::Util::refaddr()>, which is faster.
4633a7c4 749
750=item overload::Overloaded(arg)
751
752Returns true if C<arg> is subject to overloading of some operations.
753
754=item overload::Method(obj,op)
755
756Returns C<undef> or a reference to the method that implements C<op>.
757
758=back
759
b3ac6de7 760=head1 Overloading constants
761
7adf7a02 762For some applications, the Perl parser mangles constants too much.
bfce84ec 763It is possible to hook into this process via C<overload::constant()>
7adf7a02 764and C<overload::remove_constant()> functions.
b3ac6de7 765
766These functions take a hash as an argument. The recognized keys of this hash
7adf7a02 767are:
b3ac6de7 768
769=over 8
770
771=item integer
772
773to overload integer constants,
774
775=item float
776
777to overload floating point constants,
778
779=item binary
780
781to overload octal and hexadecimal constants,
782
783=item q
784
785to overload C<q>-quoted strings, constant pieces of C<qq>- and C<qx>-quoted
786strings and here-documents,
787
788=item qr
789
790to overload constant pieces of regular expressions.
791
792=back
793
794The corresponding values are references to functions which take three arguments:
795the first one is the I<initial> string form of the constant, the second one
b267980d 796is how Perl interprets this constant, the third one is how the constant is used.
b3ac6de7 797Note that the initial string form does not
b267980d 798contain string delimiters, and has backslashes in backslash-delimiter
b3ac6de7 799combinations stripped (thus the value of delimiter is not relevant for
b267980d 800processing of this string). The return value of this function is how this
b3ac6de7 801constant is going to be interpreted by Perl. The third argument is undefined
802unless for overloaded C<q>- and C<qr>- constants, it is C<q> in single-quote
803context (comes from strings, regular expressions, and single-quote HERE
b267980d 804documents), it is C<tr> for arguments of C<tr>/C<y> operators,
b3ac6de7 805it is C<s> for right-hand side of C<s>-operator, and it is C<qq> otherwise.
806
807Since an expression C<"ab$cd,,"> is just a shortcut for C<'ab' . $cd . ',,'>,
808it is expected that overloaded constant strings are equipped with reasonable
b267980d 809overloaded catenation operator, otherwise absurd results will result.
b3ac6de7 810Similarly, negative numbers are considered as negations of positive constants.
811
812Note that it is probably meaningless to call the functions overload::constant()
813and overload::remove_constant() from anywhere but import() and unimport() methods.
814From these methods they may be called as
815
816 sub import {
817 shift;
818 return unless @_;
819 die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
820 overload::constant integer => sub {Math::BigInt->new(shift)};
821 }
822
4633a7c4 823=head1 IMPLEMENTATION
824
825What follows is subject to change RSN.
826
e7ea3e70 827The table of methods for all operations is cached in magic for the
828symbol table hash for the package. The cache is invalidated during
829processing of C<use overload>, C<no overload>, new function
830definitions, and changes in @ISA. However, this invalidation remains
831unprocessed until the next C<bless>ing into the package. Hence if you
832want to change overloading structure dynamically, you'll need an
833additional (fake) C<bless>ing to update the table.
834
835(Every SVish thing has a magic queue, and magic is an entry in that
836queue. This is how a single variable may participate in multiple
837forms of magic simultaneously. For instance, environment variables
838regularly have two forms at once: their %ENV magic and their taint
839magic. However, the magic which implements overloading is applied to
840the stashes, which are rarely used directly, thus should not slow down
841Perl.)
4633a7c4 842
843If an object belongs to a package using overload, it carries a special
844flag. Thus the only speed penalty during arithmetic operations without
845overloading is the checking of this flag.
846
774d564b 847In fact, if C<use overload> is not present, there is almost no overhead
848for overloadable operations, so most programs should not suffer
849measurable performance penalties. A considerable effort was made to
850minimize the overhead when overload is used in some package, but the
851arguments in question do not belong to packages using overload. When
852in doubt, test your speed with C<use overload> and without it. So far
853there have been no reports of substantial speed degradation if Perl is
854compiled with optimization turned on.
4633a7c4 855
e7ea3e70 856There is no size penalty for data if overload is not used. The only
857size penalty if overload is used in some package is that I<all> the
858packages acquire a magic during the next C<bless>ing into the
859package. This magic is three-words-long for packages without
f610777f 860overloading, and carries the cache table if the package is overloaded.
4633a7c4 861
b267980d 862Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is
4633a7c4 863carried out before any operation that can imply an assignment to the
864object $a (or $b) refers to, like C<$a++>. You can override this
865behavior by defining your own copy constructor (see L<"Copy Constructor">).
866
867It is expected that arguments to methods that are not explicitly supposed
868to be changed are constant (but this is not enforced).
869
ee239bfe 870=head1 Metaphor clash
871
f610777f 872One may wonder why the semantic of overloaded C<=> is so counter intuitive.
b267980d 873If it I<looks> counter intuitive to you, you are subject to a metaphor
874clash.
ee239bfe 875
876Here is a Perl object metaphor:
877
878I< object is a reference to blessed data>
879
880and an arithmetic metaphor:
881
882I< object is a thing by itself>.
883
884The I<main> problem of overloading C<=> is the fact that these metaphors
885imply different actions on the assignment C<$a = $b> if $a and $b are
886objects. Perl-think implies that $a becomes a reference to whatever
887$b was referencing. Arithmetic-think implies that the value of "object"
888$a is changed to become the value of the object $b, preserving the fact
889that $a and $b are separate entities.
890
891The difference is not relevant in the absence of mutators. After
892a Perl-way assignment an operation which mutates the data referenced by $a
b267980d 893would change the data referenced by $b too. Effectively, after
ee239bfe 894C<$a = $b> values of $a and $b become I<indistinguishable>.
895
b267980d 896On the other hand, anyone who has used algebraic notation knows the
ee239bfe 897expressive power of the arithmetic metaphor. Overloading works hard
898to enable this metaphor while preserving the Perlian way as far as
d1be9408 899possible. Since it is not possible to freely mix two contradicting
ee239bfe 900metaphors, overloading allows the arithmetic way to write things I<as
901far as all the mutators are called via overloaded access only>. The
902way it is done is described in L<Copy Constructor>.
903
904If some mutator methods are directly applied to the overloaded values,
b267980d 905one may need to I<explicitly unlink> other values which references the
ee239bfe 906same value:
907
2b393bf4 908 $a = Data->new(23);
ee239bfe 909 ...
910 $b = $a; # $b is "linked" to $a
911 ...
912 $a = $a->clone; # Unlink $b from $a
913 $a->increment_by(4);
914
915Note that overloaded access makes this transparent:
916
2b393bf4 917 $a = Data->new(23);
ee239bfe 918 $b = $a; # $b is "linked" to $a
919 $a += 4; # would unlink $b automagically
920
921However, it would not make
922
2b393bf4 923 $a = Data->new(23);
ee239bfe 924 $a = 4; # Now $a is a plain 4, not 'Data'
925
926preserve "objectness" of $a. But Perl I<has> a way to make assignments
927to an object do whatever you want. It is just not the overload, but
928tie()ing interface (see L<perlfunc/tie>). Adding a FETCH() method
b267980d 929which returns the object itself, and STORE() method which changes the
ee239bfe 930value of the object, one can reproduce the arithmetic metaphor in its
931completeness, at least for variables which were tie()d from the start.
932
933(Note that a workaround for a bug may be needed, see L<"BUGS">.)
934
935=head1 Cookbook
936
937Please add examples to what follows!
938
939=head2 Two-face scalars
940
941Put this in F<two_face.pm> in your Perl library directory:
942
943 package two_face; # Scalars with separate string and
944 # numeric values.
945 sub new { my $p = shift; bless [@_], $p }
946 use overload '""' => \&str, '0+' => \&num, fallback => 1;
947 sub num {shift->[1]}
948 sub str {shift->[0]}
949
950Use it as follows:
951
952 require two_face;
2b393bf4 953 my $seven = two_face->new("vii", 7);
ee239bfe 954 printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
955 print "seven contains `i'\n" if $seven =~ /i/;
956
957(The second line creates a scalar which has both a string value, and a
958numeric value.) This prints:
959
960 seven=vii, seven=7, eight=8
961 seven contains `i'
962
f5284f61 963=head2 Two-face references
964
965Suppose you want to create an object which is accessible as both an
6d822dc4 966array reference and a hash reference.
f5284f61 967
968 package two_refs;
969 use overload '%{}' => \&gethash, '@{}' => sub { $ {shift()} };
b267980d 970 sub new {
971 my $p = shift;
f5284f61 972 bless \ [@_], $p;
973 }
974 sub gethash {
975 my %h;
976 my $self = shift;
977 tie %h, ref $self, $self;
978 \%h;
979 }
980
981 sub TIEHASH { my $p = shift; bless \ shift, $p }
982 my %fields;
983 my $i = 0;
984 $fields{$_} = $i++ foreach qw{zero one two three};
b267980d 985 sub STORE {
f5284f61 986 my $self = ${shift()};
987 my $key = $fields{shift()};
988 defined $key or die "Out of band access";
989 $$self->[$key] = shift;
990 }
b267980d 991 sub FETCH {
f5284f61 992 my $self = ${shift()};
993 my $key = $fields{shift()};
994 defined $key or die "Out of band access";
995 $$self->[$key];
996 }
997
998Now one can access an object using both the array and hash syntax:
999
2b393bf4 1000 my $bar = two_refs->new(3,4,5,6);
f5284f61 1001 $bar->[2] = 11;
1002 $bar->{two} == 11 or die 'bad hash fetch';
1003
1004Note several important features of this example. First of all, the
1005I<actual> type of $bar is a scalar reference, and we do not overload
1006the scalar dereference. Thus we can get the I<actual> non-overloaded
1007contents of $bar by just using C<$$bar> (what we do in functions which
1008overload dereference). Similarly, the object returned by the
1009TIEHASH() method is a scalar reference.
1010
1011Second, we create a new tied hash each time the hash syntax is used.
1012This allows us not to worry about a possibility of a reference loop,
d1be9408 1013which would lead to a memory leak.
f5284f61 1014
1015Both these problems can be cured. Say, if we want to overload hash
1016dereference on a reference to an object which is I<implemented> as a
1017hash itself, the only problem one has to circumvent is how to access
1fd16925 1018this I<actual> hash (as opposed to the I<virtual> hash exhibited by the
f5284f61 1019overloaded dereference operator). Here is one possible fetching routine:
1020
1021 sub access_hash {
1022 my ($self, $key) = (shift, shift);
1023 my $class = ref $self;
b267980d 1024 bless $self, 'overload::dummy'; # Disable overloading of %{}
f5284f61 1025 my $out = $self->{$key};
1026 bless $self, $class; # Restore overloading
1027 $out;
1028 }
1029
1fd16925 1030To remove creation of the tied hash on each access, one may an extra
f5284f61 1031level of indirection which allows a non-circular structure of references:
1032
1033 package two_refs1;
1034 use overload '%{}' => sub { ${shift()}->[1] },
1035 '@{}' => sub { ${shift()}->[0] };
b267980d 1036 sub new {
1037 my $p = shift;
f5284f61 1038 my $a = [@_];
1039 my %h;
1040 tie %h, $p, $a;
1041 bless \ [$a, \%h], $p;
1042 }
1043 sub gethash {
1044 my %h;
1045 my $self = shift;
1046 tie %h, ref $self, $self;
1047 \%h;
1048 }
1049
1050 sub TIEHASH { my $p = shift; bless \ shift, $p }
1051 my %fields;
1052 my $i = 0;
1053 $fields{$_} = $i++ foreach qw{zero one two three};
b267980d 1054 sub STORE {
f5284f61 1055 my $a = ${shift()};
1056 my $key = $fields{shift()};
1057 defined $key or die "Out of band access";
1058 $a->[$key] = shift;
1059 }
b267980d 1060 sub FETCH {
f5284f61 1061 my $a = ${shift()};
1062 my $key = $fields{shift()};
1063 defined $key or die "Out of band access";
1064 $a->[$key];
1065 }
1066
1fd16925 1067Now if $baz is overloaded like this, then C<$baz> is a reference to a
f5284f61 1068reference to the intermediate array, which keeps a reference to an
1069actual array, and the access hash. The tie()ing object for the access
1fd16925 1070hash is a reference to a reference to the actual array, so
f5284f61 1071
88c28ceb 1072=over
f5284f61 1073
1074=item *
1075
1076There are no loops of references.
1077
1078=item *
1079
1080Both "objects" which are blessed into the class C<two_refs1> are
1081references to a reference to an array, thus references to a I<scalar>.
1082Thus the accessor expression C<$$foo-E<gt>[$ind]> involves no
1083overloaded operations.
1084
1085=back
1086
ee239bfe 1087=head2 Symbolic calculator
1088
1089Put this in F<symbolic.pm> in your Perl library directory:
1090
1091 package symbolic; # Primitive symbolic calculator
1092 use overload nomethod => \&wrap;
1093
1094 sub new { shift; bless ['n', @_] }
1095 sub wrap {
1096 my ($obj, $other, $inv, $meth) = @_;
1097 ($obj, $other) = ($other, $obj) if $inv;
1098 bless [$meth, $obj, $other];
1099 }
1100
1101This module is very unusual as overloaded modules go: it does not
88c28ceb 1102provide any usual overloaded operators, instead it provides the L<Last
1103Resort> operator C<nomethod>. In this example the corresponding
f610777f 1104subroutine returns an object which encapsulates operations done over
2b393bf4 1105the objects: C<< symbolic->new(3) >> contains C<['n', 3]>, C<< 2 +
1106symbolic->new(3) >> contains C<['+', 2, ['n', 3]]>.
ee239bfe 1107
1108Here is an example of the script which "calculates" the side of
1109circumscribed octagon using the above package:
1110
1111 require symbolic;
1112 my $iter = 1; # 2**($iter+2) = 8
2b393bf4 1113 my $side = symbolic->new(1);
ee239bfe 1114 my $cnt = $iter;
3cb6de81 1115
ee239bfe 1116 while ($cnt--) {
1117 $side = (sqrt(1 + $side**2) - 1)/$side;
1118 }
1119 print "OK\n";
1120
1121The value of $side is
1122
1123 ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
1124 undef], 1], ['n', 1]]
1125
1126Note that while we obtained this value using a nice little script,
1127there is no simple way to I<use> this value. In fact this value may
2d3232d7 1128be inspected in debugger (see L<perldebug>), but only if
ee239bfe 1129C<bareStringify> B<O>ption is set, and not via C<p> command.
1130
1131If one attempts to print this value, then the overloaded operator
1132C<""> will be called, which will call C<nomethod> operator. The
1133result of this operator will be stringified again, but this result is
1134again of type C<symbolic>, which will lead to an infinite loop.
1135
1136Add a pretty-printer method to the module F<symbolic.pm>:
1137
1138 sub pretty {
1139 my ($meth, $a, $b) = @{+shift};
1140 $a = 'u' unless defined $a;
1141 $b = 'u' unless defined $b;
1142 $a = $a->pretty if ref $a;
1143 $b = $b->pretty if ref $b;
1144 "[$meth $a $b]";
b267980d 1145 }
ee239bfe 1146
1147Now one can finish the script by
1148
1149 print "side = ", $side->pretty, "\n";
1150
1151The method C<pretty> is doing object-to-string conversion, so it
1152is natural to overload the operator C<""> using this method. However,
1153inside such a method it is not necessary to pretty-print the
1154I<components> $a and $b of an object. In the above subroutine
1155C<"[$meth $a $b]"> is a catenation of some strings and components $a
1156and $b. If these components use overloading, the catenation operator
1fd16925 1157will look for an overloaded operator C<.>; if not present, it will
ee239bfe 1158look for an overloaded operator C<"">. Thus it is enough to use
1159
1160 use overload nomethod => \&wrap, '""' => \&str;
1161 sub str {
1162 my ($meth, $a, $b) = @{+shift};
1163 $a = 'u' unless defined $a;
1164 $b = 'u' unless defined $b;
1165 "[$meth $a $b]";
b267980d 1166 }
ee239bfe 1167
1168Now one can change the last line of the script to
1169
1170 print "side = $side\n";
1171
1172which outputs
1173
1174 side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
1175
1176and one can inspect the value in debugger using all the possible
b267980d 1177methods.
ee239bfe 1178
d1be9408 1179Something is still amiss: consider the loop variable $cnt of the
ee239bfe 1180script. It was a number, not an object. We cannot make this value of
1181type C<symbolic>, since then the loop will not terminate.
1182
1183Indeed, to terminate the cycle, the $cnt should become false.
1184However, the operator C<bool> for checking falsity is overloaded (this
1185time via overloaded C<"">), and returns a long string, thus any object
1186of type C<symbolic> is true. To overcome this, we need a way to
1187compare an object to 0. In fact, it is easier to write a numeric
1188conversion routine.
1189
1190Here is the text of F<symbolic.pm> with such a routine added (and
f610777f 1191slightly modified str()):
ee239bfe 1192
1193 package symbolic; # Primitive symbolic calculator
1194 use overload
1195 nomethod => \&wrap, '""' => \&str, '0+' => \&num;
1196
1197 sub new { shift; bless ['n', @_] }
1198 sub wrap {
1199 my ($obj, $other, $inv, $meth) = @_;
1200 ($obj, $other) = ($other, $obj) if $inv;
1201 bless [$meth, $obj, $other];
1202 }
1203 sub str {
1204 my ($meth, $a, $b) = @{+shift};
1205 $a = 'u' unless defined $a;
1206 if (defined $b) {
1207 "[$meth $a $b]";
1208 } else {
1209 "[$meth $a]";
1210 }
b267980d 1211 }
1212 my %subr = ( n => sub {$_[0]},
1213 sqrt => sub {sqrt $_[0]},
ee239bfe 1214 '-' => sub {shift() - shift()},
1215 '+' => sub {shift() + shift()},
1216 '/' => sub {shift() / shift()},
1217 '*' => sub {shift() * shift()},
1218 '**' => sub {shift() ** shift()},
1219 );
1220 sub num {
1221 my ($meth, $a, $b) = @{+shift};
b267980d 1222 my $subr = $subr{$meth}
ee239bfe 1223 or die "Do not know how to ($meth) in symbolic";
1224 $a = $a->num if ref $a eq __PACKAGE__;
1225 $b = $b->num if ref $b eq __PACKAGE__;
1226 $subr->($a,$b);
1227 }
1228
1229All the work of numeric conversion is done in %subr and num(). Of
f610777f 1230course, %subr is not complete, it contains only operators used in the
ee239bfe 1231example below. Here is the extra-credit question: why do we need an
1232explicit recursion in num()? (Answer is at the end of this section.)
1233
1234Use this module like this:
1235
1236 require symbolic;
2b393bf4 1237 my $iter = symbolic->new(2); # 16-gon
1238 my $side = symbolic->new(1);
ee239bfe 1239 my $cnt = $iter;
3cb6de81 1240
ee239bfe 1241 while ($cnt) {
1242 $cnt = $cnt - 1; # Mutator `--' not implemented
1243 $side = (sqrt(1 + $side**2) - 1)/$side;
1244 }
1245 printf "%s=%f\n", $side, $side;
1246 printf "pi=%f\n", $side*(2**($iter+2));
1247
1248It prints (without so many line breaks)
1249
1250 [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
1251 [n 1]] 2]]] 1]
1252 [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
1253 pi=3.182598
1254
1255The above module is very primitive. It does not implement
1256mutator methods (C<++>, C<-=> and so on), does not do deep copying
1257(not required without mutators!), and implements only those arithmetic
1258operations which are used in the example.
1259
1fd16925 1260To implement most arithmetic operations is easy; one should just use
ee239bfe 1261the tables of operations, and change the code which fills %subr to
1262
1263 my %subr = ( 'n' => sub {$_[0]} );
1264 foreach my $op (split " ", $overload::ops{with_assign}) {
1265 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1266 }
1267 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1268 foreach my $op (split " ", "@overload::ops{ @bins }") {
1269 $subr{$op} = eval "sub {shift() $op shift()}";
1270 }
1271 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1272 print "defining `$op'\n";
1273 $subr{$op} = eval "sub {$op shift()}";
1274 }
1275
1276Due to L<Calling Conventions for Mutators>, we do not need anything
1277special to make C<+=> and friends work, except filling C<+=> entry of
1278%subr, and defining a copy constructor (needed since Perl has no
1279way to know that the implementation of C<'+='> does not mutate
1280the argument, compare L<Copy Constructor>).
1281
1fd16925 1282To implement a copy constructor, add C<< '=' => \&cpy >> to C<use overload>
ee239bfe 1283line, and code (this code assumes that mutators change things one level
1284deep only, so recursive copying is not needed):
1285
1286 sub cpy {
1287 my $self = shift;
1288 bless [@$self], ref $self;
1289 }
1290
b267980d 1291To make C<++> and C<--> work, we need to implement actual mutators,
ee239bfe 1292either directly, or in C<nomethod>. We continue to do things inside
1293C<nomethod>, thus add
1294
1295 if ($meth eq '++' or $meth eq '--') {
1296 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
1297 return $obj;
1298 }
1299
b267980d 1300after the first line of wrap(). This is not a most effective
ee239bfe 1301implementation, one may consider
1302
1303 sub inc { $_[0] = bless ['++', shift, 1]; }
1304
1305instead.
1306
1307As a final remark, note that one can fill %subr by
1308
1309 my %subr = ( 'n' => sub {$_[0]} );
1310 foreach my $op (split " ", $overload::ops{with_assign}) {
1311 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1312 }
1313 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1314 foreach my $op (split " ", "@overload::ops{ @bins }") {
1315 $subr{$op} = eval "sub {shift() $op shift()}";
1316 }
1317 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1318 $subr{$op} = eval "sub {$op shift()}";
1319 }
1320 $subr{'++'} = $subr{'+'};
1321 $subr{'--'} = $subr{'-'};
1322
b267980d 1323This finishes implementation of a primitive symbolic calculator in
132450 lines of Perl code. Since the numeric values of subexpressions
ee239bfe 1325are not cached, the calculator is very slow.
1326
1327Here is the answer for the exercise: In the case of str(), we need no
1328explicit recursion since the overloaded C<.>-operator will fall back
1329to an existing overloaded operator C<"">. Overloaded arithmetic
1330operators I<do not> fall back to numeric conversion if C<fallback> is
1331not explicitly requested. Thus without an explicit recursion num()
1332would convert C<['+', $a, $b]> to C<$a + $b>, which would just rebuild
1333the argument of num().
1334
1335If you wonder why defaults for conversion are different for str() and
1336num(), note how easy it was to write the symbolic calculator. This
1337simplicity is due to an appropriate choice of defaults. One extra
f610777f 1338note: due to the explicit recursion num() is more fragile than sym():
1339we need to explicitly check for the type of $a and $b. If components
ee239bfe 1340$a and $b happen to be of some related type, this may lead to problems.
1341
1342=head2 I<Really> symbolic calculator
1343
1344One may wonder why we call the above calculator symbolic. The reason
1345is that the actual calculation of the value of expression is postponed
1346until the value is I<used>.
1347
1348To see it in action, add a method
1349
b267980d 1350 sub STORE {
1351 my $obj = shift;
1352 $#$obj = 1;
ee239bfe 1353 @$obj->[0,1] = ('=', shift);
1354 }
1355
1356to the package C<symbolic>. After this change one can do
1357
2b393bf4 1358 my $a = symbolic->new(3);
1359 my $b = symbolic->new(4);
ee239bfe 1360 my $c = sqrt($a**2 + $b**2);
1361
1362and the numeric value of $c becomes 5. However, after calling
1363
1364 $a->STORE(12); $b->STORE(5);
1365
1366the numeric value of $c becomes 13. There is no doubt now that the module
1367symbolic provides a I<symbolic> calculator indeed.
1368
1369To hide the rough edges under the hood, provide a tie()d interface to the
1370package C<symbolic> (compare with L<Metaphor clash>). Add methods
1371
1372 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
1373 sub FETCH { shift }
1374 sub nop { } # Around a bug
1375
1376(the bug is described in L<"BUGS">). One can use this new interface as
1377
1378 tie $a, 'symbolic', 3;
1379 tie $b, 'symbolic', 4;
1380 $a->nop; $b->nop; # Around a bug
1381
1382 my $c = sqrt($a**2 + $b**2);
1383
1384Now numeric value of $c is 5. After C<$a = 12; $b = 5> the numeric value
1385of $c becomes 13. To insulate the user of the module add a method
1386
1387 sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
1388
1389Now
1390
1391 my ($a, $b);
1392 symbolic->vars($a, $b);
1393 my $c = sqrt($a**2 + $b**2);
1394
1395 $a = 3; $b = 4;
1396 printf "c5 %s=%f\n", $c, $c;
1397
1398 $a = 12; $b = 5;
1399 printf "c13 %s=%f\n", $c, $c;
1400
1401shows that the numeric value of $c follows changes to the values of $a
1402and $b.
1403
4633a7c4 1404=head1 AUTHOR
1405
1fef88e7 1406Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>.
4633a7c4 1407
7e494759 1408=head1 SEE ALSO
1409
1410The L<overloading> pragma can be used to enable or disable overloaded
1411operations within a lexical scope.
1412
4633a7c4 1413=head1 DIAGNOSTICS
1414
1415When Perl is run with the B<-Do> switch or its equivalent, overloading
1416induces diagnostic messages.
1417
e7ea3e70 1418Using the C<m> command of Perl debugger (see L<perldebug>) one can
1419deduce which operations are overloaded (and which ancestor triggers
1420this overloading). Say, if C<eq> is overloaded, then the method C<(eq>
1421is shown by debugger. The method C<()> corresponds to the C<fallback>
1422key (in fact a presence of this method shows that this package has
1423overloading enabled, and it is what is used by the C<Overloaded>
ee239bfe 1424function of module C<overload>).
e7ea3e70 1425
6ad11d81 1426The module might issue the following warnings:
6b82e2f5 1427
1428=over 4
1429
1430=item Odd number of arguments for overload::constant
1431
1432(W) The call to overload::constant contained an odd number of arguments.
1433The arguments should come in pairs.
1434
1435=item `%s' is not an overloadable type
1436
1437(W) You tried to overload a constant type the overload package is unaware of.
1438
1439=item `%s' is not a code reference
1440
1441(W) The second (fourth, sixth, ...) argument of overload::constant needs
1442to be a code reference. Either an anonymous subroutine, or a reference
1443to a subroutine.
1444
1445=back
1446
4633a7c4 1447=head1 BUGS
1448
aa689395 1449Because it is used for overloading, the per-package hash %OVERLOAD now
1450has a special meaning in Perl. The symbol table is filled with names
1451looking like line-noise.
4633a7c4 1452
a6006777 1453For the purpose of inheritance every overloaded package behaves as if
1454C<fallback> is present (possibly undefined). This may create
1455interesting effects if some package is not overloaded, but inherits
1456from two overloaded packages.
4633a7c4 1457
b267980d 1458Relation between overloading and tie()ing is broken. Overloading is
ee239bfe 1459triggered or not basing on the I<previous> class of tie()d value.
1460
b267980d 1461This happens because the presence of overloading is checked too early,
ee239bfe 1462before any tie()d access is attempted. If the FETCH()ed class of the
b267980d 1463tie()d value does not change, a simple workaround is to access the value
ee239bfe 1464immediately after tie()ing, so that after this call the I<previous> class
1465coincides with the current one.
1466
1467B<Needed:> a way to fix this without a speed penalty.
1468
b3ac6de7 1469Barewords are not covered by overloaded string constants.
1470
ee239bfe 1471This document is confusing. There are grammos and misleading language
1472used in places. It would seem a total rewrite is needed.
4633a7c4 1473
1474=cut
1475