overload.pm 52 KB

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