home *** CD-ROM | disk | FTP | other *** search
/ Chip 2000 May / Chip_2000-05_cd1.bin / zkuste / Perl / ActivePerl-5.6.0.613.msi / 䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥 / _e709ad60598d49e2073b35300d843850 < prev    next >
Text File  |  2000-03-23  |  56KB  |  1,136 lines

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