<?xml version='1.0' encoding='utf-8'?>
<pod xmlns="http://axkit.org/ns/2000/pod2xml">
<head>
	<title>overload - Package for overloading perl operations</title>
</head>
<sect1>
<title>overload - Package for overloading perl operations</title>
<para>
overload - Perl の演算子のオーバーロードを行うパッケージ
</para>
</sect1>
<sect1>
<title>SYNOPSIS</title>
<verbatim><![CDATA[
package SomeThing;
]]></verbatim>
<verbatim><![CDATA[
use overload
	'+' => \&myadd,
	'-' => \&mysub;
	# etc
...
]]></verbatim>
<verbatim><![CDATA[
package main;
$a = new SomeThing 57;
$b=5+$a;
...
if (overload::Overloaded $b) {...}
...
$strval = overload::StrVal $b;
]]></verbatim>
</sect1>
<sect1>
<title>DESCRIPTION</title>
<sect2>
<title>Declaration of overloaded functions</title>
<para>
(オーバーロード関数の宣言)
</para>
<para>
The compilation directive
</para>
<para>
コンパイル指示子
</para>
<verbatim><![CDATA[
package Number;
use overload
	"+" => \&add,
	"*=" => "muas";
]]></verbatim>
<para>
declares function Number::add() for addition, and method muas() in
the &quot;class&quot; <code>Number</code> (or one of its base classes)
for the assignment form <code>*=</code> of multiplication.
</para>
<para>
では、加法の関数 Number::add() と「クラス」<code>Number</code> (あるいは、
その基底クラスの 1 つ) の中の乗法の代入形式 <code>*=</code> のメソッド muas() を
宣言しています。
</para>
<para>
Arguments of this directive come in (key, value) pairs.  Legal values
are values legal inside a <code>&amp;{ ... }</code> call, so the name of a
subroutine, a reference to a subroutine, or an anonymous subroutine
will all work.  Note that values specified as strings are
interpreted as methods, not subroutines.  Legal keys are listed below.
</para>
<para>
この指示子の引数は (key, value) のペアです。
この value としては、<code>&amp;{ ... }</code> の中で使用できるものが
すべてを指定できますから、サブルーチン名、
サブルーチンへのリファレンス、無名のサブルーチンといったものが
すべて使えます。
文字列として指定された値はサブルーチンではなく、
メソッドとして解釈されることに注意してください。
key として有効な値は以下に述べます。
</para>
<para>
The subroutine <code>add</code> will be called to execute <code>$a+$b</code> if $a
is a reference to an object blessed into the package <code>Number</code>, or if $a is
not an object from a package with defined mathemagic addition, but $b is a
reference to a <code>Number</code>.  It can also be called in other situations, like
<code>$a+=7</code>, or <code>$a++</code>.  See <link xref='MAGIC AUTOGENERATION'>MAGIC AUTOGENERATION</link>.  (Mathemagical
methods refer to methods triggered by an overloaded mathematical
operator.)
</para>
<para>
<code>$a+$b</code> を実行するときに、$a がパッケージ <code>Number</code> 内に
bless されたオブジェクトへのリファレンスである場合か、
$a がそのようなマスマジカルな加法を用意しているパッケージの
オブジェクトでなくても、$b が Number へのリファレンスである場合に、
サブルーチン <code>add</code> が呼び出されます。
これは、<code>$a+=7</code> とか <code>$a++</code> といった、シチュエーションでも呼ばれます。
<link xref='MAGIC AUTOGENERATION'>MAGIC AUTOGENERATION</link> の節を参照してください。
(「マスマジカル」という言葉は、オーバーロードされた
算術演算子によって起動されるメソッドを指しています。)
</para>
<para>
Since overloading respects inheritance via the @ISA hierarchy, the
above declaration would also trigger overloading of <code>+</code> and <code>*=</code> in
all the packages which inherit from <code>Number</code>.
</para>
<para>
オーバーロードは @ISA 階層による継承を遵守するので、上述の宣言は
<code>Number</code> から継承される全てのパッケージの <code>+</code> と <code>*=</code> のオーバーロードも
引き起こすことになります。
</para>
</sect2>
<sect2>
<title>Calling Conventions for Binary Operations</title>
<para>
(二項演算子の呼び出し規約)
</para>
<para>
The functions specified in the <code>use overload ...</code> directive are called
with three (in one particular case with four, see <link xref='Last Resort'>Last Resort</link>)
arguments.  If the corresponding operation is binary, then the first
two arguments are the two arguments of the operation.  However, due to
general object calling conventions, the first argument should always be
an object in the package, so in the situation of <code>7+$a</code>, the
order of the arguments is interchanged.  It probably does not matter
when implementing the addition method, but whether the arguments
are reversed is vital to the subtraction method.  The method can
query this information by examining the third argument, which can take
three different values:
</para>
<para>
<code>use overload ...</code> 指示子で指定される関数は、
3 つ (唯一特別な場合があって、
その時は 4 つ (<link xref='Last Resort'>Last Resort</link>の節を参照) ) の引数で呼び出されます。
対応する演算子が、二項演算子であれば、最初の 2 つの引数は、
その演算子の 2 つの引数です。
しかしながら、通常のオブジェクトメソッドの呼び出し規約によって、
最初の引数は、常にそのパッケージのオブジェクトでなければなりませんので、
<code>7+$a</code> のような場合には、引数の順序の入れ替えが行なわれます。
これは、加法のメソッドを実装する時には、
おそらく問題にはならないものですが、減法のメソッドにとっては、
引数を入替えるか否かは、非常に重大な問題です。
メソッド側では、この引数の入れ替えについての情報を 3 つめの引数を
調べることで、確かめることができます。
この引数は、3 種類の値をとります:
</para>
<list>
<item><itemtext>FALSE</itemtext>
<para>
(偽)
</para>
<para>
the order of arguments is as in the current operation.
</para>
<para>
引数の順序は、現在の演算子でのものと同じです。
</para>
</item>
<item><itemtext>TRUE</itemtext>
<para>
(真)
</para>
<para>
the arguments are reversed.
</para>
<para>
引数は、逆になっています。
</para>
</item>
<item><itemtext><code>undef</code></itemtext>
<para>
the current operation is an assignment variant (as in
<code>$a+=7</code>), but the usual function is called instead.  This additional
information can be used to generate some optimizations.  Compare
<link xref='Calling Conventions for Mutators'>Calling Conventions for Mutators</link>.
</para>
<para>
現在の演算子は、(<code>$a+=7</code> のような) 代入形式のものですが、
代わりに普通の関数が呼ばれます。
この付加的な情報は、何らかの最適化を行なうときに
使用できます。
<link xref='Calling Conventions for Mutators'>Calling Conventions for Mutators</link> と比較してください。
</para>
</item>
</list>
</sect2>
<sect2>
<title>Calling Conventions for Unary Operations</title>
<para>
(単項演算子の呼び出し規約)
</para>
<para>
Unary operation are considered binary operations with the second
argument being <code>undef</code>.  Thus the functions that overloads <code>{&quot;++&quot;}</code>
is called with arguments <code>($a,undef,'')</code> when $a++ is executed.
</para>
<para>
単項演算子は、2 番目の引数が <code>undef</code> の二項演算子であると
考えられます。
つまり、<code>{&quot;++&quot;}</code> をオーバーロードする関数は、
$a++ が実行されるときに、<code>($a, undef, '')</code> という引数で呼び出されます。
</para>
</sect2>
<sect2>
<title>Calling Conventions for Mutators</title>
<para>
(ミューテータの呼び出し規約)
</para>
<para>
Two types of mutators have different calling conventions:
</para>
<para>
2 種類のミューテータは異なった呼び出し規約を持ちます:
</para>
<list>
<item><itemtext><code>++</code> and <code>--</code></itemtext>
<para>
(<code>++</code> と <code>--</code>)
</para>
<para>
The routines which implement these operators are expected to actually
<emphasis>mutate</emphasis> their arguments.  So, assuming that $obj is a reference to a
number,
</para>
<para>
これらの演算子を実装するルーチンは、実際はこれらの引数を
<emphasis>変更(mutate)</emphasis> することを想定しています。
それで、$obj が数値へのリファレンスと仮定すると、
</para>
<verbatim><![CDATA[
sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \$n}
]]></verbatim>
<para>
is an appropriate implementation of overloaded <code>++</code>.  Note that
</para>
<para>
はオーバーロードした <code>++</code> の適切な実装です。以下のものは
</para>
<verbatim><![CDATA[
sub incr { ++$ {$_[0]} ; shift }
]]></verbatim>
<para>
is OK if used with preincrement and with postincrement. (In the case
of postincrement a copying will be performed, see <link xref='Copy Constructor'>Copy Constructor</link>.)
</para>
<para>
事前インクリメントと事後インクリメントの場合は OK であることに
注意してください。
事後インクリメントの場合、コピーが実行されます。
<link xref='Copy Constructor'>Copy Constructor</link> を参照してください。)
</para>
</item>
<item><itemtext><code>x=</code> and other assignment versions</itemtext>
<para>
(<code>x=</code> とその他の代入演算子)
</para>
<para>
There is nothing special about these methods.  They may change the
value of their arguments, and may leave it as is.  The result is going
to be assigned to the value in the left-hand-side if different from
this value.
</para>
<para>
これらのメソッドについて何も特別なものはありません。
引数の値を変更するかもしれませんし、そのままかもしれません。
結果は、もしこの値と違うなら左側の値に代入されることになります。
</para>
<para>
This allows for the same method to be used as overloaded <code>+=</code> and
<code>+</code>.  Note that this is <emphasis>allowed</emphasis>, but not recommended, since by the
semantic of <link xref='#Fallback'>&quot;Fallback&quot;</link> Perl will call the method for <code>+</code> anyway,
if <code>+=</code> is not overloaded.
</para>
<para>
これは、オーバーロードした <code>+=</code> と <code>+</code> として同じメソッドを使うことを
許します。
これは <emphasis>許されます</emphasis> が、推奨されません; なぜなら <link xref='#Fallback'>&quot;Fallback&quot;</link> の
意味論によって Perl はもし <code>+=</code> がオーバーロードされていなければ
とにかく <code>+</code> を呼び出すからです。
</para>
</item>
</list>
<para>
<strong>Warning.</strong>  Due to the presense of assignment versions of operations,
routines which may be called in assignment context may create
self-referential structures.  Currently Perl will not free self-referential
structures until cycles are <code>explicitly</code> broken.  You may get problems
when traversing your structures too.
</para>
<para>
<strong>警告:</strong> 演算の代入版の存在によって、代入コンテキストで呼び出される
ルーチンは自己参照構造を作るかもしれません。
現在のところ、Perl は循環が <code>明示的に</code> 破壊されるまで自己参照構造を
解放しません。
構造をたどっていくときにも問題になるかもしれません。
</para>
<para>
Say,
</para>
<para>
以下のようにすると、
</para>
<verbatim><![CDATA[
use overload '+' => sub { bless [ \$_[0], \$_[1] ] };
]]></verbatim>
<para>
is asking for trouble, since for code <code>$obj += $foo</code> the subroutine
is called as <code>$obj = add($obj, $foo, undef)</code>, or <code>$obj = [\$obj,
\$foo]</code>.  If using such a subroutine is an important optimization, one
can overload <code>+=</code> explicitly by a non-&quot;optimized&quot; version, or switch
to non-optimized version if <code>not defined $_[2]</code> (see
<link xref='Calling Conventions for Binary Operations'>Calling Conventions for Binary Operations</link>).
</para>
<para>
は自ら災いを招くことになります; なぜなら <code>$obj += $foo</code> というコードでは
サブルーチンは <code>$obj = add($obj, $foo, undef)</code> あるいは <code>$obj = [\$obj,
\$foo]</code> として呼び出されるからです。
もしこのようなサブルーチンを使うことが重要な最適化なら、
非「最適化」版で明示的に <code>+=</code> をオーバーロードするか、
もし <code>not defined $_[2]</code> なら非最適化版に切り替えることができます
(<link xref='Calling Conventions for Binary Operations'>Calling Conventions for Binary Operations</link> を参照してください)。
</para>
<para>
Even if no <emphasis>explicit</emphasis> assignment-variants of operators are present in
the script, they may be generated by the optimizer.  Say, <code>&quot;,$obj,&quot;</code> or
<code>',' . $obj . ','</code> may be both optimized to
</para>
<para>
たとえスクリプトで <emphasis>明示的に</emphasis> 代入系の演算子を使っていなくても、
オプティマイザによって生成されるかもしれません。
例えば、<code>&quot;,$obj,&quot;</code> や <code>',' . $obj . ','</code> は両方とも以下のように
最適化されるかもしれません
</para>
<verbatim><![CDATA[
my $tmp = ',' . $obj;    $tmp .= ',';
]]></verbatim>
</sect2>
<sect2>
<title>Overloadable Operations</title>
<para>
(オーバーロードできる操作)
</para>
<para>
The following symbols can be specified in <code>use overload</code> directive:
</para>
<para>
以下のシンボルが <code>use overload</code> 指示子で指定できます:
</para>
<list>
<item><itemtext><emphasis>Arithmetic operations</emphasis></itemtext>
<para>
(<emphasis>算術演算子</emphasis>)
</para>
<verbatim><![CDATA[
"+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
"**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
]]></verbatim>
<para>
For these operations a substituted non-assignment variant can be called if
the assignment variant is not available.  Methods for operations &quot;<code>+</code>&quot;,
&quot;<code>-</code>&quot;, &quot;<code>+=</code>&quot;, and &quot;<code>-=</code>&quot; can be called to automatically generate
increment and decrement methods.  The operation &quot;<code>-</code>&quot; can be used to
autogenerate missing methods for unary minus or <code>abs</code>.
</para>
<para>
これらの演算子について、代入形式のものが存在しないときには、代わりに
非代入形式のものが呼ばれます。
演算子 <code>&quot;+&quot;</code>, <code>&quot;-&quot;</code>, <code>&quot;+=&quot;</code>, <code>&quot;-=&quot;</code> に対するメソッドは、
インクリメント演算子やデクリメント演算子を自動生成するために
呼ばれることがあります。
演算子 <code>&quot;-&quot;</code> は、単項のマイナスや <code>abs</code> のメソッドがないときに
自動生成するために使われます。
</para>
<para>
See <link xref='#MAGIC_AUTOGENERATION'>&quot;MAGIC AUTOGENERATION&quot;</link>, <link xref='#Calling_Conventions_for_Mutato'>&quot;Calling Conventions for Mutators&quot;</link> and
<link xref='#Calling_Conventions_for_Binary'>&quot;Calling Conventions for Binary Operations&quot;</link>) for details of these
substitutions.
</para>
<para>
これらの置換に関する詳細については <link xref='#MAGIC_AUTOGENERATION'>&quot;MAGIC AUTOGENERATION&quot;</link>,
<link xref='#Calling_Conventions_for_Mutato'>&quot;Calling Conventions for Mutators&quot;</link>,
<link xref='#Calling_Conventions_for_Binary'>&quot;Calling Conventions for Binary Operations&quot;</link> を参照して下さい。
</para>
</item>
<item><itemtext><emphasis>Comparison operations</emphasis></itemtext>
<para>
(<emphasis>比較演算子</emphasis>)
</para>
<verbatim><![CDATA[
"<",  "<=", ">",  ">=", "==", "!=", "<=>",
"lt", "le", "gt", "ge", "eq", "ne", "cmp",
]]></verbatim>
<para>
If the corresponding &quot;spaceship&quot; variant is available, it can be
used to substitute for the missing operation.  During <code>sort</code>ing
arrays, <code>cmp</code> is used to compare values subject to <code>use overload</code>.
</para>
<para>
ある演算子が無い場合にも、対応する「スペースシップ」形式が使えるならば、
代わりに使うことができます。
配列のソートのときには、<code>use overload</code> のもとの <code>cmp</code> を使って値を
比較します。
</para>
</item>
<item><itemtext><emphasis>Bit operations</emphasis></itemtext>
<para>
(<emphasis>ビット演算子</emphasis>)
</para>
<verbatim><![CDATA[
"&", "^", "|", "neg", "!", "~",
]]></verbatim>
<para>
&quot;<code>neg</code>&quot; stands for unary minus.  If the method for <code>neg</code> is not
specified, it can be autogenerated using the method for
subtraction. If the method for &quot;<code>!</code>&quot; is not specified, it can be
autogenerated using the methods for &quot;<code>bool</code>&quot;, or &quot;<code>\&quot;\&quot;</code>&quot;, or &quot;<code>0+</code>&quot;.
</para>
<para>
&quot;<code>neg</code>&quot; は、単項のマイナスを表わします。
<code>neg</code> のメソッドが指定されていないときには、
引き算のメソッドを使って、自動生成されます。
&quot;<code>!</code>&quot; のメソッドが指定されていないときには、
&quot;<code>bool</code>&quot;, &quot;<code>\&quot;\&quot;</code>&quot;, &quot;<code>0+</code>&quot; のいずれかのメソッドを使って
自動生成されます。
</para>
</item>
<item><itemtext><emphasis>Increment and decrement</emphasis></itemtext>
<para>
(<emphasis>インクリメントとデクリメント</emphasis>)
</para>
<verbatim><![CDATA[
"++", "--",
]]></verbatim>
<para>
If undefined, addition and subtraction methods can be
used instead.  These operations are called both in prefix and
postfix form.
</para>
<para>
未定義であれば、足し算と引き算のメソッドが代わりに使われます。
これらの演算子は、前置としても後置としても使われます。
</para>
</item>
<item><itemtext><emphasis>Transcendental functions</emphasis></itemtext>
<para>
(<emphasis>超越関数</emphasis>)
</para>
<verbatim><![CDATA[
"atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
]]></verbatim>
<para>
If <code>abs</code> is unavailable, it can be autogenerated using methods
for &quot;&lt;&quot; or &quot;&lt;=&gt;&quot; combined with either unary minus or subtraction.
</para>
<para>
<code>abs</code> がないときには、&quot;&lt;&quot; か &quot;&lt;=&lt;&gt;&quot; のメソッドを、
単項のマイナスか引き算のメソッドと組み合わせて、
自動生成されます。
</para>
</item>
<item><itemtext><emphasis>Boolean, string and numeric conversion</emphasis></itemtext>
<para>
(<emphasis>ブール変換、文字列変換、数値変換</emphasis>)
</para>
<verbatim><![CDATA[
"bool", "\"\"", "0+",
]]></verbatim>
<para>
If one or two of these operations are not overloaded, the remaining ones can
be used instead.  <code>bool</code> is used in the flow control operators
(like <code>while</code>) and for the ternary &quot;<code>?:</code>&quot; operation.  These functions can
return any arbitrary Perl value.  If the corresponding operation for this value
is overloaded too, that operation will be called again with this value.
</para>
<para>
これらの中でオーバーロードしていないものがあっても、残りが一つで
も定義してあれば、それを代わりに使うことができます。
<code>bool</code> は、(<code>while</code> のような) フロー制御演算子や、
三項演算子 &quot;<code>?:</code>&quot; で使われます。
これらの関数は、任意の Perl 値を返すことができます。
この値に対応する演算子もオーバーロードされている場合には、
その演算子がその時の値を使って、再度呼び出されることになります。
</para>
<para>
As a special case if the overload returns the object itself then it will
be used directly. An overloaded conversion returning the object is
probably a bug, because you're likely to get something that looks like
<code>YourPackage=HASH(0x8172b34)</code>.
</para>
<para>
特別な場合として、オーバーロードがオブジェクト自身を返した場合、
これが直接使われます。
オブジェクトを返すオーバーロードされた変換はおそらくバグです; なぜなら
おそらく <code>YourPackage=HASH(0x8172b34)</code> のようなものを受け取るからです。
</para>
</item>
<item><itemtext><emphasis>Iteration</emphasis></itemtext>
<para>
(<emphasis>反復子</emphasis>)
</para>
<verbatim><![CDATA[
"<>"
]]></verbatim>
<para>
If not overloaded, the argument will be converted to a filehandle or
glob (which may require a stringification).  The same overloading
happens both for the <emphasis>read-filehandle</emphasis> syntax <code>&lt;$var&gt;</code> and
<emphasis>globbing</emphasis> syntax <code>&lt;${var}&gt;</code>.
</para>
<para>
オーバーロードされないと、引数はファイルハンドルかグロブに変換されます
(文字列化が必要かもしれません)。
同じオーバーロードは <emphasis>ファイルハンドル読み込み</emphasis> 構文 <code>&lt;$var&gt;</code> と
<emphasis>グロブ</emphasis> 構文 <code>&lt;${var}&gt;</code> の両方でも起こります。
</para>
</item>
<item><itemtext><emphasis>Dereferencing</emphasis></itemtext>
<para>
(<emphasis>デリファレンス</emphasis>)
</para>
<verbatim><![CDATA[
'${}', '@{}', '%{}', '&{}', '*{}'.
]]></verbatim>
<para>
If not overloaded, the argument will be dereferenced <emphasis>as is</emphasis>, thus
should be of correct type.  These functions should return a reference
of correct type, or another object with overloaded dereferencing.
</para>
<para>
オーバーロードされないと、引数は <emphasis>そのままで</emphasis> デリファレンスされ、
正しい型になるべきです。
これらの関数は正しい型のリファレンスか、オーバーロードされた
デリファレンスと共に他のオブジェクトが返されるべきです。
</para>
<para>
As a special case if the overload returns the object itself then it
will be used directly (provided it is the correct type).
</para>
<para>
特別な場合として、オーバーロードがオブジェクト自身を返した場合、
(正しい型なら)これが直接使われます。
</para>
<para>
The dereference operators must be specified explicitly they will not be passed to
&quot;nomethod&quot;.
</para>
<para>
デリファレンス演算子は &quot;nomethod&quot; を渡されないように明示的に
指定されなければなりません。
</para>
</item>
<item><itemtext><emphasis>Special</emphasis></itemtext>
<para>
(<emphasis>特殊 key</emphasis>)
</para>
<verbatim><![CDATA[
"nomethod", "fallback", "=",
]]></verbatim>
<para>
see <link xref='SPECIAL SYMBOLS FOR {tag:code>use overload{#tag:code}'}SPECIAL SYMBOLS FOR <code>use overload</code></link>.
</para>
<para>
<link xref='SPECIAL SYMBOLS FOR {tag:code>use overload{#tag:code}'}SPECIAL SYMBOLS FOR <code>use overload</code></link> を参照してください。
</para>
</item>
</list>
<para>
See <link xref='#Fallback'>&quot;Fallback&quot;</link> for an explanation of when a missing method can be
autogenerated.
</para>
<para>
存在しないメソッドの自動生成についての説明は <link xref='#Fallback'>&quot;Fallback&quot;</link> を参照して下さい。
</para>
<para>
A computer-readable form of the above table is available in the hash
%overload::ops, with values being space-separated lists of names:
</para>
<para>
上述のテーブルのコンピュータ可読形式は、ハッシュ %overload::ops で
利用可能です; 値は空白で区切られた名前のリストです:
</para>
<verbatim><![CDATA[
with_assign	  => '+ - * / % ** << >> x .',
assign		  => '+= -= *= /= %= **= <<= >>= x= .=',
num_comparison	  => '< <= > >= == !=',
'3way_comparison'=> '<=> cmp',
str_comparison	  => 'lt le gt ge eq ne',
binary		  => '& | ^',
unary		  => 'neg ! ~',
mutators	  => '++ --',
func		  => 'atan2 cos sin exp abs log sqrt',
conversion	  => 'bool "" 0+',
iterators	  => '<>',
dereferencing	  => '${} @{} %{} &{} *{}',
special	  => 'nomethod fallback ='
]]></verbatim>
</sect2>
<sect2>
<title>Inheritance and overloading</title>
<para>
(継承とオーバーロード)
</para>
<para>
Inheritance interacts with overloading in two ways.
</para>
<para>
継承はオーバーロードに二つの方法で関わります。
</para>
<list>
<item><itemtext>Strings as values of <code>use overload</code> directive</itemtext>
<para>
(<code>use overload</code> 指示子の値としての文字列)
</para>
<para>
If <code>value</code> in
</para>
<para>
もし以下での <code>value</code> が
</para>
<verbatim><![CDATA[
use overload key => value;
]]></verbatim>
<para>
is a string, it is interpreted as a method name.
</para>
<para>
文字列の場合、メソッド名として解釈されます。
</para>
</item>
<item><itemtext>Overloading of an operation is inherited by derived classes</itemtext>
<para>
(操作のオーバーロードは派生クラスによって継承される)
</para>
<para>
Any class derived from an overloaded class is also overloaded.  The
set of overloaded methods is the union of overloaded methods of all
the ancestors. If some method is overloaded in several ancestor, then
which description will be used is decided by the usual inheritance
rules:
</para>
<para>
オーバーロードされたクラスから派生したクラスもオーバーロードされます。
オーバーロードされたメソッドの集合は全ての祖先のオーバーロードされた
メソッドの結合です。
もしあるメソッドが複数の祖先によってオーバーロードされているなら、
どれが使われるかは通常の継承ルールによって決定されます:
</para>
<para>
If <code>A</code> inherits from <code>B</code> and <code>C</code> (in this order), <code>B</code> overloads
<code>+</code> with <code>\&amp;D::plus_sub</code>, and <code>C</code> overloads <code>+</code> by <code>&quot;plus_meth&quot;</code>,
then the subroutine <code>D::plus_sub</code> will be called to implement
operation <code>+</code> for an object in package <code>A</code>.
</para>
<para>
もし <code>A</code> が <code>B</code> を <code>C</code> を (この順序で) 継承していて、<code>B</code> が <code>+</code> を
<code>\&amp;D::plus_sub</code> でオーバーロードし、<code>C</code> が <code>+</code> を <code>&quot;plus_meth&quot;</code> で
オーバーロードしている場合、パッケージ <code>A</code> でオブジェクトのために
演算 <code>+</code> を実装するために、サブルーチン <code>D::plus_sub</code> が呼び出されます。
</para>
</item>
</list>
<para>
Note that since the value of the <code>fallback</code> key is not a subroutine,
its inheritance is not governed by the above rules.  In the current
implementation, the value of <code>fallback</code> in the first overloaded
ancestor is used, but this is accidental and subject to change.
</para>
<para>
<code>fallback</code> キーの値はサブルーチンではないので、この継承は上述のルールには
従いません。
現在の実装では、最初にオーバーロードした祖先の <code>fallback</code> の値が
使われますが、これは偶然で、変更される予定です。
</para>
</sect2>
</sect1>
<sect1>
<title>SPECIAL SYMBOLS FOR <code>use overload</code></title>
<para>
(<code>use overload</code> の特殊シンボル)
</para>
<para>
Three keys are recognized by Perl that are not covered by the above
description.
</para>
<para>
ここまでに説明してきたものの他に、3 つの key が Perl に認識されます。
</para>
<sect2>
<title>Last Resort</title>
<para>
(最後の手段)
</para>
<para>
<code>&quot;nomethod&quot;</code> should be followed by a reference to a function of four
parameters.  If defined, it is called when the overloading mechanism
cannot find a method for some operation.  The first three arguments of
this function coincide with the arguments for the corresponding method if
it were found, the fourth argument is the symbol
corresponding to the missing method.  If several methods are tried,
the last one is used.  Say, <code>1-$a</code> can be equivalent to
</para>
<para>
<code>&quot;nomethod&quot;</code> は、4 つのパラメータを持つ関数へのリファレンスが引き続きます。
これが定義されていれば、オーバーロードの仕組みで、
何らかの演算子に対するメソッドを見つけることができなかったときに、
呼び出されます。
この関数の最初の 3 つの引数は、本来、
呼ばれるはずだったメソッドに対する引数と一致し、4 番目の引数は、
見つからなかったメソッドに対応するシンボルとなります。
いくつかのメソッドが試されている場合には、最後のものが使われます。
たとえば、<code>1-$a</code> であれば、
<code>&quot;nomethod&quot; =&gt; &quot;nomethodMethod&quot;</code> の組が <code>use overload</code> 指示子で
指定されていれば:
</para>
<verbatim><![CDATA[
&nomethodMethod($a,1,1,"-")
]]></verbatim>
<para>
if the pair <code>&quot;nomethod&quot; =&gt; &quot;nomethodMethod&quot;</code> was specified in the
<code>use overload</code> directive.
</para>
<para>
と同様です。
</para>
<para>
The <code>&quot;nomethod&quot;</code> mechanism is <emphasis>not</emphasis> used for the dereference operators
( ${} @{} %{} &amp;{} *{} ).
</para>
<para>
<code>&quot;nomethod&quot;</code> の機構は デリファレンス演算子 ( ${} @{} %{} &amp;{} *{} ) では
<emphasis>使用されません</emphasis>。
</para>
<para>
If some operation cannot be resolved, and there is no function
assigned to <code>&quot;nomethod&quot;</code>, then an exception will be raised via die()--
unless <code>&quot;fallback&quot;</code> was specified as a key in <code>use overload</code> directive.
</para>
<para>
何らかの演算子が見つからず、<code>&quot;nomethod&quot;</code> に結び付けられた関数もない
場合には、(<code>&quot;fallback&quot;</code> が <code>use overload</code> 指示子のキーとして
指定されていない限り) die() による例外が発生します。
</para>
</sect2>
<sect2>
<title>Fallback</title>
<para>
(フォールバック)
</para>
<para>
The key <code>&quot;fallback&quot;</code> governs what to do if a method for a particular
operation is not found.  Three different cases are possible depending on
the value of <code>&quot;fallback&quot;</code>:
</para>
<para>
<code>&quot;fallback&quot;</code> は、特定の演算子に対するメソッドが見つからない場合の
動作を規定します。
<code>&quot;fallback&quot;</code> の value によって、3 つの場合があります:
</para>
<list>
<item><itemtext><code>undef</code></itemtext>
<para>
Perl tries to use a
substituted method (see <link xref='MAGIC AUTOGENERATION'>MAGIC AUTOGENERATION</link>).  If this fails, it
then tries to calls <code>&quot;nomethod&quot;</code> value; if missing, an exception
will be raised.
</para>
<para>
Perl は、代替のメソッドを使うことを試みます
(<link xref='MAGIC AUTOGENERATION'>MAGIC AUTOGENERATION</link> の節を参照してください)。
それもダメならば、<code>&quot;nomethod&quot;</code> を呼び出そうとします。
これも無い場合には、例外が発生することになります。
</para>
</item>
<item><itemtext>TRUE</itemtext>
<para>
(真)
</para>
<para>
The same as for the <code>undef</code> value, but no exception is raised.  Instead,
it silently reverts to what it would have done were there no <code>use overload</code>
present.
</para>
<para>
<code>undef</code> の場合と同じですが、例外を発生させません。
この場合、黙って、もし <code>use overload</code> がなかったときに、
行なってであろう動作に戻されることになります。
</para>
</item>
<item><itemtext>defined, but FALSE</itemtext>
<para>
(定義済みだが「偽」)
</para>
<para>
No autogeneration is tried.  Perl tries to call
<code>&quot;nomethod&quot;</code> value, and if this is missing, raises an exception.
</para>
<para>
マジック自動生成は行ないません。
Perl は、まず <code>&quot;nomethod&quot;</code> の実行を試みて、
これがなければ、例外を発生させます。
</para>
</item>
</list>
<para>
<strong>Note.</strong> <code>&quot;fallback&quot;</code> inheritance via @ISA is not carved in stone
yet, see <link xref='#Inheritance_and_overloading'>&quot;Inheritance and overloading&quot;</link>.
</para>
<para>
<strong>注意</strong>: @ISA 経由の <code>&quot;fallback&quot;</code> 継承はまだ行われません。
<link xref='#Inheritance_and_overloading'>&quot;Inheritance and overloading&quot;</link> を参照して下さい。
</para>
</sect2>
<sect2>
<title>Copy Constructor</title>
<para>
(コピーコンストラクタ)
</para>
<para>
The value for <code>&quot;=&quot;</code> is a reference to a function with three
arguments, i.e., it looks like the other values in <code>use
overload</code>. However, it does not overload the Perl assignment
operator. This would go against Camel hair.
</para>
<para>
<code>&quot;=&quot;</code> の値は、3 引数の関数へのリファレンスです。
つまり、<code>use overload</code> の他の値と似ているように見えます。
しかし、これは Perl の代入演算子をオーバーロードしません。
これは「ラクダの毛(Camel hair)」に対抗しています。
</para>
<para>
This operation is called in the situations when a mutator is applied
to a reference that shares its object with some other reference, such
as
</para>
<para>
この演算は、以下のような、他のリファレンスとオブジェクトを共有する
リファレンスに対して、ミューテータを使うときに呼び出されます。
</para>
<verbatim><![CDATA[
$a=$b;
++$a;
]]></verbatim>
<para>
To make this change $a and not change $b, a copy of <code>$$a</code> is made,
and $a is assigned a reference to this new object.  This operation is
done during execution of the <code>++$a</code>, and not during the assignment,
(so before the increment <code>$$a</code> coincides with <code>$$b</code>).  This is only
done if <code>++</code> is expressed via a method for <code>'++'</code> or <code>'+='</code> (or
<code>nomethod</code>).  Note that if this operation is expressed via <code>'+'</code>
a nonmutator, i.e., as in
</para>
<para>
これを、$a を変更し、$b を変更しないようにするために、<code>$$a</code> のコピーを作り、
この新しいオブジェクトへのリファレンスが $a に代入されます。
この操作は、<code>++$a</code> の実行中に (すなわち、その前に
<code>$$a</code> が <code>$$b</code> に一致します)、行われます。
これは<code>++</code> が <code>'++'</code> か <code>'+='</code> (か <code>nomethod</code>) のメソッドを通じて
表現されているときにだけ行なわれます。　
この演算子が、非ミューテータ <code>&quot;+&quot;</code> を使って記述されている場合、
</para>
<verbatim><![CDATA[
$a=$b;
$a=$a+1;
]]></verbatim>
<para>
then <code>$a</code> does not reference a new copy of <code>$$a</code>, since $$a does not
appear as lvalue when the above code is executed.
</para>
<para>
<code>$a</code> は <code>$$a</code> の新しいコピーのリファレンスではありません。
上記のコードが実行されたときに $$a は左辺値としては現れていないからです。
</para>
<para>
If the copy constructor is required during the execution of some mutator,
but a method for <code>'='</code> was not specified, it can be autogenerated as a
string copy if the object is a plain scalar.
</para>
<para>
コピーコンストラクタが、いくつかのミューテータの実行中に必要となって、
<code>'='</code> が指定されていないときには、そのオブジェクトが
単なるスカラであれば、文字列コピーとして自動生成されます。
</para>
<list>
<item><itemtext><strong>Example</strong></itemtext>
<para>
(<strong>例</strong>)
</para>
<para>
The actually executed code for
</para>
<para>
以下の記述で
</para>
<verbatim><![CDATA[
$a=$b;
        Something else which does not modify $a or $b....
++$a;
]]></verbatim>
<para>
may be
</para>
<para>
実際に実行されるコードは以下のようになります
</para>
<verbatim><![CDATA[
$a=$b;
        Something else which does not modify $a or $b....
$a = $a->clone(undef,"");
        $a->incr(undef,"");
]]></verbatim>
<para>
if $b was mathemagical, and <code>'++'</code> was overloaded with <code>\&amp;incr</code>,
<code>'='</code> was overloaded with <code>\&amp;clone</code>.
</para>
<para>
(もし $b がマスマジカルで、<code>'++'</code> が <code>\&amp;incr</code> でオーバーロードされていて、
<code>'='</code> が <code>\&amp;clone</code> でオーバーロードされていれば。)
</para>
</item>
</list>
<para>
Same behaviour is triggered by <code>$b = $a++</code>, which is consider a synonym for
<code>$b = $a; ++$a</code>.
</para>
<para>
同じ振る舞いは <code>$b = $a++</code> で引き起こされます; これは
<code>$b = $a; ++$a</code> と同義として扱われます。
</para>
</sect2>
</sect1>
<sect1>
<title>MAGIC AUTOGENERATION</title>
<para>
(マジック自動生成)
</para>
<para>
If a method for an operation is not found, and the value for  <code>&quot;fallback&quot;</code> is
TRUE or undefined, Perl tries to autogenerate a substitute method for
the missing operation based on the defined operations.  Autogenerated method
substitutions are possible for the following operations:
</para>
<para>
演算子に対するメソッドが見つからず、<code>&quot;fallback&quot;</code> が
「真」か「未定義」であれば、Perl は、定義されている演算子を
もとに、見つからなかった演算子の代わりのメソッドを自動生成しようと試みます。
以下の演算子に対して、自動生成代替メソッドが行なえます:
</para>
<list>
<item><itemtext><emphasis>Assignment forms of arithmetic operations</emphasis></itemtext>
<para>
(<emphasis>算術演算子の代入形式</emphasis>)
</para>
<para>
<code>$a+=$b</code> can use the method for <code>&quot;+&quot;</code> if the method for <code>&quot;+=&quot;</code>
is not defined.
</para>
<para>
<code>&quot;+=&quot;</code> メソッドが定義されていないとき、
<code>$a+=$b</code> は、<code>&quot;+&quot;</code> メソッドを使うことができます。
</para>
</item>
<item><itemtext><emphasis>Conversion operations</emphasis></itemtext>
<para>
(<emphasis>変換演算子</emphasis>)
</para>
<para>
String, numeric, and boolean conversion are calculated in terms of one
another if not all of them are defined.
</para>
<para>
文字列、数値、ブール値変換は、すべてが定義されてはいないとき、
互いに別のもので計算されます。
</para>
</item>
<item><itemtext><emphasis>Increment and decrement</emphasis></itemtext>
<para>
(<emphasis>インクリメントとデクリメント</emphasis>)
</para>
<para>
The <code>++$a</code> operation can be expressed in terms of <code>$a+=1</code> or <code>$a+1</code>,
and <code>$a--</code> in terms of <code>$a-=1</code> and <code>$a-1</code>.
</para>
<para>
演算 <code>++$a</code> は、<code>$a+=1</code> か <code>$a+1</code> で、演算 <code>$a--</code> は、
<code>$a-=1</code> か <code>$a-1</code> で表現することができます。
</para>
</item>
<item><itemtext><code>abs($a)</code></itemtext>
<para>
can be expressed in terms of <code>$a&lt;0</code> and <code>-$a</code> (or <code>0-$a</code>).
</para>
<para>
abs($a) は、<code>$a&lt;0</code> と <code>-$a</code> (または <code>0-$a</code>) で表現できます。
</para>
</item>
<item><itemtext><emphasis>Unary minus</emphasis></itemtext>
<para>
(<emphasis>単項のマイナス</emphasis>)
</para>
<para>
can be expressed in terms of subtraction.
</para>
<para>
単項のマイナスは、引き算を使って表現できます。
</para>
</item>
<item><itemtext><emphasis>Negation</emphasis></itemtext>
<para>
(<emphasis>否定</emphasis>)
</para>
<para>
<code>!</code> and <code>not</code> can be expressed in terms of boolean conversion, or
string or numerical conversion.
</para>
<para>
<code>!</code> と <code>not</code> はブール値変換、文字列変換、数値変換を使って
表現できます。
</para>
</item>
<item><itemtext><emphasis>Concatenation</emphasis></itemtext>
<para>
(<emphasis>連結</emphasis>)
</para>
<para>
can be expressed in terms of string conversion.
</para>
<para>
連結は、文字列変換を使って表現できます。
</para>
</item>
<item><itemtext><emphasis>Comparison operations</emphasis></itemtext>
<para>
(<emphasis>比較演算子</emphasis>)
</para>
<para>
can be expressed in terms of its &quot;spaceship&quot; counterpart: either
<code>&lt;=&gt;</code> or <code>cmp</code>:
</para>
<para>
比較演算は、それぞれに対応する「スペースシップ」演算
(<code>&lt;=&lt;&gt;</code> か <code>cmp</code>) を用いて表現することができます:
</para>
<verbatim><![CDATA[
<, >, <=, >=, ==, != 	in terms of <=>
lt, gt, le, ge, eq, ne 	in terms of cmp
]]></verbatim>
</item>
<item><itemtext><emphasis>Iterator</emphasis></itemtext>
<para>
(<emphasis>反復子</emphasis>)
</para>
<verbatim><![CDATA[
<>				in terms of builtin operations
]]></verbatim>
</item>
<item><itemtext><emphasis>Dereferencing</emphasis></itemtext>
<para>
(<emphasis>デリファレンス</emphasis>)
</para>
<verbatim><![CDATA[
${} @{} %{} &{} *{}		in terms of builtin operations
]]></verbatim>
</item>
<item><itemtext><emphasis>Copy operator</emphasis></itemtext>
<para>
(<emphasis>コピー演算子</emphasis>)
</para>
<para>
can be expressed in terms of an assignment to the dereferenced value, if this
value is a scalar and not a reference.
</para>
<para>
コピー演算は被参照した値が、リファレンスではないスカラであれば、
その値への代入という形で表現できます。
</para>
</item>
</list>
</sect1>
<sect1>
<title>Losing overloading</title>
<para>
(オーバーロードが失われるとき)
</para>
<para>
The restriction for the comparison operation is that even if, for example,
`<code>cmp</code>' should return a blessed reference, the autogenerated `<code>lt</code>'
function will produce only a standard logical value based on the
numerical value of the result of `<code>cmp</code>'.  In particular, a working
numeric conversion is needed in this case (possibly expressed in terms of
other conversions).
</para>
<para>
比較演算子に対する制限は、たとえば、`<code>cmp</code>' が bless された
リファレンスを返さなければならないとしても、自動生成された関数
`<code>lt</code>' は、`<code>cmp</code>' の結果の数値に基づく標準の論理値だけを
作り出します。
特に、この場合には、(ときには別の変換で表わされた)
数値変換が使えないといけません。
</para>
<para>
Similarly, <code>.=</code>  and <code>x=</code> operators lose their mathemagical properties
if the string conversion substitution is applied.
</para>
<para>
同様に、<code>.=</code> 演算子や <code>x=</code> 演算子も、文字列変換による代替が起これば、
マスマジカルな性質がなくなります。
</para>
<para>
When you chop() a mathemagical object it is promoted to a string and its
mathemagical properties are lost.  The same can happen with other
operations as well.
</para>
<para>
マスマジカルなオブジェクトを chop() すると、文字列になり、
マスマジカルな性質はなくなります。
同じことは、他の演算でも起こります。
</para>
</sect1>
<sect1>
<title>Run-time Overloading</title>
<para>
(実行時オーバーロード)
</para>
<para>
Since all <code>use</code> directives are executed at compile-time, the only way to
change overloading during run-time is to
</para>
<para>
全ての <code>use</code> 指示子はコンパイル時に実行されるので、実行時にオーバーロードを
変更する唯一の方法は以下のものです
</para>
<verbatim><![CDATA[
eval 'use overload "+" => \&addmethod';
]]></verbatim>
<para>
You can also use
</para>
<para>
また、以下のようにもできます
</para>
<verbatim><![CDATA[
eval 'no overload "+", "--", "<="';
]]></verbatim>
<para>
though the use of these constructs during run-time is questionable.
</para>
<para>
しかし実行時にこのような構文を使うのは問題が多いです。
</para>
</sect1>
<sect1>
<title>Public functions</title>
<para>
(パブリック関数)
</para>
<para>
Package <code>overload.pm</code> provides the following public functions:
</para>
<para>
パッケージ <code>overload.pm</code> は以下のパブリック関数を提供します:
</para>
<list>
<item><itemtext>overload::StrVal(arg)</itemtext>
<para>
Gives string value of <code>arg</code> as in absence of stringify overloading.
</para>
<para>
文字列化のオーバーロードがないものとしたときの <code>arg</code> の文字列値を
与えます。
</para>
</item>
<item><itemtext>overload::Overloaded(arg)</itemtext>
<para>
Returns true if <code>arg</code> is subject to overloading of some operations.
</para>
<para>
<code>arg</code> が何らかの操作のオーバーロードの影響下にあるなら真を返します。
</para>
</item>
<item><itemtext>overload::Method(obj,op)</itemtext>
<para>
Returns <code>undef</code> or a reference to the method that implements <code>op</code>.
</para>
<para>
<code>op</code> を実装しているメソッドへのリファレンス、あるいは <code>undef</code> を
返します。
</para>
</item>
</list>
</sect1>
<sect1>
<title>Overloading constants</title>
<para>
(定数のオーバーロード)
</para>
<para>
For some application Perl parser mangles constants too much.  It is possible
to hook into this process via overload::constant() and overload::remove_constant()
functions.
</para>
<para>
アプリケーションによっては Perl パーザが定数をいじりすぎる場合があります。
この処理を overload::constant() 関数と overload::remove_constant() 関数を
使ってフックできます。
</para>
<para>
These functions take a hash as an argument.  The recognized keys of this hash
are
</para>
<para>
これらの関数は引数としてハッシュを取ります。
ハッシュのキーとして認識されるのは以下のものです。
</para>
<list>
<item><itemtext>integer</itemtext>
<para>
to overload integer constants,
</para>
<para>
整数定数をオーバーロードします。
</para>
</item>
<item><itemtext>float</itemtext>
<para>
to overload floating point constants,
</para>
<para>
浮動小数点数定数をオーバーロードします。
</para>
</item>
<item><itemtext>binary</itemtext>
<para>
to overload octal and hexadecimal constants,
</para>
<para>
8 進および 16 進定数をオーバーロードします。
</para>
</item>
<item><itemtext>q</itemtext>
<para>
to overload <code>q</code>-quoted strings, constant pieces of <code>qq</code>- and <code>qx</code>-quoted
strings and here-documents,
</para>
<para>
<code>q</code>-クォートされた文字列、<code>qq</code>- および <code>qx</code>-クォートされた文字列の
定数片、ヒヤドキュメントをオーバーロードします。
</para>
</item>
<item><itemtext>qr</itemtext>
<para>
to overload constant pieces of regular expressions.
</para>
<para>
正規表現の定数片をオーバーロードします。
</para>
</item>
</list>
<para>
The corresponding values are references to functions which take three arguments:
the first one is the <emphasis>initial</emphasis> string form of the constant, the second one
is how Perl interprets this constant, the third one is how the constant is used.
Note that the initial string form does not
contain string delimiters, and has backslashes in backslash-delimiter
combinations stripped (thus the value of delimiter is not relevant for
processing of this string).  The return value of this function is how this
constant is going to be interpreted by Perl.  The third argument is undefined
unless for overloaded <code>q</code>- and <code>qr</code>- constants, it is <code>q</code> in single-quote
context (comes from strings, regular expressions, and single-quote HERE
documents), it is <code>tr</code> for arguments of <code>tr</code>/<code>y</code> operators,
it is <code>s</code> for right-hand side of <code>s</code>-operator, and it is <code>qq</code> otherwise.
</para>
<para>
対応する値は 3 つの引数を取る関数へのリファレンスへのリファレンスです:
最初のものは定数の <emphasis>初期</emphasis> 文字列形式、2 番目は Perl がこの定数を
どのように解釈するか、3 番目は定数をどのように使うかです。
初期文字列形式は文字列デリミタを含んでおらず、バックスラッシュ-デリミタの
組み合わせでのバックスラッシュは削除されている(従ってデリミタの値は
この文字列を処理するには適切ではない)ことに注意してください。
この関数の返り値はこの定数が Perl によってどのように解釈されるかです。
3 番目の引数は、オーバーロードされた <code>q</code>- か <code>qr</code>- 定数以外では未定義値、
(文字列、正規表現、シングルクォートヒヤドキュメントによる)
シングルクォートコンテキストの場合は <code>q</code>、<code>tr</code>/<code>y</code> 演算子の引数の
場合は <code>tr</code>、<code>s</code> 演算子の右側の場合は <code>s</code>、その他では <code>qq</code> になります。
</para>
<para>
Since an expression <code>&quot;ab$cd,,&quot;</code> is just a shortcut for <code>'ab' . $cd . ',,'</code>,
it is expected that overloaded constant strings are equipped with reasonable
overloaded catenation operator, otherwise absurd results will result.
Similarly, negative numbers are considered as negations of positive constants.
</para>
<para>
式 <code>&quot;ab$cd,,&quot;</code> は単に <code>'ab' . $cd . ',,'</code> のショートカットなので、
オーバーロード定数文字列は妥当なオーバーロードされた結合演算子を
装備していると想定していて、さもなければ不合理な結果となります。
同様に、負数は正数の否定として扱われます。
</para>
<para>
Note that it is probably meaningless to call the functions overload::constant()
and overload::remove_constant() from anywhere but import() and unimport() methods.
From these methods they may be called as
</para>
<para>
import() と unimport() メソッド以外から overload::constant() や
overload::remove_constant() を呼び出すのはおそらく無意味であることに
注意してください。
これらのメソッドからは、以下のようにして呼び出されます
</para>
<verbatim><![CDATA[
sub import {
  shift;
  return unless @_;
  die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
  overload::constant integer => sub {Math::BigInt->new(shift)};
}
]]></verbatim>
<para>
<strong>BUGS</strong> Currently overloaded-ness of constants does not propagate
into <code>eval '...'</code>.
</para>
<para>
<strong>バグ</strong> 現在のところ、定数のオーバーロード性は <code>eval '...'</code> に伝播しません。
</para>
</sect1>
<sect1>
<title>IMPLEMENTATION</title>
<para>
(実装)
</para>
<para>
What follows is subject to change RSN.
</para>
<para>
以下はすぐに変更される可能性があります。
</para>
<para>
The table of methods for all operations is cached in magic for the
symbol table hash for the package.  The cache is invalidated during
processing of <code>use overload</code>, <code>no overload</code>, new function
definitions, and changes in @ISA. However, this invalidation remains
unprocessed until the next <code>bless</code>ing into the package. Hence if you
want to change overloading structure dynamically, you'll need an
additional (fake) <code>bless</code>ing to update the table.
</para>
<para>
すべての演算のためのメソッドのテーブルは、該当パッケージの
シンボルテーブルに対するマジックとしてキャッシュされます。
このキャッシュは <code>use overload</code>, <code>no overload</code>, 新しい関数定義、
@ISA の変更のいずれかの処理の間に無効化されます。
しかし、この無効化はパッケージに対する次の <code>bless</code> までは
実行されずに残されます。
つまり、オーバーロード構造を動的に変更したいならば、テーブルを
更新するために、(意味の無い) <code>bless</code> を行なう必要があります。
</para>
<para>
(Every SVish thing has a magic queue, and magic is an entry in that
queue.  This is how a single variable may participate in multiple
forms of magic simultaneously.  For instance, environment variables
regularly have two forms at once: their %ENV magic and their taint
magic. However, the magic which implements overloading is applied to
the stashes, which are rarely used directly, thus should not slow down
Perl.)
</para>
<para>
(すべての SV 風のものは、マジックキューを持っており、マジックが
キューのエントリになっています。
これによって、1 つの変数が、同時に複数のマジックの形式に
関ることができるのです。
たとえば、環境変数は普段、%ENV マジックと「汚染」マジックの
2 つの形式を一度に持っています。
しかし、オーバーロードを実装しているマジックは隠してあるものに
適用され、これはめったに直接使うことはないため、
Perl の速度を低下させないはずです。)
</para>
<para>
If an object belongs to a package using overload, it carries a special
flag.  Thus the only speed penalty during arithmetic operations without
overloading is the checking of this flag.
</para>
<para>
オブジェクトがオーバーロードを使うパッケージに属するならば、
そのオブジェクトには、特別なフラグが用意されます。
つまり、オーバーロードされていない算術演算を行なうときの、
スピードに対する影響は、このフラグのチェックのみです。
</para>
<para>
In fact, if <code>use overload</code> is not present, there is almost no overhead
for overloadable operations, so most programs should not suffer
measurable performance penalties.  A considerable effort was made to
minimize the overhead when overload is used in some package, but the
arguments in question do not belong to packages using overload.  When
in doubt, test your speed with <code>use overload</code> and without it.  So far
there have been no reports of substantial speed degradation if Perl is
compiled with optimization turned on.
</para>
<para>
実際、<code>use overload</code> が存在しなければ、オーバーロード可能な演算に
対するオーバヘッドはほとんど無く、ほとんどのプログラムで、
認識できるようなパフォーマスの低下はないはずです。
あるパッケージでオーバーロードが使われても、
対象の引数がオーバーロードを使ったパッケージに属していない場合には、
オーバヘッドの最小限にする最大限の努力が為されました。
疑わしいときには、<code>use overload</code> がある場合と無い場合で、
スピードのテストをしてください。　これまでのところ、Perl が
最適化を指定してコンパイル場合には、顕著なスピードの低下の報告は
あがっていません。
</para>
<para>
There is no size penalty for data if overload is not used. The only
size penalty if overload is used in some package is that <emphasis>all</emphasis> the
packages acquire a magic during the next <code>bless</code>ing into the
package. This magic is three-words-long for packages without
overloading, and carries the cache table if the package is overloaded.
</para>
<para>
オーバーロードが使われないときには、データの大きさには影響しません。
あるパッケージでオーバーロードを使うときの唯一のサイズペナルティは、
<emphasis>全ての</emphasis>パッケージが次のパッケージへの <code>bless</code> 時に
マジックを求めることです。
このマジックはオーバーロードを使わないパッケージの場合は 3 ワード長で、
オーバーロードを使うパッケージの場合はキャッシュテーブルを運びます。
</para>
<para>
Copying (<code>$a=$b</code>) is shallow; however, a one-level-deep copying is
carried out before any operation that can imply an assignment to the
object $a (or $b) refers to, like <code>$a++</code>.  You can override this
behavior by defining your own copy constructor (see <link xref='#Copy_Constructor'>&quot;Copy Constructor&quot;</link>).
</para>
<para>
<code>$a=$b</code> のようなコピーは、表層的なものです。
しかし、<code>$a++</code> のように、$b (または、$a) が参照するオブジェクトへの
代入を意味する演算の前に、1 層深度のコピーが行なわれます。
この動作は、
自分でコピーコンストラクタを定義することによって変更することが
できます (<link xref='#Copy_Constructor'>&quot;Copy Constructor&quot;</link>の項を参照してください)。
</para>
<para>
It is expected that arguments to methods that are not explicitly supposed
to be changed are constant (but this is not enforced).
</para>
<para>
明示的にサポートされていないメソッドに対する引数は、
定数であることが期待されます (が、強制はされません)。
</para>
</sect1>
<sect1>
<title>Metaphor clash</title>
<para>
(比喩の衝突)
</para>
<para>
One may wonder why the semantic of overloaded <code>=</code> is so counter intuitive.
If it <emphasis>looks</emphasis> counter intuitive to you, you are subject to a metaphor
clash.
</para>
<para>
なぜオーバーロードされた <code>=</code> の意味論がこんなに直感的でないかを
不思議に思う人がいるかもしれません。
もし直感的でない <emphasis>ように見える</emphasis> なら、比喩の衝突に影響されています。
</para>
<para>
Here is a Perl object metaphor:
</para>
<para>
Perl のオブジェクトの比喩はこれです:
</para>
<para>
<emphasis>  object is a reference to blessed data</emphasis>
</para>
<para>
<emphasis>  オブジェクトは bless されたデータへのリファレンス</emphasis>
</para>
<para>
and an arithmetic metaphor:
</para>
<para>
そして算術の比喩はこれです:
</para>
<para>
<emphasis>  object is a thing by itself</emphasis>.
</para>
<para>
<emphasis>  オブジェクトはそれ自体が一つのもの</emphasis>。
</para>
<para>
The <emphasis>main</emphasis> problem of overloading <code>=</code> is the fact that these metaphors
imply different actions on the assignment <code>$a = $b</code> if $a and $b are
objects.  Perl-think implies that $a becomes a reference to whatever
$b was referencing.  Arithmetic-think implies that the value of &quot;object&quot;
$a is changed to become the value of the object $b, preserving the fact
that $a and $b are separate entities.
</para>
<para>
<code>=</code> をオーバーロードする <emphasis>主な</emphasis> 問題は、$a と $b がオブジェクトのとき、
<code>$a = $b</code> という代入はこれらの比喩からは異なった動作を暗示するという
事実です。
Perl 的な考え方は、$a は $b がリファレンスしている何かへのリファレンスに
なることを暗示します。
算術的な考え方は、$a と $b が別々の実体であることは維持したまま、
「オブジェクト」$a の値は、オブジェクト $b の値になることを暗示します。
</para>
<para>
The difference is not relevant in the absence of mutators.  After
a Perl-way assignment an operation which mutates the data referenced by $a
would change the data referenced by $b too.  Effectively, after
<code>$a = $b</code> values of $a and $b become <emphasis>indistinguishable</emphasis>.
</para>
<para>
ミューテータがないなら、これは違いはありません。
Perl 式の代入の後、$a でリファレンスされているデータを変更する演算は
$b でリファレンスされているデータも変更します。
事実上、<code>$a = $b</code> の後では $a と $b の値は <emphasis>区別ができない</emphasis> ものに
なります。
</para>
<para>
On the other hand, anyone who has used algebraic notation knows the
expressive power of the arithmetic metaphor.  Overloading works hard
to enable this metaphor while preserving the Perlian way as far as
possible.  Since it is not not possible to freely mix two contradicting
metaphors, overloading allows the arithmetic way to write things <emphasis>as
far as all the mutators are called via overloaded access only</emphasis>.  The
way it is done is described in <link xref='Copy Constructor'>Copy Constructor</link>.
</para>
<para>
一方、算術記法を使っている人は誰でも、算術の比喩の表現力を知っています。
オーバーロードはこの比喩を有効にするのは難しい一方、Perl 的な方法を
出来るだけ保存した形で動作します。
2 つの矛盾する比喩を自由に混ぜることは不可能なので、
オーバーロードは <emphasis>全てのミューテータがオーバーロードされた
アクセス経由でのみ呼び出される限りにおいて</emphasis> 算術的な方法で
書くことができます。
これを行う方法は <link xref='Copy Constructor'>Copy Constructor</link> に記述されています。
</para>
<para>
If some mutator methods are directly applied to the overloaded values,
one may need to <emphasis>explicitly unlink</emphasis> other values which references the
same value:
</para>
<para>
あるミューテータメソッドがオーバーロードされた値に直接適用される場合、
同じ値をリファレンスしているほかの値と <emphasis>明示的にリンクを切る</emphasis> 必要が
あるかもしれません:
</para>
<verbatim><![CDATA[
$a = new Data 23;
...
$b = $a;		# $b is "linked" to $a
...
$a = $a->clone;	# Unlink $b from $a
$a->increment_by(4);
]]></verbatim>
<para>
Note that overloaded access makes this transparent:
</para>
<para>
オーバーロードされたアクセスはこれを透過的にすることに注意してください:
</para>
<verbatim><![CDATA[
$a = new Data 23;
$b = $a;		# $b is "linked" to $a
$a += 4;		# would unlink $b automagically
]]></verbatim>
<para>
However, it would not make
</para>
<para>
しかし、以下のようにしても、
</para>
<verbatim><![CDATA[
$a = new Data 23;
$a = 4;		# Now $a is a plain 4, not 'Data'
]]></verbatim>
<para>
preserve &quot;objectness&quot; of $a.  But Perl <emphasis>has</emphasis> a way to make assignments
to an object do whatever you want.  It is just not the overload, but
tie()ing interface (see <link xref='perlfunc#tie'>perlfunc/tie</link>).  Adding a FETCH() method
which returns the object itself, and STORE() method which changes the
value of the object, one can reproduce the arithmetic metaphor in its
completeness, at least for variables which were tie()d from the start.
</para>
<para>
$a の「オブジェクト性」は保存されません。
しかし、Perl にはオブジェクトへの代入を望み通りのやり方にする方法が
<emphasis>あります</emphasis>。
これは単にオーバーロードではなく、tie() するインターフェースです
(<link xref='perlfunc#tie'>perlfunc/tie</link> を参照してください)。
オブジェクト自身を返す FETCH() メソッドと、オブジェクトの値を変更する
STORE() メソッドを追加することで、少なくとも最初から tie() されている
変数に対しては、完全性に対して算術の比喩を再現できます。
</para>
<para>
(Note that a workaround for a bug may be needed, see <link xref='#BUGS'>&quot;BUGS&quot;</link>.)
</para>
<para>
(このバグの回避策が必要かもしれないことに注意してください; <link xref='#BUGS'>&quot;BUGS&quot;</link> を
参照してください。)
</para>
</sect1>
<sect1>
<title>Cookbook</title>
<para>
(レシピ集)
</para>
<para>
Please add examples to what follows!
</para>
<para>
どうかこれに引き続く例を追加してください!
</para>
<sect2>
<title>Two-face scalars</title>
<para>
(2 面スカラ)
</para>
<para>
Put this in <filename>two_face.pm</filename> in your Perl library directory:
</para>
<para>
これを <filename>two_face.pm</filename> として Perl ライブラリディレクトリに置きます:
</para>
<verbatim><![CDATA[
package two_face;		# Scalars with separate string and
                              # numeric values.
sub new { my $p = shift; bless [@_], $p }
use overload '""' => \&str, '0+' => \&num, fallback => 1;
sub num {shift->[1]}
sub str {shift->[0]}
]]></verbatim>
<para>
Use it as follows:
</para>
<para>
以下のようにして使います:
</para>
<verbatim><![CDATA[
require two_face;
my $seven = new two_face ("vii", 7);
printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
print "seven contains `i'\n" if $seven =~ /i/;
]]></verbatim>
<para>
(The second line creates a scalar which has both a string value, and a
numeric value.)  This prints:
</para>
<para>
(2 行目は文字列値と数値の両方を持つスカラを作ります。)
これは以下を出力します:
</para>
<verbatim><![CDATA[
seven=vii, seven=7, eight=8
seven contains `i'
]]></verbatim>
</sect2>
<sect2>
<title>Two-face references</title>
<para>
(2 面リファレンス)
</para>
<para>
Suppose you want to create an object which is accessible as both an
array reference and a hash reference, similar to the
<link xref='perlref#Pseudo-hashes:_Using_an_array_'>pseudo-hash</link>
builtin Perl type.  Let's make it better than a pseudo-hash by
allowing index 0 to be treated as a normal element.
</para>
<para>
Perl 組み込みの
<link xref='perlref#Pseudo-hashes:_Using_an_array_'>擬似ハッシュ</link> 型のような、
配列リファレンスとハッシュリファレンスの両方としてアクセス可能な
オブジェクトを作りたいとします。
添え字 0 を普通の要素として扱える擬似ハッシュよりもよいものを作りましょう。
</para>
<verbatim><![CDATA[
package two_refs;
use overload '%{}' => \&gethash, '@{}' => sub { $ {shift()} };
sub new {
  my $p = shift;
  bless \ [@_], $p;
}
sub gethash {
  my %h;
  my $self = shift;
  tie %h, ref $self, $self;
  \%h;
}
]]></verbatim>
<verbatim><![CDATA[
sub TIEHASH { my $p = shift; bless \ shift, $p }
my %fields;
my $i = 0;
$fields{$_} = $i++ foreach qw{zero one two three};
sub STORE {
  my $self = ${shift()};
  my $key = $fields{shift()};
  defined $key or die "Out of band access";
  $$self->[$key] = shift;
}
sub FETCH {
  my $self = ${shift()};
  my $key = $fields{shift()};
  defined $key or die "Out of band access";
  $$self->[$key];
}
]]></verbatim>
<para>
Now one can access an object using both the array and hash syntax:
</para>
<para>
これで配列とハッシュの両方の文法を使ってオブジェクトにアクセスできます:
</para>
<verbatim><![CDATA[
my $bar = new two_refs 3,4,5,6;
$bar->[2] = 11;
$bar->{two} == 11 or die 'bad hash fetch';
]]></verbatim>
<para>
Note several important features of this example.  First of all, the
<emphasis>actual</emphasis> type of $bar is a scalar reference, and we do not overload
the scalar dereference.  Thus we can get the <emphasis>actual</emphasis> non-overloaded
contents of $bar by just using <code>$$bar</code> (what we do in functions which
overload dereference).  Similarly, the object returned by the
TIEHASH() method is a scalar reference.
</para>
<para>
この例のいくつかの重要な機能に注意してください。
まず、$bar の <emphasis>実際の</emphasis> 型はスカラリファレンスで、スカラデリファレンスは
オーバーロードしていません。
従って、単に(関数の中でオーバーロードデリファレンスをしている方法である)
<code>$$bar</code> とすることで、<emphasis>実際の</emphasis> $bar のオーバーロードされていない中身を
得ることができます。
同様に、TIEHASH() メソッドで返されるオブジェクトはスカラリファレンスです。
</para>
<para>
Second, we create a new tied hash each time the hash syntax is used.
This allows us not to worry about a possibility of a reference loop,
would would lead to a memory leak.
</para>
<para>
2 番目に、ハッシュ文法が使われるたびに新しい tie されたハッシュを作ります。
これにより、メモリリークを引き起こすことになるリファレンスループの
可能性について心配しなくても良くなります。
</para>
<para>
Both these problems can be cured.  Say, if we want to overload hash
dereference on a reference to an object which is <emphasis>implemented</emphasis> as a
hash itself, the only problem one has to circumvent is how to access
this <emphasis>actual</emphasis> hash (as opposed to the <emphasis>virtual</emphasis> hash exhibited by the
overloaded dereference operator).  Here is one possible fetching routine:
</para>
<para>
これらの問題の両方は修正できます。
例えば、ハッシュ自身として <emphasis>実装されている</emphasis> オブジェクトへの
リファレンスに対するハッシュのデリファレンスをオーバーロードしたい場合、
回避する必要がある唯一の問題は、(オーバーロードされた
デリファレンス演算子によって提供される <emphasis>仮想</emphasis> ハッシュではなく)
この <emphasis>実際の</emphasis> ハッシュにどうやってアクセスするかです。
これは可能なフェッチルーチンの一つです:
</para>
<verbatim><![CDATA[
sub access_hash {
  my ($self, $key) = (shift, shift);
  my $class = ref $self;
  bless $self, 'overload::dummy'; # Disable overloading of %{}
  my $out = $self->{$key};
  bless $self, $class;	# Restore overloading
  $out;
}
]]></verbatim>
<para>
To remove creation of the tied hash on each access, one may an extra
level of indirection which allows a non-circular structure of references:
</para>
<para>
アクセス毎に tie されたハッシュの生成をしないようにするには、
リファレンスの非円形の構造を許すための追加のレベルの間接化を行います:
</para>
<verbatim><![CDATA[
package two_refs1;
use overload '%{}' => sub { ${shift()}->[1] },
             '@{}' => sub { ${shift()}->[0] };
sub new {
  my $p = shift;
  my $a = [@_];
  my %h;
  tie %h, $p, $a;
  bless \ [$a, \%h], $p;
}
sub gethash {
  my %h;
  my $self = shift;
  tie %h, ref $self, $self;
  \%h;
}
]]></verbatim>
<verbatim><![CDATA[
sub TIEHASH { my $p = shift; bless \ shift, $p }
my %fields;
my $i = 0;
$fields{$_} = $i++ foreach qw{zero one two three};
sub STORE {
  my $a = ${shift()};
  my $key = $fields{shift()};
  defined $key or die "Out of band access";
  $a->[$key] = shift;
}
sub FETCH {
  my $a = ${shift()};
  my $key = $fields{shift()};
  defined $key or die "Out of band access";
  $a->[$key];
}
]]></verbatim>
<para>
Now if $baz is overloaded like this, then <code>$baz</code> is a reference to a
reference to the intermediate array, which keeps a reference to an
actual array, and the access hash.  The tie()ing object for the access
hash is a reference to a reference to the actual array, so
</para>
<para>
ここでもし $bar がこのようにオーバーロードされると、<code>$baz</code> は
実際の配列とアクセスハッシュへのリファレンスを保持している中間の配列への
リファレンスへのリファレンスです。
アクセスハッシュへの tie() したオブジェクトは 実際の配列への
リファレンスへのリファレンスなので、
</para>
<list>
<item><para>
There are no loops of references.
</para>
<para>
リファレンスのループはありません。
</para>
</item>
<item><para>
Both &quot;objects&quot; which are blessed into the class <code>two_refs1</code> are
references to a reference to an array, thus references to a <emphasis>scalar</emphasis>.
Thus the accessor expression <code>$$foo-&gt;[$ind]</code> involves no
overloaded operations.
</para>
<para>
<code>two_refs1</code> クラスに bless された両方の「オブジェクト」は配列への
リファレンスへのリファレンスなので、<emphasis>スカラ</emphasis> へのリファレンスです。
従って、アクセサ式 <code>$$foo-&gt;[$ind]</code> はオーバーロードされた演算を
伴いません。
</para>
</item>
</list>
</sect2>
<sect2>
<title>Symbolic calculator</title>
<para>
(シンボリック計算機)
</para>
<para>
Put this in <filename>symbolic.pm</filename> in your Perl library directory:
</para>
<para>
この <filename>symbolic.pm</filename> をあなたの Perl ライブラリディレクトリに入れてください:
</para>
<verbatim><![CDATA[
package symbolic;		# Primitive symbolic calculator
use overload nomethod => \&wrap;
]]></verbatim>
<verbatim><![CDATA[
sub new { shift; bless ['n', @_] }
sub wrap {
  my ($obj, $other, $inv, $meth) = @_;
  ($obj, $other) = ($other, $obj) if $inv;
  bless [$meth, $obj, $other];
}
]]></verbatim>
<para>
This module is very unusual as overloaded modules go: it does not
provide any usual overloaded operators, instead it provides the {tag:link xref='Last
Resort'}Last
Resort</link> operator <code>nomethod</code>.  In this example the corresponding
subroutine returns an object which encapsulates operations done over
the objects: <code>new symbolic 3</code> contains <code>['n', 3]</code>, <code>2 + new
symbolic 3</code> contains <code>['+', 2, ['n', 3]]</code>.
</para>
<para>
このモジュールは、オーバーロードするモジュールとしてはかなり変わっています:
通常のオーバーロード演算子は何も提供せず、その代わりに
<link xref='Last Resort'>Last Resort</link> 演算子 <code>nomethod</code> を提供します。
この例で、対応するサブルーチンはオブジェクトに対して行われた演算を
カプセル化したオブジェクトを返します:
<code>new symbolic 3</code> は <code>['n', 3]</code> を含み、<code>2 + new symbolic 3</code> は
<code>['+', 2, ['n', 3]]</code> を含みます。
</para>
<para>
Here is an example of the script which &quot;calculates&quot; the side of
circumscribed octagon using the above package:
</para>
<para>
以下は、上述のパッケージを使って外接 8 角形の辺を「計算する」スクリプトの
例です:
</para>
<verbatim><![CDATA[
require symbolic;
my $iter = 1;			# 2**($iter+2) = 8
my $side = new symbolic 1;
my $cnt = $iter;
]]></verbatim>
<verbatim><![CDATA[
while ($cnt--) {
  $side = (sqrt(1 + $side**2) - 1)/$side;
}
print "OK\n";
]]></verbatim>
<para>
The value of $side is
</para>
<para>
$side の値は
</para>
<verbatim><![CDATA[
['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
	               undef], 1], ['n', 1]]
]]></verbatim>
<para>
Note that while we obtained this value using a nice little script,
there is no simple way to <emphasis>use</emphasis> this value.  In fact this value may
be inspected in debugger (see <link xref='perldebug'>perldebug</link>), but ony if
<code>bareStringify</code> <strong>O</strong>ption is set, and not via <code>p</code> command.
</para>
<para>
素晴らしい小さいスクリプトを使ってこの値を得ることは出来ましたが、
この値を <emphasis>使う</emphasis> 単純な方法はないことに注意してください。
実際この値はデバッガ (<link xref='perldebug'>perldebug</link> を参照してください) で検査できますが、
<code>bareStringify</code> オプションがセットされていて、<code>p</code> コマンド
経由でないときのみです。
</para>
<para>
If one attempts to print this value, then the overloaded operator
<code>&quot;&quot;</code> will be called, which will call <code>nomethod</code> operator.  The
result of this operator will be stringified again, but this result is
again of type <code>symbolic</code>, which will lead to an infinite loop.
</para>
<para>
もしこの値を表示しようとすると、オーバーロードされた演算子
<code>&quot;&quot;</code> が呼び出され、これは <code>nomethod</code> 演算子を呼び出します。
この演算子の結果として再び文字列化が行われますが、この結果は再び
<code>symbolic</code> 型なので、無限ループを引き起こします。
</para>
<para>
Add a pretty-printer method to the module <filename>symbolic.pm</filename>:
</para>
<para>
<filename>symbolic.pm</filename> モジュールに整形表示メソッドを追加します:
</para>
<verbatim><![CDATA[
sub pretty {
  my ($meth, $a, $b) = @{+shift};
  $a = 'u' unless defined $a;
  $b = 'u' unless defined $b;
  $a = $a->pretty if ref $a;
  $b = $b->pretty if ref $b;
  "[$meth $a $b]";
}
]]></verbatim>
<para>
Now one can finish the script by
</para>
<para>
これでスクリプトの末尾に以下のように書けます
</para>
<verbatim><![CDATA[
print "side = ", $side->pretty, "\n";
]]></verbatim>
<para>
The method <code>pretty</code> is doing object-to-string conversion, so it
is natural to overload the operator <code>&quot;&quot;</code> using this method.  However,
inside such a method it is not necessary to pretty-print the
<emphasis>components</emphasis> $a and $b of an object.  In the above subroutine
<code>&quot;[$meth $a $b]&quot;</code> is a catenation of some strings and components $a
and $b.  If these components use overloading, the catenation operator
will look for an overloaded operator <code>.</code>; if not present, it will
look for an overloaded operator <code>&quot;&quot;</code>.  Thus it is enough to use
</para>
<para>
メソッド <code>pretty</code> はオブジェクト-文字列変換を行うので、
このメソッドを使って演算子 <code>&quot;&quot;</code> をオーバーロードするのが自然です。
しかし、このようなメソッドの内部では
オブジェクトの <emphasis>要素</emphasis> である $a や $b を整形表示する必要はありません。
上述のサブルーチンで、<code>&quot;[$meth $a $b]&quot;</code> は、なんらかの文字列と要素 $a および
$b の連結です。
もしこれらの要素がオーバーロードを使っていると、連結演算子は
オーバーロードされた演算子 <code>.</code> を探します; もし存在しなければ、
オーバーロードされた演算子 <code>&quot;&quot;</code> を探します。
従って以下を使えば十分です
</para>
<verbatim><![CDATA[
use overload nomethod => \&wrap, '""' => \&str;
sub str {
  my ($meth, $a, $b) = @{+shift};
  $a = 'u' unless defined $a;
  $b = 'u' unless defined $b;
  "[$meth $a $b]";
}
]]></verbatim>
<para>
Now one can change the last line of the script to
</para>
<para>
これでスクリプトの末尾を以下のように書き換えられます
</para>
<verbatim><![CDATA[
print "side = $side\n";
]]></verbatim>
<para>
which outputs
</para>
<para>
以下のように出力されます
</para>
<verbatim><![CDATA[
side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
]]></verbatim>
<para>
and one can inspect the value in debugger using all the possible
methods.
</para>
<para>
そして全ての可能なメソッドを使ってデバッガで値を検査できます。
</para>
<para>
Something is is still amiss: consider the loop variable $cnt of the
script.  It was a number, not an object.  We cannot make this value of
type <code>symbolic</code>, since then the loop will not terminate.
</para>
<para>
まだ何かがおかしいです: スクリプトのループ変数 $cnt を考えてみます。
これは数値であり、オブジェクトではありません。
この値の型を <code>symbolic</code> にはできません; なぜならそうするとループが
終了しないからです。
</para>
<para>
Indeed, to terminate the cycle, the $cnt should become false.
However, the operator <code>bool</code> for checking falsity is overloaded (this
time via overloaded <code>&quot;&quot;</code>), and returns a long string, thus any object
of type <code>symbolic</code> is true.  To overcome this, we need a way to
compare an object to 0.  In fact, it is easier to write a numeric
conversion routine.
</para>
<para>
確かに、循環を終了させるために、$cnt は偽になる必要があります。
しかし、偽かどうかをチェックする演算子 <code>bool</code> が
(今回はオーバーロードされた <code>&quot;&quot;</code> 経由で) オーバーロードされていて、
長い文字列を返すので、型 <code>symbolic</code> のあらゆるオブジェクトは真です。
これを乗り越えるために、オブジェクトを 0 と比較する方法が必要です。
実際、これは数値変換ルーチンを書くより簡単です。
</para>
<para>
Here is the text of <filename>symbolic.pm</filename> with such a routine added (and
slightly modified str()):
</para>
<para>
以下はそのようなルーチンを追加した (そして str() を少し修正した)
<filename>symbolic.pm</filename> の内容です:
</para>
<verbatim><![CDATA[
package symbolic;		# Primitive symbolic calculator
use overload
  nomethod => \&wrap, '""' => \&str, '0+' => \&num;
]]></verbatim>
<verbatim><![CDATA[
sub new { shift; bless ['n', @_] }
sub wrap {
  my ($obj, $other, $inv, $meth) = @_;
  ($obj, $other) = ($other, $obj) if $inv;
  bless [$meth, $obj, $other];
}
sub str {
  my ($meth, $a, $b) = @{+shift};
  $a = 'u' unless defined $a;
  if (defined $b) {
    "[$meth $a $b]";
  } else {
    "[$meth $a]";
  }
}
my %subr = ( n => sub {$_[0]},
	       sqrt => sub {sqrt $_[0]},
	       '-' => sub {shift() - shift()},
	       '+' => sub {shift() + shift()},
	       '/' => sub {shift() / shift()},
	       '*' => sub {shift() * shift()},
	       '**' => sub {shift() ** shift()},
	     );
sub num {
  my ($meth, $a, $b) = @{+shift};
  my $subr = $subr{$meth}
    or die "Do not know how to ($meth) in symbolic";
  $a = $a->num if ref $a eq __PACKAGE__;
  $b = $b->num if ref $b eq __PACKAGE__;
  $subr->($a,$b);
}
]]></verbatim>
<para>
All the work of numeric conversion is done in %subr and num().  Of
course, %subr is not complete, it contains only operators used in the
example below.  Here is the extra-credit question: why do we need an
explicit recursion in num()?  (Answer is at the end of this section.)
</para>
<para>
全ての数値変換の作業は %subr と num() で行われます。
もちろん、%subr は不完全で、以下の例で使われる演算子のみを含んでいます。
これは追加点の質問です: なぜ num() で明示的な再帰が必要なのでしょう?
(答えはこの章の最後にあります。)
</para>
<para>
Use this module like this:
</para>
<para>
このモジュールは以下のようにして使います:
</para>
<verbatim><![CDATA[
require symbolic;
my $iter = new symbolic 2;	# 16-gon
my $side = new symbolic 1;
my $cnt = $iter;
]]></verbatim>
<verbatim><![CDATA[
while ($cnt) {
  $cnt = $cnt - 1;		# Mutator `--' not implemented
  $side = (sqrt(1 + $side**2) - 1)/$side;
}
printf "%s=%f\n", $side, $side;
printf "pi=%f\n", $side*(2**($iter+2));
]]></verbatim>
<para>
It prints (without so many line breaks)
</para>
<para>
これは(たくさんの改行を除くと)以下のものを表示します
</para>
<verbatim><![CDATA[
[/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
			  [n 1]] 2]]] 1]
   [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
pi=3.182598
]]></verbatim>
<para>
The above module is very primitive.  It does not implement
mutator methods (<code>++</code>, <code>-=</code> and so on), does not do deep copying
(not required without mutators!), and implements only those arithmetic
operations which are used in the example.
</para>
<para>
上述のモジュールはとても原始的なものです。
ミューテータメソッド (<code>++</code>, <code>-=</code> and so on) を実装していませんし、
ディープコピー(ミューテータがなければ不要です!)もできませんし、
例で使う算術演算しか実装していません。
</para>
<para>
To implement most arithmetic operations is easy; one should just use
the tables of operations, and change the code which fills %subr to
</para>
<para>
ほとんどの算術演算の実装は簡単です; 単に演算のテーブルを使って、
%subr を埋めているコードを以下のように変更するだけです
</para>
<verbatim><![CDATA[
my %subr = ( 'n' => sub {$_[0]} );
foreach my $op (split " ", $overload::ops{with_assign}) {
  $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
}
my @bins = qw(binary 3way_comparison num_comparison str_comparison);
foreach my $op (split " ", "@overload::ops{ @bins }") {
  $subr{$op} = eval "sub {shift() $op shift()}";
}
foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
  print "defining `$op'\n";
  $subr{$op} = eval "sub {$op shift()}";
}
]]></verbatim>
<para>
Due to <link xref='Calling Conventions for Mutators'>Calling Conventions for Mutators</link>, we do not need anything
special to make <code>+=</code> and friends work, except filling <code>+=</code> entry of
%subr, and defining a copy constructor (needed since Perl has no
way to know that the implementation of <code>'+='</code> does not mutate
the argument, compare <link xref='Copy Constructor'>Copy Constructor</link>).
</para>
<para>
<link xref='Calling Conventions for Mutators'>Calling Conventions for Mutators</link> によって、%subr の <code>+=</code> エントリを
埋めることと、コピーコンストラクタを定義すること (これは <code>'+='</code> の実装が
引数を変更しないことを Perl が知る方法はないために必要です;
<link xref='Copy Constructor'>Copy Constructor</link> と比較してください) のほかに、<code>+=</code> とその親類が
動作するために必要なことは何もありません。
</para>
<para>
To implement a copy constructor, add <code>'=' =&gt; \&amp;cpy</code> to <code>use overload</code>
line, and code (this code assumes that mutators change things one level
deep only, so recursive copying is not needed):
</para>
<para>
コピーコンストラクタを実行するには、<code>use overload</code> の行に
<code>'=' =&gt; \&amp;cpy</code> を追加して、以下のコードを書きます
(このコードは、ミューテータは 1 レベルの深さのみの変更を行うので、
再帰的コピーは不要であることを仮定しています):
</para>
<verbatim><![CDATA[
sub cpy {
  my $self = shift;
  bless [@$self], ref $self;
}
]]></verbatim>
<para>
To make <code>++</code> and <code>--</code> work, we need to implement actual mutators,
either directly, or in <code>nomethod</code>.  We continue to do things inside
<code>nomethod</code>, thus add
</para>
<para>
<code>++</code> と <code>--</code> が動作するようにするには、実際のミューテータを、
直接あるいは <code>nomethod</code> で実装する必要があります。
私達は物事を <code>nomethod</code> で続けると決めたので、以下を
</para>
<verbatim><![CDATA[
if ($meth eq '++' or $meth eq '--') {
  @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular referencen
  return $obj;
}
]]></verbatim>
<para>
after the first line of wrap().  This is not a most effective
implementation, one may consider
</para>
<para>
wrap() の最初の行の後に追加します。
これは最も効果的な実装というわけではないので、代わりに
</para>
<verbatim><![CDATA[
sub inc { $_[0] = bless ['++', shift, 1]; }
]]></verbatim>
<para>
instead.
</para>
<para>
とすることを考えるかもしれません。
</para>
<para>
As a final remark, note that one can fill %subr by
</para>
<para>
最後の意見として、以下のようなもので %subr を埋めることができることに
注意してください
</para>
<verbatim><![CDATA[
my %subr = ( 'n' => sub {$_[0]} );
foreach my $op (split " ", $overload::ops{with_assign}) {
  $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
}
my @bins = qw(binary 3way_comparison num_comparison str_comparison);
foreach my $op (split " ", "@overload::ops{ @bins }") {
  $subr{$op} = eval "sub {shift() $op shift()}";
}
foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
  $subr{$op} = eval "sub {$op shift()}";
}
$subr{'++'} = $subr{'+'};
$subr{'--'} = $subr{'-'};
]]></verbatim>
<para>
This finishes implementation of a primitive symbolic calculator in
50 lines of Perl code.  Since the numeric values of subexpressions
are not cached, the calculator is very slow.
</para>
<para>
これは、原始的なシンボリック計算機を 50 行の Perl コードで実装完了します。
部分式の数値はキャッシュされないので、計算機はとても遅いです。
</para>
<para>
Here is the answer for the exercise: In the case of str(), we need no
explicit recursion since the overloaded <code>.</code>-operator will fall back
to an existing overloaded operator <code>&quot;&quot;</code>.  Overloaded arithmetic
operators <emphasis>do not</emphasis> fall back to numeric conversion if <code>fallback</code> is
not explicitly requested.  Thus without an explicit recursion num()
would convert <code>['+', $a, $b]</code> to <code>$a + $b</code>, which would just rebuild
the argument of num().
</para>
<para>
これが課題の答えです: str() の場合、オーバーロードした <code>.</code> 演算子は
すでに存在するオーバーロードした演算子 <code>&quot;&quot;</code> にフォールバックするので、
明示的な再帰をする必要はありません。
オーバーロードした算術演算子は、明示的に <code>fallback</code> が要求されない限り
フォールバック <emphasis>しません</emphasis> 。
従って、明示的な再帰なしでは num() は <code>['+', $a, $b]</code> を <code>$a + $b</code> に
変換し、これは単に num() の引数を再ビルドします。
</para>
<para>
If you wonder why defaults for conversion are different for str() and
num(), note how easy it was to write the symbolic calculator.  This
simplicity is due to an appropriate choice of defaults.  One extra
note: due to the explicit recursion num() is more fragile than sym():
we need to explicitly check for the type of $a and $b.  If components
$a and $b happen to be of some related type, this may lead to problems.
</para>
<para>
もしなぜ str() と num() で変換のデフォルトが異なるかが不思議なら、
シンボリック計算機を書くのがどれだけ簡単だったかに注意してください。
この簡単さは適切なデフォルトの選択によるものです。
もう一つ追加の注意: 明示的な再帰によって、num() は sym() より壊れやすいです:
$a と $b の型を明示的にチェックする必要があります。
もし $a と $b がたまたま関係のある型の場合、これは問題を引き起こすかも
しれません。
</para>
</sect2>
<sect2>
<title><emphasis>Really</emphasis> symbolic calculator</title>
<para>
(<emphasis>本当に</emphasis> シンボリックな計算機)
</para>
<para>
One may wonder why we call the above calculator symbolic.  The reason
is that the actual calculation of the value of expression is postponed
until the value is <emphasis>used</emphasis>.
</para>
<para>
なぜ私達が上述の計算機をシンボリックと呼ぶのかを疑問に思う人も
いるかもしれません。
その理由は、式の値の実際の計算はその値が <emphasis>使われる</emphasis> まで延期されます。
</para>
<para>
To see it in action, add a method
</para>
<para>
実行中に見るために、以下のメソッドを
</para>
<verbatim><![CDATA[
sub STORE {
  my $obj = shift;
  $#$obj = 1;
  @$obj->[0,1] = ('=', shift);
}
]]></verbatim>
<para>
to the package <code>symbolic</code>.  After this change one can do
</para>
<para>
パッケージ <code>symbolic</code> に追加します。
この変更の後、以下のように出来て
</para>
<verbatim><![CDATA[
my $a = new symbolic 3;
my $b = new symbolic 4;
my $c = sqrt($a**2 + $b**2);
]]></verbatim>
<para>
and the numeric value of $c becomes 5.  However, after calling
</para>
<para>
$c の数値は 5 になります。
しかし、以下の呼出し後、
</para>
<verbatim><![CDATA[
$a->STORE(12);  $b->STORE(5);
]]></verbatim>
<para>
the numeric value of $c becomes 13.  There is no doubt now that the module
symbolic provides a <emphasis>symbolic</emphasis> calculator indeed.
</para>
<para>
$c の数値は 13 になります。
これでモジュール symbolic はまさに <emphasis>シンボリック</emphasis> 計算機を提供します。
</para>
<para>
To hide the rough edges under the hood, provide a tie()d interface to the
package <code>symbolic</code> (compare with <link xref='Metaphor clash'>Metaphor clash</link>).  Add methods
</para>
<para>
フードの中の荒いエッジを隠すために、パッケージ <code>symbolic</code> へ
tie() したインターフェースを提供します
(<link xref='Metaphor clash'>Metaphor clash</link> と比較してください)。
メソッドを追加します
</para>
<verbatim><![CDATA[
sub TIESCALAR { my $pack = shift; $pack->new(@_) }
sub FETCH { shift }
sub nop {  }		# Around a bug
]]></verbatim>
<para>
(the bug is described in <link xref='#BUGS'>&quot;BUGS&quot;</link>).  One can use this new interface as
</para>
<para>
(このバグは <link xref='#BUGS'>&quot;BUGS&quot;</link> に記述されています)。
この新しいインタフェースは以下のようにして使えます
</para>
<verbatim><![CDATA[
tie $a, 'symbolic', 3;
tie $b, 'symbolic', 4;
$a->nop;  $b->nop;	# Around a bug
]]></verbatim>
<verbatim><![CDATA[
my $c = sqrt($a**2 + $b**2);
]]></verbatim>
<para>
Now numeric value of $c is 5.  After <code>$a = 12; $b = 5</code> the numeric value
of $c becomes 13.  To insulate the user of the module add a method
</para>
<para>
ここで $c の数値は 5 です。
<code>$a = 12; $b = 5</code> の後、$c の数値は 13 になります。
モジュールのユーザーを分離す津ために、メソッドを追加します
</para>
<verbatim><![CDATA[
sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
]]></verbatim>
<para>
Now
</para>
<para>
ここで
</para>
<verbatim><![CDATA[
my ($a, $b);
symbolic->vars($a, $b);
my $c = sqrt($a**2 + $b**2);
]]></verbatim>
<verbatim><![CDATA[
$a = 3; $b = 4;
printf "c5  %s=%f\n", $c, $c;
]]></verbatim>
<verbatim><![CDATA[
$a = 12; $b = 5;
printf "c13  %s=%f\n", $c, $c;
]]></verbatim>
<para>
shows that the numeric value of $c follows changes to the values of $a
and $b.
</para>
<para>
とすると、$c の数値は $a と $b の値の変更に従います。
</para>
</sect2>
</sect1>
<sect1>
<title>AUTHOR</title>
<para>
Ilya Zakharevich &lt;<filename>ilya@math.mps.ohio-state.edu</filename>&gt;.
</para>
</sect1>
<sect1>
<title>DIAGNOSTICS</title>
<para>
When Perl is run with the <strong>-Do</strong> switch or its equivalent, overloading
induces diagnostic messages.
</para>
<para>
Perl を <strong>-Do</strong> スイッチか同等のものを使って起動すると、
オーバーロードによって診断メッセージを引き起こします。
</para>
<para>
Using the <code>m</code> command of Perl debugger (see <link xref='perldebug'>perldebug</link>) one can
deduce which operations are overloaded (and which ancestor triggers
this overloading). Say, if <code>eq</code> is overloaded, then the method <code>(eq</code>
is shown by debugger. The method <code>()</code> corresponds to the <code>fallback</code>
key (in fact a presence of this method shows that this package has
overloading enabled, and it is what is used by the <code>Overloaded</code>
function of module <code>overload</code>).
</para>
<para>
Perl デバッガの <code>m</code> コマンド (<link xref='perldebug'>perldebug</link> を参照してください) を
使うことで、どの演算がオーバーロードされているか (そしてどの祖先が
このオーバーロードを引き起こしているか) を推論することができます。
例えば、<code>eq</code> がオーバーロードされていると、メソッド <code>(eq</code> が
デバッガによって表示されます。
メソッド <code>()</code> は <code>fallback</code> キーに対応します
(実際このメソッドの存在は、このパッケージはオーバーロードが有効になっていて、
<code>overload</code> モジュールの <code>Overloaded</code> 関数で使われていることを
示しています)。
</para>
<para>
The module might issue the following warnings:
</para>
<para>
このモジュールは以下の警告を出すことがあります:
</para>
<list>
<item><itemtext>Odd number of arguments for overload::constant</itemtext>
<para>
(W) The call to overload::constant contained an odd number of arguments.
The arguments should come in pairs.
</para>
<para>
(W) 奇数の数の引数で overload::constant を呼び出しました。
引数はペアになっている必要があります。
</para>
</item>
<item><itemtext>`%s' is not an overloadable type</itemtext>
<para>
(W) You tried to overload a constant type the overload package is unaware of.
</para>
<para>
(W) オーバーロードパッケージが知らない定数型をオーバーロードしようとしました。
</para>
</item>
<item><itemtext>`%s' is not a code reference</itemtext>
<para>
(W) The second (fourth, sixth, ...) argument of overload::constant needs
to be a code reference. Either an anonymous subroutine, or a reference
to a subroutine.
</para>
<para>
(W) overload::constant の 2 番目 (4 番目、6 番目, ...) の引数はコード
リファレンスである必要があります。
無名サブルーチンか、サブルーチンへのリファレンスです。
</para>
</item>
</list>
</sect1>
<sect1>
<title>BUGS</title>
<para>
Because it is used for overloading, the per-package hash %OVERLOAD now
has a special meaning in Perl. The symbol table is filled with names
looking like line-noise.
</para>
<para>
オーバーロードに使用されるため、Perl では、ハッシュ %OVERLOAD は、
パッケージごとに特別な意味を持つことになります。
シンボルテーブルはごみのように見える名前で埋められます。
</para>
<para>
For the purpose of inheritance every overloaded package behaves as if
<code>fallback</code> is present (possibly undefined). This may create
interesting effects if some package is not overloaded, but inherits
from two overloaded packages.
</para>
<para>
継承の目的のために、全てのオーバーロードされたパッケージは
(未定義かもしれない) <code>fallback</code> が存在するかのように振る舞います。
これは、あるパッケージがオーバーロードしていないけれども、
2 つのオーバーロードしたパッケージを継承しているという場合に、
興味深い効果を作り出します。
</para>
<para>
Relation between overloading and tie()ing is broken.  Overloading is
triggered or not basing on the <emphasis>previous</emphasis> class of tie()d value.
</para>
<para>
オーバーロードと tie() の関係は壊れています。
オーバーロードは tie() された値の <emphasis>以前の</emphasis> クラスによって
引き起こされるかどうかが決まります。
</para>
<para>
This happens because the presence of overloading is checked too early,
before any tie()d access is attempted.  If the FETCH()ed class of the
tie()d value does not change, a simple workaround is to access the value
immediately after tie()ing, so that after this call the <emphasis>previous</emphasis> class
coincides with the current one.
</para>
<para>
これは、オーバーロードの存在のチェックが早すぎて、tie() したアクセスを
試みる前に行われるために起こります。
もし tie() された値の FETCH() されたクラスが変更していないなら、簡単な
回避法は tie() した直後に値にアクセスすることで、この呼び出しの後
<emphasis>以前の</emphasis> クラスは現在のものと同期します。
</para>
<para>
<strong>Needed:</strong> a way to fix this without a speed penalty.
</para>
<para>
<strong>必要:</strong> 速度に影響を与えることなくこれを修正する方法。
</para>
<para>
Barewords are not covered by overloaded string constants.
</para>
<para>
裸の単語はオーバーロードされた文字列定数の対象となりません。
</para>
<para>
This document is confusing.  There are grammos and misleading language
used in places.  It would seem a total rewrite is needed.
</para>
<para>
このドキュメントは混乱しています。あちこちに
誤解しやすい文章があります。完全な書き直しが必要です。
</para>
<para>
Translate: 吉村 寿人 &lt;JAE00534@niftyserve.or.jp&gt; (5.000)
Update: Kentaro Shirakata &lt;argrath@ub32.org&gt; (5.6.1-)
License: GPL or Artistic
</para>
</sect1>
</pod>
