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