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