Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1422 lines
46 KiB

  1. package overload;
  2. $overload::hint_bits = 0x20000;
  3. sub nil {}
  4. sub OVERLOAD {
  5. $package = shift;
  6. my %arg = @_;
  7. my ($sub, $fb);
  8. $ {$package . "::OVERLOAD"}{dummy}++; # Register with magic by touching.
  9. *{$package . "::()"} = \&nil; # Make it findable via fetchmethod.
  10. for (keys %arg) {
  11. if ($_ eq 'fallback') {
  12. $fb = $arg{$_};
  13. } else {
  14. $sub = $arg{$_};
  15. if (not ref $sub and $sub !~ /::/) {
  16. $ {$package . "::(" . $_} = $sub;
  17. $sub = \&nil;
  18. }
  19. #print STDERR "Setting `$ {'package'}::\cO$_' to \\&`$sub'.\n";
  20. *{$package . "::(" . $_} = \&{ $sub };
  21. }
  22. }
  23. ${$package . "::()"} = $fb; # Make it findable too (fallback only).
  24. }
  25. sub import {
  26. $package = (caller())[0];
  27. # *{$package . "::OVERLOAD"} = \&OVERLOAD;
  28. shift;
  29. $package->overload::OVERLOAD(@_);
  30. }
  31. sub unimport {
  32. $package = (caller())[0];
  33. ${$package . "::OVERLOAD"}{dummy}++; # Upgrade the table
  34. shift;
  35. for (@_) {
  36. if ($_ eq 'fallback') {
  37. undef $ {$package . "::()"};
  38. } else {
  39. delete $ {$package . "::"}{"(" . $_};
  40. }
  41. }
  42. }
  43. sub Overloaded {
  44. my $package = shift;
  45. $package = ref $package if ref $package;
  46. $package->can('()');
  47. }
  48. sub ov_method {
  49. my $globref = shift;
  50. return undef unless $globref;
  51. my $sub = \&{*$globref};
  52. return $sub if $sub ne \&nil;
  53. return shift->can($ {*$globref});
  54. }
  55. sub OverloadedStringify {
  56. my $package = shift;
  57. $package = ref $package if ref $package;
  58. #$package->can('(""')
  59. ov_method mycan($package, '(""'), $package
  60. or ov_method mycan($package, '(0+'), $package
  61. or ov_method mycan($package, '(bool'), $package
  62. or ov_method mycan($package, '(nomethod'), $package;
  63. }
  64. sub Method {
  65. my $package = shift;
  66. $package = ref $package if ref $package;
  67. #my $meth = $package->can('(' . shift);
  68. ov_method mycan($package, '(' . shift), $package;
  69. #return $meth if $meth ne \&nil;
  70. #return $ {*{$meth}};
  71. }
  72. sub AddrRef {
  73. my $package = ref $_[0];
  74. return "$_[0]" unless $package;
  75. bless $_[0], overload::Fake; # Non-overloaded package
  76. my $str = "$_[0]";
  77. bless $_[0], $package; # Back
  78. $package . substr $str, index $str, '=';
  79. }
  80. sub StrVal {
  81. (OverloadedStringify($_[0]) or ref($_[0]) eq 'Regexp') ?
  82. (AddrRef(shift)) :
  83. "$_[0]";
  84. }
  85. sub mycan { # Real can would leave stubs.
  86. my ($package, $meth) = @_;
  87. return \*{$package . "::$meth"} if defined &{$package . "::$meth"};
  88. my $p;
  89. foreach $p (@{$package . "::ISA"}) {
  90. my $out = mycan($p, $meth);
  91. return $out if $out;
  92. }
  93. return undef;
  94. }
  95. %constants = (
  96. 'integer' => 0x1000,
  97. 'float' => 0x2000,
  98. 'binary' => 0x4000,
  99. 'q' => 0x8000,
  100. 'qr' => 0x10000,
  101. );
  102. %ops = ( with_assign => "+ - * / % ** << >> x .",
  103. assign => "+= -= *= /= %= **= <<= >>= x= .=",
  104. num_comparison => "< <= > >= == !=",
  105. '3way_comparison'=> "<=> cmp",
  106. str_comparison => "lt le gt ge eq ne",
  107. binary => "& | ^",
  108. unary => "neg ! ~",
  109. mutators => '++ --',
  110. func => "atan2 cos sin exp abs log sqrt",
  111. conversion => 'bool "" 0+',
  112. iterators => '<>',
  113. dereferencing => '${} @{} %{} &{} *{}',
  114. special => 'nomethod fallback =');
  115. use warnings::register;
  116. sub constant {
  117. # Arguments: what, sub
  118. while (@_) {
  119. if (@_ == 1) {
  120. warnings::warnif ("Odd number of arguments for overload::constant");
  121. last;
  122. }
  123. elsif (!exists $constants {$_ [0]}) {
  124. warnings::warnif ("`$_[0]' is not an overloadable type");
  125. }
  126. elsif (!ref $_ [1] || "$_[1]" !~ /CODE\(0x[\da-f]+\)$/) {
  127. # Can't use C<ref $_[1] eq "CODE"> above as code references can be
  128. # blessed, and C<ref> would return the package the ref is blessed into.
  129. if (warnings::enabled) {
  130. $_ [1] = "undef" unless defined $_ [1];
  131. warnings::warn ("`$_[1]' is not a code reference");
  132. }
  133. }
  134. else {
  135. $^H{$_[0]} = $_[1];
  136. $^H |= $constants{$_[0]} | $overload::hint_bits;
  137. }
  138. shift, shift;
  139. }
  140. }
  141. sub remove_constant {
  142. # Arguments: what, sub
  143. while (@_) {
  144. delete $^H{$_[0]};
  145. $^H &= ~ $constants{$_[0]};
  146. shift, shift;
  147. }
  148. }
  149. 1;
  150. __END__
  151. =head1 NAME
  152. overload - Package for overloading perl operations
  153. =head1 SYNOPSIS
  154. package SomeThing;
  155. use overload
  156. '+' => \&myadd,
  157. '-' => \&mysub;
  158. # etc
  159. ...
  160. package main;
  161. $a = new SomeThing 57;
  162. $b=5+$a;
  163. ...
  164. if (overload::Overloaded $b) {...}
  165. ...
  166. $strval = overload::StrVal $b;
  167. =head1 DESCRIPTION
  168. =head2 Declaration of overloaded functions
  169. The compilation directive
  170. package Number;
  171. use overload
  172. "+" => \&add,
  173. "*=" => "muas";
  174. declares function Number::add() for addition, and method muas() in
  175. the "class" C<Number> (or one of its base classes)
  176. for the assignment form C<*=> of multiplication.
  177. Arguments of this directive come in (key, value) pairs. Legal values
  178. are values legal inside a C<&{ ... }> call, so the name of a
  179. subroutine, a reference to a subroutine, or an anonymous subroutine
  180. will all work. Note that values specified as strings are
  181. interpreted as methods, not subroutines. Legal keys are listed below.
  182. The subroutine C<add> will be called to execute C<$a+$b> if $a
  183. is a reference to an object blessed into the package C<Number>, or if $a is
  184. not an object from a package with defined mathemagic addition, but $b is a
  185. reference to a C<Number>. It can also be called in other situations, like
  186. C<$a+=7>, or C<$a++>. See L<MAGIC AUTOGENERATION>. (Mathemagical
  187. methods refer to methods triggered by an overloaded mathematical
  188. operator.)
  189. Since overloading respects inheritance via the @ISA hierarchy, the
  190. above declaration would also trigger overloading of C<+> and C<*=> in
  191. all the packages which inherit from C<Number>.
  192. =head2 Calling Conventions for Binary Operations
  193. The functions specified in the C<use overload ...> directive are called
  194. with three (in one particular case with four, see L<Last Resort>)
  195. arguments. If the corresponding operation is binary, then the first
  196. two arguments are the two arguments of the operation. However, due to
  197. general object calling conventions, the first argument should always be
  198. an object in the package, so in the situation of C<7+$a>, the
  199. order of the arguments is interchanged. It probably does not matter
  200. when implementing the addition method, but whether the arguments
  201. are reversed is vital to the subtraction method. The method can
  202. query this information by examining the third argument, which can take
  203. three different values:
  204. =over 7
  205. =item FALSE
  206. the order of arguments is as in the current operation.
  207. =item TRUE
  208. the arguments are reversed.
  209. =item C<undef>
  210. the current operation is an assignment variant (as in
  211. C<$a+=7>), but the usual function is called instead. This additional
  212. information can be used to generate some optimizations. Compare
  213. L<Calling Conventions for Mutators>.
  214. =back
  215. =head2 Calling Conventions for Unary Operations
  216. Unary operation are considered binary operations with the second
  217. argument being C<undef>. Thus the functions that overloads C<{"++"}>
  218. is called with arguments C<($a,undef,'')> when $a++ is executed.
  219. =head2 Calling Conventions for Mutators
  220. Two types of mutators have different calling conventions:
  221. =over
  222. =item C<++> and C<-->
  223. The routines which implement these operators are expected to actually
  224. I<mutate> their arguments. So, assuming that $obj is a reference to a
  225. number,
  226. sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \$n}
  227. is an appropriate implementation of overloaded C<++>. Note that
  228. sub incr { ++$ {$_[0]} ; shift }
  229. is OK if used with preincrement and with postincrement. (In the case
  230. of postincrement a copying will be performed, see L<Copy Constructor>.)
  231. =item C<x=> and other assignment versions
  232. There is nothing special about these methods. They may change the
  233. value of their arguments, and may leave it as is. The result is going
  234. to be assigned to the value in the left-hand-side if different from
  235. this value.
  236. This allows for the same method to be used as overloaded C<+=> and
  237. C<+>. Note that this is I<allowed>, but not recommended, since by the
  238. semantic of L<"Fallback"> Perl will call the method for C<+> anyway,
  239. if C<+=> is not overloaded.
  240. =back
  241. B<Warning.> Due to the presense of assignment versions of operations,
  242. routines which may be called in assignment context may create
  243. self-referential structures. Currently Perl will not free self-referential
  244. structures until cycles are C<explicitly> broken. You may get problems
  245. when traversing your structures too.
  246. Say,
  247. use overload '+' => sub { bless [ \$_[0], \$_[1] ] };
  248. is asking for trouble, since for code C<$obj += $foo> the subroutine
  249. is called as C<$obj = add($obj, $foo, undef)>, or C<$obj = [\$obj,
  250. \$foo]>. If using such a subroutine is an important optimization, one
  251. can overload C<+=> explicitly by a non-"optimized" version, or switch
  252. to non-optimized version if C<not defined $_[2]> (see
  253. L<Calling Conventions for Binary Operations>).
  254. Even if no I<explicit> assignment-variants of operators are present in
  255. the script, they may be generated by the optimizer. Say, C<",$obj,"> or
  256. C<',' . $obj . ','> may be both optimized to
  257. my $tmp = ',' . $obj; $tmp .= ',';
  258. =head2 Overloadable Operations
  259. The following symbols can be specified in C<use overload> directive:
  260. =over 5
  261. =item * I<Arithmetic operations>
  262. "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
  263. "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
  264. For these operations a substituted non-assignment variant can be called if
  265. the assignment variant is not available. Methods for operations "C<+>",
  266. "C<->", "C<+=>", and "C<-=>" can be called to automatically generate
  267. increment and decrement methods. The operation "C<->" can be used to
  268. autogenerate missing methods for unary minus or C<abs>.
  269. See L<"MAGIC AUTOGENERATION">, L<"Calling Conventions for Mutators"> and
  270. L<"Calling Conventions for Binary Operations">) for details of these
  271. substitutions.
  272. =item * I<Comparison operations>
  273. "<", "<=", ">", ">=", "==", "!=", "<=>",
  274. "lt", "le", "gt", "ge", "eq", "ne", "cmp",
  275. If the corresponding "spaceship" variant is available, it can be
  276. used to substitute for the missing operation. During C<sort>ing
  277. arrays, C<cmp> is used to compare values subject to C<use overload>.
  278. =item * I<Bit operations>
  279. "&", "^", "|", "neg", "!", "~",
  280. "C<neg>" stands for unary minus. If the method for C<neg> is not
  281. specified, it can be autogenerated using the method for
  282. subtraction. If the method for "C<!>" is not specified, it can be
  283. autogenerated using the methods for "C<bool>", or "C<\"\">", or "C<0+>".
  284. =item * I<Increment and decrement>
  285. "++", "--",
  286. If undefined, addition and subtraction methods can be
  287. used instead. These operations are called both in prefix and
  288. postfix form.
  289. =item * I<Transcendental functions>
  290. "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
  291. If C<abs> is unavailable, it can be autogenerated using methods
  292. for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
  293. =item * I<Boolean, string and numeric conversion>
  294. "bool", "\"\"", "0+",
  295. If one or two of these operations are not overloaded, the remaining ones can
  296. be used instead. C<bool> is used in the flow control operators
  297. (like C<while>) and for the ternary "C<?:>" operation. These functions can
  298. return any arbitrary Perl value. If the corresponding operation for this value
  299. is overloaded too, that operation will be called again with this value.
  300. As a special case if the overload returns the object itself then it will
  301. be used directly. An overloaded conversion returning the object is
  302. probably a bug, because you're likely to get something that looks like
  303. C<YourPackage=HASH(0x8172b34)>.
  304. =item * I<Iteration>
  305. "<>"
  306. If not overloaded, the argument will be converted to a filehandle or
  307. glob (which may require a stringification). The same overloading
  308. happens both for the I<read-filehandle> syntax C<E<lt>$varE<gt>> and
  309. I<globbing> syntax C<E<lt>${var}E<gt>>.
  310. =item * I<Dereferencing>
  311. '${}', '@{}', '%{}', '&{}', '*{}'.
  312. If not overloaded, the argument will be dereferenced I<as is>, thus
  313. should be of correct type. These functions should return a reference
  314. of correct type, or another object with overloaded dereferencing.
  315. As a special case if the overload returns the object itself then it
  316. will be used directly (provided it is the correct type).
  317. The dereference operators must be specified explicitly they will not be passed to
  318. "nomethod".
  319. =item * I<Special>
  320. "nomethod", "fallback", "=",
  321. see L<SPECIAL SYMBOLS FOR C<use overload>>.
  322. =back
  323. See L<"Fallback"> for an explanation of when a missing method can be
  324. autogenerated.
  325. A computer-readable form of the above table is available in the hash
  326. %overload::ops, with values being space-separated lists of names:
  327. with_assign => '+ - * / % ** << >> x .',
  328. assign => '+= -= *= /= %= **= <<= >>= x= .=',
  329. num_comparison => '< <= > >= == !=',
  330. '3way_comparison'=> '<=> cmp',
  331. str_comparison => 'lt le gt ge eq ne',
  332. binary => '& | ^',
  333. unary => 'neg ! ~',
  334. mutators => '++ --',
  335. func => 'atan2 cos sin exp abs log sqrt',
  336. conversion => 'bool "" 0+',
  337. iterators => '<>',
  338. dereferencing => '${} @{} %{} &{} *{}',
  339. special => 'nomethod fallback ='
  340. =head2 Inheritance and overloading
  341. Inheritance interacts with overloading in two ways.
  342. =over
  343. =item Strings as values of C<use overload> directive
  344. If C<value> in
  345. use overload key => value;
  346. is a string, it is interpreted as a method name.
  347. =item Overloading of an operation is inherited by derived classes
  348. Any class derived from an overloaded class is also overloaded. The
  349. set of overloaded methods is the union of overloaded methods of all
  350. the ancestors. If some method is overloaded in several ancestor, then
  351. which description will be used is decided by the usual inheritance
  352. rules:
  353. If C<A> inherits from C<B> and C<C> (in this order), C<B> overloads
  354. C<+> with C<\&D::plus_sub>, and C<C> overloads C<+> by C<"plus_meth">,
  355. then the subroutine C<D::plus_sub> will be called to implement
  356. operation C<+> for an object in package C<A>.
  357. =back
  358. Note that since the value of the C<fallback> key is not a subroutine,
  359. its inheritance is not governed by the above rules. In the current
  360. implementation, the value of C<fallback> in the first overloaded
  361. ancestor is used, but this is accidental and subject to change.
  362. =head1 SPECIAL SYMBOLS FOR C<use overload>
  363. Three keys are recognized by Perl that are not covered by the above
  364. description.
  365. =head2 Last Resort
  366. C<"nomethod"> should be followed by a reference to a function of four
  367. parameters. If defined, it is called when the overloading mechanism
  368. cannot find a method for some operation. The first three arguments of
  369. this function coincide with the arguments for the corresponding method if
  370. it were found, the fourth argument is the symbol
  371. corresponding to the missing method. If several methods are tried,
  372. the last one is used. Say, C<1-$a> can be equivalent to
  373. &nomethodMethod($a,1,1,"-")
  374. if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
  375. C<use overload> directive.
  376. The C<"nomethod"> mechanism is I<not> used for the dereference operators
  377. ( ${} @{} %{} &{} *{} ).
  378. If some operation cannot be resolved, and there is no function
  379. assigned to C<"nomethod">, then an exception will be raised via die()--
  380. unless C<"fallback"> was specified as a key in C<use overload> directive.
  381. =head2 Fallback
  382. The key C<"fallback"> governs what to do if a method for a particular
  383. operation is not found. Three different cases are possible depending on
  384. the value of C<"fallback">:
  385. =over 16
  386. =item * C<undef>
  387. Perl tries to use a
  388. substituted method (see L<MAGIC AUTOGENERATION>). If this fails, it
  389. then tries to calls C<"nomethod"> value; if missing, an exception
  390. will be raised.
  391. =item * TRUE
  392. The same as for the C<undef> value, but no exception is raised. Instead,
  393. it silently reverts to what it would have done were there no C<use overload>
  394. present.
  395. =item * defined, but FALSE
  396. No autogeneration is tried. Perl tries to call
  397. C<"nomethod"> value, and if this is missing, raises an exception.
  398. =back
  399. B<Note.> C<"fallback"> inheritance via @ISA is not carved in stone
  400. yet, see L<"Inheritance and overloading">.
  401. =head2 Copy Constructor
  402. The value for C<"="> is a reference to a function with three
  403. arguments, i.e., it looks like the other values in C<use
  404. overload>. However, it does not overload the Perl assignment
  405. operator. This would go against Camel hair.
  406. This operation is called in the situations when a mutator is applied
  407. to a reference that shares its object with some other reference, such
  408. as
  409. $a=$b;
  410. ++$a;
  411. To make this change $a and not change $b, a copy of C<$$a> is made,
  412. and $a is assigned a reference to this new object. This operation is
  413. done during execution of the C<++$a>, and not during the assignment,
  414. (so before the increment C<$$a> coincides with C<$$b>). This is only
  415. done if C<++> is expressed via a method for C<'++'> or C<'+='> (or
  416. C<nomethod>). Note that if this operation is expressed via C<'+'>
  417. a nonmutator, i.e., as in
  418. $a=$b;
  419. $a=$a+1;
  420. then C<$a> does not reference a new copy of C<$$a>, since $$a does not
  421. appear as lvalue when the above code is executed.
  422. If the copy constructor is required during the execution of some mutator,
  423. but a method for C<'='> was not specified, it can be autogenerated as a
  424. string copy if the object is a plain scalar.
  425. =over 5
  426. =item B<Example>
  427. The actually executed code for
  428. $a=$b;
  429. Something else which does not modify $a or $b....
  430. ++$a;
  431. may be
  432. $a=$b;
  433. Something else which does not modify $a or $b....
  434. $a = $a->clone(undef,"");
  435. $a->incr(undef,"");
  436. if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
  437. C<'='> was overloaded with C<\&clone>.
  438. =back
  439. Same behaviour is triggered by C<$b = $a++>, which is consider a synonym for
  440. C<$b = $a; ++$a>.
  441. =head1 MAGIC AUTOGENERATION
  442. If a method for an operation is not found, and the value for C<"fallback"> is
  443. TRUE or undefined, Perl tries to autogenerate a substitute method for
  444. the missing operation based on the defined operations. Autogenerated method
  445. substitutions are possible for the following operations:
  446. =over 16
  447. =item I<Assignment forms of arithmetic operations>
  448. C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
  449. is not defined.
  450. =item I<Conversion operations>
  451. String, numeric, and boolean conversion are calculated in terms of one
  452. another if not all of them are defined.
  453. =item I<Increment and decrement>
  454. The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
  455. and C<$a--> in terms of C<$a-=1> and C<$a-1>.
  456. =item C<abs($a)>
  457. can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
  458. =item I<Unary minus>
  459. can be expressed in terms of subtraction.
  460. =item I<Negation>
  461. C<!> and C<not> can be expressed in terms of boolean conversion, or
  462. string or numerical conversion.
  463. =item I<Concatenation>
  464. can be expressed in terms of string conversion.
  465. =item I<Comparison operations>
  466. can be expressed in terms of its "spaceship" counterpart: either
  467. C<E<lt>=E<gt>> or C<cmp>:
  468. <, >, <=, >=, ==, != in terms of <=>
  469. lt, gt, le, ge, eq, ne in terms of cmp
  470. =item I<Iterator>
  471. <> in terms of builtin operations
  472. =item I<Dereferencing>
  473. ${} @{} %{} &{} *{} in terms of builtin operations
  474. =item I<Copy operator>
  475. can be expressed in terms of an assignment to the dereferenced value, if this
  476. value is a scalar and not a reference.
  477. =back
  478. =head1 Losing overloading
  479. The restriction for the comparison operation is that even if, for example,
  480. `C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
  481. function will produce only a standard logical value based on the
  482. numerical value of the result of `C<cmp>'. In particular, a working
  483. numeric conversion is needed in this case (possibly expressed in terms of
  484. other conversions).
  485. Similarly, C<.=> and C<x=> operators lose their mathemagical properties
  486. if the string conversion substitution is applied.
  487. When you chop() a mathemagical object it is promoted to a string and its
  488. mathemagical properties are lost. The same can happen with other
  489. operations as well.
  490. =head1 Run-time Overloading
  491. Since all C<use> directives are executed at compile-time, the only way to
  492. change overloading during run-time is to
  493. eval 'use overload "+" => \&addmethod';
  494. You can also use
  495. eval 'no overload "+", "--", "<="';
  496. though the use of these constructs during run-time is questionable.
  497. =head1 Public functions
  498. Package C<overload.pm> provides the following public functions:
  499. =over 5
  500. =item overload::StrVal(arg)
  501. Gives string value of C<arg> as in absence of stringify overloading.
  502. =item overload::Overloaded(arg)
  503. Returns true if C<arg> is subject to overloading of some operations.
  504. =item overload::Method(obj,op)
  505. Returns C<undef> or a reference to the method that implements C<op>.
  506. =back
  507. =head1 Overloading constants
  508. For some application Perl parser mangles constants too much. It is possible
  509. to hook into this process via overload::constant() and overload::remove_constant()
  510. functions.
  511. These functions take a hash as an argument. The recognized keys of this hash
  512. are
  513. =over 8
  514. =item integer
  515. to overload integer constants,
  516. =item float
  517. to overload floating point constants,
  518. =item binary
  519. to overload octal and hexadecimal constants,
  520. =item q
  521. to overload C<q>-quoted strings, constant pieces of C<qq>- and C<qx>-quoted
  522. strings and here-documents,
  523. =item qr
  524. to overload constant pieces of regular expressions.
  525. =back
  526. The corresponding values are references to functions which take three arguments:
  527. the first one is the I<initial> string form of the constant, the second one
  528. is how Perl interprets this constant, the third one is how the constant is used.
  529. Note that the initial string form does not
  530. contain string delimiters, and has backslashes in backslash-delimiter
  531. combinations stripped (thus the value of delimiter is not relevant for
  532. processing of this string). The return value of this function is how this
  533. constant is going to be interpreted by Perl. The third argument is undefined
  534. unless for overloaded C<q>- and C<qr>- constants, it is C<q> in single-quote
  535. context (comes from strings, regular expressions, and single-quote HERE
  536. documents), it is C<tr> for arguments of C<tr>/C<y> operators,
  537. it is C<s> for right-hand side of C<s>-operator, and it is C<qq> otherwise.
  538. Since an expression C<"ab$cd,,"> is just a shortcut for C<'ab' . $cd . ',,'>,
  539. it is expected that overloaded constant strings are equipped with reasonable
  540. overloaded catenation operator, otherwise absurd results will result.
  541. Similarly, negative numbers are considered as negations of positive constants.
  542. Note that it is probably meaningless to call the functions overload::constant()
  543. and overload::remove_constant() from anywhere but import() and unimport() methods.
  544. From these methods they may be called as
  545. sub import {
  546. shift;
  547. return unless @_;
  548. die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
  549. overload::constant integer => sub {Math::BigInt->new(shift)};
  550. }
  551. B<BUGS> Currently overloaded-ness of constants does not propagate
  552. into C<eval '...'>.
  553. =head1 IMPLEMENTATION
  554. What follows is subject to change RSN.
  555. The table of methods for all operations is cached in magic for the
  556. symbol table hash for the package. The cache is invalidated during
  557. processing of C<use overload>, C<no overload>, new function
  558. definitions, and changes in @ISA. However, this invalidation remains
  559. unprocessed until the next C<bless>ing into the package. Hence if you
  560. want to change overloading structure dynamically, you'll need an
  561. additional (fake) C<bless>ing to update the table.
  562. (Every SVish thing has a magic queue, and magic is an entry in that
  563. queue. This is how a single variable may participate in multiple
  564. forms of magic simultaneously. For instance, environment variables
  565. regularly have two forms at once: their %ENV magic and their taint
  566. magic. However, the magic which implements overloading is applied to
  567. the stashes, which are rarely used directly, thus should not slow down
  568. Perl.)
  569. If an object belongs to a package using overload, it carries a special
  570. flag. Thus the only speed penalty during arithmetic operations without
  571. overloading is the checking of this flag.
  572. In fact, if C<use overload> is not present, there is almost no overhead
  573. for overloadable operations, so most programs should not suffer
  574. measurable performance penalties. A considerable effort was made to
  575. minimize the overhead when overload is used in some package, but the
  576. arguments in question do not belong to packages using overload. When
  577. in doubt, test your speed with C<use overload> and without it. So far
  578. there have been no reports of substantial speed degradation if Perl is
  579. compiled with optimization turned on.
  580. There is no size penalty for data if overload is not used. The only
  581. size penalty if overload is used in some package is that I<all> the
  582. packages acquire a magic during the next C<bless>ing into the
  583. package. This magic is three-words-long for packages without
  584. overloading, and carries the cache table if the package is overloaded.
  585. Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is
  586. carried out before any operation that can imply an assignment to the
  587. object $a (or $b) refers to, like C<$a++>. You can override this
  588. behavior by defining your own copy constructor (see L<"Copy Constructor">).
  589. It is expected that arguments to methods that are not explicitly supposed
  590. to be changed are constant (but this is not enforced).
  591. =head1 Metaphor clash
  592. One may wonder why the semantic of overloaded C<=> is so counter intuitive.
  593. If it I<looks> counter intuitive to you, you are subject to a metaphor
  594. clash.
  595. Here is a Perl object metaphor:
  596. I< object is a reference to blessed data>
  597. and an arithmetic metaphor:
  598. I< object is a thing by itself>.
  599. The I<main> problem of overloading C<=> is the fact that these metaphors
  600. imply different actions on the assignment C<$a = $b> if $a and $b are
  601. objects. Perl-think implies that $a becomes a reference to whatever
  602. $b was referencing. Arithmetic-think implies that the value of "object"
  603. $a is changed to become the value of the object $b, preserving the fact
  604. that $a and $b are separate entities.
  605. The difference is not relevant in the absence of mutators. After
  606. a Perl-way assignment an operation which mutates the data referenced by $a
  607. would change the data referenced by $b too. Effectively, after
  608. C<$a = $b> values of $a and $b become I<indistinguishable>.
  609. On the other hand, anyone who has used algebraic notation knows the
  610. expressive power of the arithmetic metaphor. Overloading works hard
  611. to enable this metaphor while preserving the Perlian way as far as
  612. possible. Since it is not not possible to freely mix two contradicting
  613. metaphors, overloading allows the arithmetic way to write things I<as
  614. far as all the mutators are called via overloaded access only>. The
  615. way it is done is described in L<Copy Constructor>.
  616. If some mutator methods are directly applied to the overloaded values,
  617. one may need to I<explicitly unlink> other values which references the
  618. same value:
  619. $a = new Data 23;
  620. ...
  621. $b = $a; # $b is "linked" to $a
  622. ...
  623. $a = $a->clone; # Unlink $b from $a
  624. $a->increment_by(4);
  625. Note that overloaded access makes this transparent:
  626. $a = new Data 23;
  627. $b = $a; # $b is "linked" to $a
  628. $a += 4; # would unlink $b automagically
  629. However, it would not make
  630. $a = new Data 23;
  631. $a = 4; # Now $a is a plain 4, not 'Data'
  632. preserve "objectness" of $a. But Perl I<has> a way to make assignments
  633. to an object do whatever you want. It is just not the overload, but
  634. tie()ing interface (see L<perlfunc/tie>). Adding a FETCH() method
  635. which returns the object itself, and STORE() method which changes the
  636. value of the object, one can reproduce the arithmetic metaphor in its
  637. completeness, at least for variables which were tie()d from the start.
  638. (Note that a workaround for a bug may be needed, see L<"BUGS">.)
  639. =head1 Cookbook
  640. Please add examples to what follows!
  641. =head2 Two-face scalars
  642. Put this in F<two_face.pm> in your Perl library directory:
  643. package two_face; # Scalars with separate string and
  644. # numeric values.
  645. sub new { my $p = shift; bless [@_], $p }
  646. use overload '""' => \&str, '0+' => \&num, fallback => 1;
  647. sub num {shift->[1]}
  648. sub str {shift->[0]}
  649. Use it as follows:
  650. require two_face;
  651. my $seven = new two_face ("vii", 7);
  652. printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
  653. print "seven contains `i'\n" if $seven =~ /i/;
  654. (The second line creates a scalar which has both a string value, and a
  655. numeric value.) This prints:
  656. seven=vii, seven=7, eight=8
  657. seven contains `i'
  658. =head2 Two-face references
  659. Suppose you want to create an object which is accessible as both an
  660. array reference and a hash reference, similar to the
  661. L<pseudo-hash|perlref/"Pseudo-hashes: Using an array as a hash">
  662. builtin Perl type. Let's make it better than a pseudo-hash by
  663. allowing index 0 to be treated as a normal element.
  664. package two_refs;
  665. use overload '%{}' => \&gethash, '@{}' => sub { $ {shift()} };
  666. sub new {
  667. my $p = shift;
  668. bless \ [@_], $p;
  669. }
  670. sub gethash {
  671. my %h;
  672. my $self = shift;
  673. tie %h, ref $self, $self;
  674. \%h;
  675. }
  676. sub TIEHASH { my $p = shift; bless \ shift, $p }
  677. my %fields;
  678. my $i = 0;
  679. $fields{$_} = $i++ foreach qw{zero one two three};
  680. sub STORE {
  681. my $self = ${shift()};
  682. my $key = $fields{shift()};
  683. defined $key or die "Out of band access";
  684. $$self->[$key] = shift;
  685. }
  686. sub FETCH {
  687. my $self = ${shift()};
  688. my $key = $fields{shift()};
  689. defined $key or die "Out of band access";
  690. $$self->[$key];
  691. }
  692. Now one can access an object using both the array and hash syntax:
  693. my $bar = new two_refs 3,4,5,6;
  694. $bar->[2] = 11;
  695. $bar->{two} == 11 or die 'bad hash fetch';
  696. Note several important features of this example. First of all, the
  697. I<actual> type of $bar is a scalar reference, and we do not overload
  698. the scalar dereference. Thus we can get the I<actual> non-overloaded
  699. contents of $bar by just using C<$$bar> (what we do in functions which
  700. overload dereference). Similarly, the object returned by the
  701. TIEHASH() method is a scalar reference.
  702. Second, we create a new tied hash each time the hash syntax is used.
  703. This allows us not to worry about a possibility of a reference loop,
  704. would would lead to a memory leak.
  705. Both these problems can be cured. Say, if we want to overload hash
  706. dereference on a reference to an object which is I<implemented> as a
  707. hash itself, the only problem one has to circumvent is how to access
  708. this I<actual> hash (as opposed to the I<virtual> hash exhibited by the
  709. overloaded dereference operator). Here is one possible fetching routine:
  710. sub access_hash {
  711. my ($self, $key) = (shift, shift);
  712. my $class = ref $self;
  713. bless $self, 'overload::dummy'; # Disable overloading of %{}
  714. my $out = $self->{$key};
  715. bless $self, $class; # Restore overloading
  716. $out;
  717. }
  718. To remove creation of the tied hash on each access, one may an extra
  719. level of indirection which allows a non-circular structure of references:
  720. package two_refs1;
  721. use overload '%{}' => sub { ${shift()}->[1] },
  722. '@{}' => sub { ${shift()}->[0] };
  723. sub new {
  724. my $p = shift;
  725. my $a = [@_];
  726. my %h;
  727. tie %h, $p, $a;
  728. bless \ [$a, \%h], $p;
  729. }
  730. sub gethash {
  731. my %h;
  732. my $self = shift;
  733. tie %h, ref $self, $self;
  734. \%h;
  735. }
  736. sub TIEHASH { my $p = shift; bless \ shift, $p }
  737. my %fields;
  738. my $i = 0;
  739. $fields{$_} = $i++ foreach qw{zero one two three};
  740. sub STORE {
  741. my $a = ${shift()};
  742. my $key = $fields{shift()};
  743. defined $key or die "Out of band access";
  744. $a->[$key] = shift;
  745. }
  746. sub FETCH {
  747. my $a = ${shift()};
  748. my $key = $fields{shift()};
  749. defined $key or die "Out of band access";
  750. $a->[$key];
  751. }
  752. Now if $baz is overloaded like this, then C<$baz> is a reference to a
  753. reference to the intermediate array, which keeps a reference to an
  754. actual array, and the access hash. The tie()ing object for the access
  755. hash is a reference to a reference to the actual array, so
  756. =over
  757. =item *
  758. There are no loops of references.
  759. =item *
  760. Both "objects" which are blessed into the class C<two_refs1> are
  761. references to a reference to an array, thus references to a I<scalar>.
  762. Thus the accessor expression C<$$foo-E<gt>[$ind]> involves no
  763. overloaded operations.
  764. =back
  765. =head2 Symbolic calculator
  766. Put this in F<symbolic.pm> in your Perl library directory:
  767. package symbolic; # Primitive symbolic calculator
  768. use overload nomethod => \&wrap;
  769. sub new { shift; bless ['n', @_] }
  770. sub wrap {
  771. my ($obj, $other, $inv, $meth) = @_;
  772. ($obj, $other) = ($other, $obj) if $inv;
  773. bless [$meth, $obj, $other];
  774. }
  775. This module is very unusual as overloaded modules go: it does not
  776. provide any usual overloaded operators, instead it provides the L<Last
  777. Resort> operator C<nomethod>. In this example the corresponding
  778. subroutine returns an object which encapsulates operations done over
  779. the objects: C<new symbolic 3> contains C<['n', 3]>, C<2 + new
  780. symbolic 3> contains C<['+', 2, ['n', 3]]>.
  781. Here is an example of the script which "calculates" the side of
  782. circumscribed octagon using the above package:
  783. require symbolic;
  784. my $iter = 1; # 2**($iter+2) = 8
  785. my $side = new symbolic 1;
  786. my $cnt = $iter;
  787. while ($cnt--) {
  788. $side = (sqrt(1 + $side**2) - 1)/$side;
  789. }
  790. print "OK\n";
  791. The value of $side is
  792. ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
  793. undef], 1], ['n', 1]]
  794. Note that while we obtained this value using a nice little script,
  795. there is no simple way to I<use> this value. In fact this value may
  796. be inspected in debugger (see L<perldebug>), but ony if
  797. C<bareStringify> B<O>ption is set, and not via C<p> command.
  798. If one attempts to print this value, then the overloaded operator
  799. C<""> will be called, which will call C<nomethod> operator. The
  800. result of this operator will be stringified again, but this result is
  801. again of type C<symbolic>, which will lead to an infinite loop.
  802. Add a pretty-printer method to the module F<symbolic.pm>:
  803. sub pretty {
  804. my ($meth, $a, $b) = @{+shift};
  805. $a = 'u' unless defined $a;
  806. $b = 'u' unless defined $b;
  807. $a = $a->pretty if ref $a;
  808. $b = $b->pretty if ref $b;
  809. "[$meth $a $b]";
  810. }
  811. Now one can finish the script by
  812. print "side = ", $side->pretty, "\n";
  813. The method C<pretty> is doing object-to-string conversion, so it
  814. is natural to overload the operator C<""> using this method. However,
  815. inside such a method it is not necessary to pretty-print the
  816. I<components> $a and $b of an object. In the above subroutine
  817. C<"[$meth $a $b]"> is a catenation of some strings and components $a
  818. and $b. If these components use overloading, the catenation operator
  819. will look for an overloaded operator C<.>; if not present, it will
  820. look for an overloaded operator C<"">. Thus it is enough to use
  821. use overload nomethod => \&wrap, '""' => \&str;
  822. sub str {
  823. my ($meth, $a, $b) = @{+shift};
  824. $a = 'u' unless defined $a;
  825. $b = 'u' unless defined $b;
  826. "[$meth $a $b]";
  827. }
  828. Now one can change the last line of the script to
  829. print "side = $side\n";
  830. which outputs
  831. side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
  832. and one can inspect the value in debugger using all the possible
  833. methods.
  834. Something is is still amiss: consider the loop variable $cnt of the
  835. script. It was a number, not an object. We cannot make this value of
  836. type C<symbolic>, since then the loop will not terminate.
  837. Indeed, to terminate the cycle, the $cnt should become false.
  838. However, the operator C<bool> for checking falsity is overloaded (this
  839. time via overloaded C<"">), and returns a long string, thus any object
  840. of type C<symbolic> is true. To overcome this, we need a way to
  841. compare an object to 0. In fact, it is easier to write a numeric
  842. conversion routine.
  843. Here is the text of F<symbolic.pm> with such a routine added (and
  844. slightly modified str()):
  845. package symbolic; # Primitive symbolic calculator
  846. use overload
  847. nomethod => \&wrap, '""' => \&str, '0+' => \&num;
  848. sub new { shift; bless ['n', @_] }
  849. sub wrap {
  850. my ($obj, $other, $inv, $meth) = @_;
  851. ($obj, $other) = ($other, $obj) if $inv;
  852. bless [$meth, $obj, $other];
  853. }
  854. sub str {
  855. my ($meth, $a, $b) = @{+shift};
  856. $a = 'u' unless defined $a;
  857. if (defined $b) {
  858. "[$meth $a $b]";
  859. } else {
  860. "[$meth $a]";
  861. }
  862. }
  863. my %subr = ( n => sub {$_[0]},
  864. sqrt => sub {sqrt $_[0]},
  865. '-' => sub {shift() - shift()},
  866. '+' => sub {shift() + shift()},
  867. '/' => sub {shift() / shift()},
  868. '*' => sub {shift() * shift()},
  869. '**' => sub {shift() ** shift()},
  870. );
  871. sub num {
  872. my ($meth, $a, $b) = @{+shift};
  873. my $subr = $subr{$meth}
  874. or die "Do not know how to ($meth) in symbolic";
  875. $a = $a->num if ref $a eq __PACKAGE__;
  876. $b = $b->num if ref $b eq __PACKAGE__;
  877. $subr->($a,$b);
  878. }
  879. All the work of numeric conversion is done in %subr and num(). Of
  880. course, %subr is not complete, it contains only operators used in the
  881. example below. Here is the extra-credit question: why do we need an
  882. explicit recursion in num()? (Answer is at the end of this section.)
  883. Use this module like this:
  884. require symbolic;
  885. my $iter = new symbolic 2; # 16-gon
  886. my $side = new symbolic 1;
  887. my $cnt = $iter;
  888. while ($cnt) {
  889. $cnt = $cnt - 1; # Mutator `--' not implemented
  890. $side = (sqrt(1 + $side**2) - 1)/$side;
  891. }
  892. printf "%s=%f\n", $side, $side;
  893. printf "pi=%f\n", $side*(2**($iter+2));
  894. It prints (without so many line breaks)
  895. [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
  896. [n 1]] 2]]] 1]
  897. [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
  898. pi=3.182598
  899. The above module is very primitive. It does not implement
  900. mutator methods (C<++>, C<-=> and so on), does not do deep copying
  901. (not required without mutators!), and implements only those arithmetic
  902. operations which are used in the example.
  903. To implement most arithmetic operations is easy; one should just use
  904. the tables of operations, and change the code which fills %subr to
  905. my %subr = ( 'n' => sub {$_[0]} );
  906. foreach my $op (split " ", $overload::ops{with_assign}) {
  907. $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
  908. }
  909. my @bins = qw(binary 3way_comparison num_comparison str_comparison);
  910. foreach my $op (split " ", "@overload::ops{ @bins }") {
  911. $subr{$op} = eval "sub {shift() $op shift()}";
  912. }
  913. foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
  914. print "defining `$op'\n";
  915. $subr{$op} = eval "sub {$op shift()}";
  916. }
  917. Due to L<Calling Conventions for Mutators>, we do not need anything
  918. special to make C<+=> and friends work, except filling C<+=> entry of
  919. %subr, and defining a copy constructor (needed since Perl has no
  920. way to know that the implementation of C<'+='> does not mutate
  921. the argument, compare L<Copy Constructor>).
  922. To implement a copy constructor, add C<< '=' => \&cpy >> to C<use overload>
  923. line, and code (this code assumes that mutators change things one level
  924. deep only, so recursive copying is not needed):
  925. sub cpy {
  926. my $self = shift;
  927. bless [@$self], ref $self;
  928. }
  929. To make C<++> and C<--> work, we need to implement actual mutators,
  930. either directly, or in C<nomethod>. We continue to do things inside
  931. C<nomethod>, thus add
  932. if ($meth eq '++' or $meth eq '--') {
  933. @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
  934. return $obj;
  935. }
  936. after the first line of wrap(). This is not a most effective
  937. implementation, one may consider
  938. sub inc { $_[0] = bless ['++', shift, 1]; }
  939. instead.
  940. As a final remark, note that one can fill %subr by
  941. my %subr = ( 'n' => sub {$_[0]} );
  942. foreach my $op (split " ", $overload::ops{with_assign}) {
  943. $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
  944. }
  945. my @bins = qw(binary 3way_comparison num_comparison str_comparison);
  946. foreach my $op (split " ", "@overload::ops{ @bins }") {
  947. $subr{$op} = eval "sub {shift() $op shift()}";
  948. }
  949. foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
  950. $subr{$op} = eval "sub {$op shift()}";
  951. }
  952. $subr{'++'} = $subr{'+'};
  953. $subr{'--'} = $subr{'-'};
  954. This finishes implementation of a primitive symbolic calculator in
  955. 50 lines of Perl code. Since the numeric values of subexpressions
  956. are not cached, the calculator is very slow.
  957. Here is the answer for the exercise: In the case of str(), we need no
  958. explicit recursion since the overloaded C<.>-operator will fall back
  959. to an existing overloaded operator C<"">. Overloaded arithmetic
  960. operators I<do not> fall back to numeric conversion if C<fallback> is
  961. not explicitly requested. Thus without an explicit recursion num()
  962. would convert C<['+', $a, $b]> to C<$a + $b>, which would just rebuild
  963. the argument of num().
  964. If you wonder why defaults for conversion are different for str() and
  965. num(), note how easy it was to write the symbolic calculator. This
  966. simplicity is due to an appropriate choice of defaults. One extra
  967. note: due to the explicit recursion num() is more fragile than sym():
  968. we need to explicitly check for the type of $a and $b. If components
  969. $a and $b happen to be of some related type, this may lead to problems.
  970. =head2 I<Really> symbolic calculator
  971. One may wonder why we call the above calculator symbolic. The reason
  972. is that the actual calculation of the value of expression is postponed
  973. until the value is I<used>.
  974. To see it in action, add a method
  975. sub STORE {
  976. my $obj = shift;
  977. $#$obj = 1;
  978. @$obj->[0,1] = ('=', shift);
  979. }
  980. to the package C<symbolic>. After this change one can do
  981. my $a = new symbolic 3;
  982. my $b = new symbolic 4;
  983. my $c = sqrt($a**2 + $b**2);
  984. and the numeric value of $c becomes 5. However, after calling
  985. $a->STORE(12); $b->STORE(5);
  986. the numeric value of $c becomes 13. There is no doubt now that the module
  987. symbolic provides a I<symbolic> calculator indeed.
  988. To hide the rough edges under the hood, provide a tie()d interface to the
  989. package C<symbolic> (compare with L<Metaphor clash>). Add methods
  990. sub TIESCALAR { my $pack = shift; $pack->new(@_) }
  991. sub FETCH { shift }
  992. sub nop { } # Around a bug
  993. (the bug is described in L<"BUGS">). One can use this new interface as
  994. tie $a, 'symbolic', 3;
  995. tie $b, 'symbolic', 4;
  996. $a->nop; $b->nop; # Around a bug
  997. my $c = sqrt($a**2 + $b**2);
  998. Now numeric value of $c is 5. After C<$a = 12; $b = 5> the numeric value
  999. of $c becomes 13. To insulate the user of the module add a method
  1000. sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
  1001. Now
  1002. my ($a, $b);
  1003. symbolic->vars($a, $b);
  1004. my $c = sqrt($a**2 + $b**2);
  1005. $a = 3; $b = 4;
  1006. printf "c5 %s=%f\n", $c, $c;
  1007. $a = 12; $b = 5;
  1008. printf "c13 %s=%f\n", $c, $c;
  1009. shows that the numeric value of $c follows changes to the values of $a
  1010. and $b.
  1011. =head1 AUTHOR
  1012. Ilya Zakharevich E<lt>F<[email protected]>E<gt>.
  1013. =head1 DIAGNOSTICS
  1014. When Perl is run with the B<-Do> switch or its equivalent, overloading
  1015. induces diagnostic messages.
  1016. Using the C<m> command of Perl debugger (see L<perldebug>) one can
  1017. deduce which operations are overloaded (and which ancestor triggers
  1018. this overloading). Say, if C<eq> is overloaded, then the method C<(eq>
  1019. is shown by debugger. The method C<()> corresponds to the C<fallback>
  1020. key (in fact a presence of this method shows that this package has
  1021. overloading enabled, and it is what is used by the C<Overloaded>
  1022. function of module C<overload>).
  1023. The module might issue the following warnings:
  1024. =over 4
  1025. =item Odd number of arguments for overload::constant
  1026. (W) The call to overload::constant contained an odd number of arguments.
  1027. The arguments should come in pairs.
  1028. =item `%s' is not an overloadable type
  1029. (W) You tried to overload a constant type the overload package is unaware of.
  1030. =item `%s' is not a code reference
  1031. (W) The second (fourth, sixth, ...) argument of overload::constant needs
  1032. to be a code reference. Either an anonymous subroutine, or a reference
  1033. to a subroutine.
  1034. =back
  1035. =head1 BUGS
  1036. Because it is used for overloading, the per-package hash %OVERLOAD now
  1037. has a special meaning in Perl. The symbol table is filled with names
  1038. looking like line-noise.
  1039. For the purpose of inheritance every overloaded package behaves as if
  1040. C<fallback> is present (possibly undefined). This may create
  1041. interesting effects if some package is not overloaded, but inherits
  1042. from two overloaded packages.
  1043. Relation between overloading and tie()ing is broken. Overloading is
  1044. triggered or not basing on the I<previous> class of tie()d value.
  1045. This happens because the presence of overloading is checked too early,
  1046. before any tie()d access is attempted. If the FETCH()ed class of the
  1047. tie()d value does not change, a simple workaround is to access the value
  1048. immediately after tie()ing, so that after this call the I<previous> class
  1049. coincides with the current one.
  1050. B<Needed:> a way to fix this without a speed penalty.
  1051. Barewords are not covered by overloaded string constants.
  1052. This document is confusing. There are grammos and misleading language
  1053. used in places. It would seem a total rewrite is needed.
  1054. =cut