<?xml version='1.0' encoding='utf-8'?>
<pod xmlns="http://axkit.org/ns/2000/pod2xml">
<head>
	<title>perlreftut - Mark's very short tutorial about references</title>
</head>
<sect1>
<title>perlreftut - Mark's very short tutorial about references</title>
<para>
perlreftut - Mark によるリファレンスに関するとても短いチュートリアル
</para>
</sect1>
<sect1>
<title>DESCRIPTION</title>
<para>
One of the most important new features in Perl 5 was the capability to
manage complicated data structures like multidimensional arrays and
nested hashes.  To enable these, Perl 5 introduced a feature called
`references', and using references is the key to managing complicated,
structured data in Perl.  Unfortunately, there's a lot of funny syntax
to learn, and the main manual page can be hard to follow.  The manual
is quite complete, and sometimes people find that a problem, because
it can be hard to tell what is important and what isn't.
</para>
<para>
Perl 5 における最も重要な新機能の一つは、多次元配列やネストした
ハッシュのような複雑なデータ構造を扱うことのできる能力です。
これらを可能とするために、Perl 5 は「リファレンス」と呼ばれる機能を導入し、
そしてリファレンスを使うことは、複雑で構造化されたデータをPerlで扱うことの
鍵です。
残念なことに、学ぶにはおかしな構文がたくさんあり、メインの
マニュアルページはフォローするのが難しい状態です。
マニュアルはほぼ完璧で、ときとして読者は何が重要で何が重要でないかを
説明するのが難しいので問題を見つけることがあります。
</para>
<para>
Fortunately, you only need to know 10% of what's in the main page to get
90% of the benefit.  This page will show you that 10%.
</para>
<para>
幸運にも、メインページにあることの 10% を知るだけで 90% の恩恵を
受けることができます。
このページではあなたにその 10% をお見せします。
</para>
</sect1>
<sect1>
<title>Who Needs Complicated Data Structures?</title>
<para>
(誰が複合データ構造を必要としているの?)
</para>
<para>
One problem that came up all the time in Perl 4 was how to represent a
hash whose values were lists.  Perl 4 had hashes, of course, but the
values had to be scalars; they couldn't be lists.
</para>
<para>
Perl 4 の時代にあった問題の一つが、リストの値を持ったハッシュの表現を
どのように行うかということでした。
Perl 4 はもちろんハッシュを持っていましたが、その値は
スカラでなければならず、リストを使うことはできませんでした。
</para>
<para>
Why would you want a hash of lists?  Let's take a simple example: You
have a file of city and country names, like this:
</para>
<para>
リストのハッシュをなぜ使いたいのでしょうか?
簡単な例で考えてみましょう:
あなたが以下のような都市と国の名前のファイルを持っていたとします:
</para>
<verbatim><![CDATA[
Chicago, USA
Frankfurt, Germany
Berlin, Germany
Washington, USA
Helsinki, Finland
New York, USA
]]></verbatim>
<para>
and you want to produce an output like this, with each country mentioned
once, and then an alphabetical list of the cities in that country:
</para>
<para>
そして、以下のように、国は一度だけ現れてその国の都市がアルファベット順に
現れるような出力を得たかったとします:
</para>
<verbatim><![CDATA[
Finland: Helsinki.
Germany: Berlin, Frankfurt.
USA:  Chicago, New York, Washington.
]]></verbatim>
<para>
The natural way to do this is to have a hash whose keys are country
names.  Associated with each country name key is a list of the cities in
that country.  Each time you read a line of input, split it into a country
and a city, look up the list of cities already known to be in that
country, and append the new city to the list.  When you're done reading
the input, iterate over the hash as usual, sorting each list of cities
before you print it out.
</para>
<para>
これを行う自然な方法は、キーが国の名前であるハッシュを使うことです。
国の名前はその国の都市のリストに関連付けられます。
入力を読むたびに国と都市に分割し、新たな都市をリストに追加します。
入力を読み終えたら通常通りハッシュをイテレートして、出力の前に都市の
各リストをソートしてやります。
</para>
<para>
If hash values can't be lists, you lose.  In Perl 4, hash values can't
be lists; they can only be strings.  You lose.  You'd probably have to
combine all the cities into a single string somehow, and then when
time came to write the output, you'd have to break the string into a
list, sort the list, and turn it back into a string.  This is messy
and error-prone.  And it's frustrating, because Perl already has
perfectly good lists that would solve the problem if only you could
use them.
</para>
<para>
もしハッシュの値がリストにできなければあなたの負けです。
Perl 4 では、ハッシュの値はリストにはできず、文字列だけが可能でした。
おそらくはすべての都市を一つの文字列に連結し、出力するときにその文字列を
リストに分解してからそのリストをソートして、その結果を再度文字列へ戻す
必要があるでしょう。
これはわかりにくくて、エラーを持ち込みやすいやり方です。
ハッシュの値をリストにできさえすれば、問題を解決できる完璧なリストを
すでに Perl は持っているので、これは不満がたまります。
</para>
</sect1>
<sect1>
<title>The Solution</title>
<para>
(解決法)
</para>
<para>
By the time Perl 5 rolled around, we were already stuck with this
design: Hash values must be scalars.  The solution to this is
references.
</para>
<para>
Perl 5 の時代でも、すでにこのデザインに困っていました: ハッシュの値は
スカラでなければならないのです。
これを解決するのがリファレンスです。
</para>
<para>
A reference is a scalar value that <emphasis>refers to</emphasis> an entire array or an
entire hash (or to just about anything else).  Names are one kind of
reference that you're already familiar with.  Think of the President
of the United States: a messy, inconvenient bag of blood and bones.
But to talk about him, or to represent him in a computer program, all
you need is the easy, convenient scalar string &quot;George Bush&quot;.
</para>
<para>
リファレンスは配列全体やハッシュ全体(もしくはそれ以外の何か)を <emphasis>参照する</emphasis>
スカラです。
名前はすでになじみの深いリファレンスの一種です。
アメリカ合衆国の大統領を考えてみましょう: 厄介で不自由な、血や骨の
入った袋です。
しかし、彼について語るときやコンピュータプログラムで彼を表すのために
必要なのは、簡単で、便利なスカラ文字列「George Bush」なのです。
</para>
<para>
References in Perl are like names for arrays and hashes.  They're
Perl's private, internal names, so you can be sure they're
unambiguous.  Unlike &quot;George Bush&quot;, a reference only refers to one
thing, and you always know what it refers to.  If you have a reference
to an array, you can recover the entire array from it.  If you have a
reference to a hash, you can recover the entire hash.  But the
reference is still an easy, compact scalar value.
</para>
<para>
Perl におけるリファレンスは配列やハッシュの名前に似ています。
それらは Perl のプライベートで内部的なな名前なので曖昧さがないことを
保証できます。
「George Bush」とは異なり、一つのリファレンスは一つのものしか参照しません。
配列全体を一つの名前でリカバーできます。
ハッシュへのリファレンスを持っていれば、ハッシュ全体をリカバーできます。
しかし、リファレンスは簡単で、コンパクトなスカラ値なのです。
</para>
<para>
You can't have a hash whose values are arrays; hash values can only be
scalars.  We're stuck with that.  But a single reference can refer to
an entire array, and references are scalars, so you can have a hash of
references to arrays, and it'll act a lot like a hash of arrays, and
it'll be just as useful as a hash of arrays.
</para>
<para>
あなたは値が配列であるハッシュを持つことはできません。
ハッシュの値はスカラのみ可能です。
わたしたちはそれに困っています。
しかし、一つのリファレンスは配列全体を参照することができ、リファレンスは
スカラなので、配列へのリファレンスのハッシュを持つことができます。
そしてそれは配列のハッシュのように振る舞い、配列のハッシュであるかのように
便利なのです。
</para>
<para>
We'll come back to this city-country problem later, after we've seen
some syntax for managing references.
</para>
<para>
この都市と国の問題にはリファレンスを扱うための幾つかの構文を見た後で
戻ります。
</para>
</sect1>
<sect1>
<title>Syntax</title>
<para>
(文法)
</para>
<para>
There are just two ways to make a reference, and just two ways to use
it once you have it.
</para>
<para>
リファレンスを作るには二つの方法があり、使うにも二つの方法があります。
</para>
<sect2>
<title>Making References</title>
<para>
(リファレンスを作る)
</para>
<sect3>
<title><strong>Make Rule 1</strong></title>
<para>
(<strong>作成ルール 1</strong>)
</para>
<para>
If you put a <code>\</code> in front of a variable, you get a
reference to that variable.
</para>
<para>
ある変数の先頭に <code>\</code> をつければ、その変数へのリファレンスを
得ることができます。
</para>
<verbatim><![CDATA[
$aref = \@array;         # $aref now holds a reference to @array
$href = \%hash;          # $href now holds a reference to %hash
$sref = \$scalar;        # $sref now holds a reference to $scalar
]]></verbatim>
<verbatim><![CDATA[
$aref = \@array;         # $aref は @array へのリファレンスを保持する
$href = \%hash;          # $href は %hash へのリファレンスを保持する
$sref = \$scalar;        # $sref は $scalar へのリファレンスを保持する
]]></verbatim>
<para>
Once the reference is stored in a variable like $aref or $href, you
can copy it or store it just the same as any other scalar value:
</para>
<para>
$aref や $href のような変数にリファレンスを格納指定しまえば、
スカラ変数のようにコピーしたり格納することができます:
</para>
<verbatim><![CDATA[
$xy = $aref;             # $xy now holds a reference to @array
$p[3] = $href;           # $p[3] now holds a reference to %hash
$z = $p[3];              # $z now holds a reference to %hash
]]></verbatim>
<verbatim><![CDATA[
$xy = $aref;             # $xy は @array へのリファレンスを保持する
$p[3] = $href;           # $p[3] は %hash へのリファレンスを保持する
$z = $p[3];              # $z は %hash へのリファレンスを保持する
]]></verbatim>
<para>
These examples show how to make references to variables with names.
Sometimes you want to make an array or a hash that doesn't have a
name.  This is analogous to the way you like to be able to use the
string <code>&quot;\n&quot;</code> or the number 80 without having to store it in a named
variable first.
</para>
<para>
これらの例は、名前を使って変数へのリファレンスを作る方法を
例示するものでした。
ときとして、名前を持っていない配列やハッシュを作りたいときが
あるかもしれません。
これは、文字列 <code>&quot;\n&quot;</code> や、数値 80 を、一旦名前付き変数に保管する
必要なしに使えるようにする方法と似ています。
</para>
<para>
<strong>Make Rule 2</strong>
</para>
</sect3>
<sect3>
<title><strong>Make Rule 2</strong></title>
<para>
(<strong>作成ルール 2</strong>)
</para>
<para>
<code>[ ITEMS ]</code> makes a new, anonymous array, and returns a reference to
that array.  <code>{ ITEMS }</code> makes a new, anonymous hash, and returns a
reference to that hash.
</para>
<para>
<code>[ ITEMS ]</code> は新たな無名配列を作り、その配列へのリファレンスを返します。
<code>{ ITEMS }</code> は新たな無名ハッシュを作り、そのハッシュへのリファレンスを
返します。
</para>
<verbatim><![CDATA[
$aref = [ 1, "foo", undef, 13 ];
# $aref now holds a reference to an array
]]></verbatim>
<verbatim><![CDATA[
$aref = [ 1, "foo", undef, 13 ];  
# $aref は配列へのリファレンスを保持している
]]></verbatim>
<verbatim><![CDATA[
$href = { APR => 4, AUG => 8 };
# $href now holds a reference to a hash
]]></verbatim>
<verbatim><![CDATA[
$href = { APR => 4, AUG => 8 };   
# $href はハッシュへのリファレンスを保持している
]]></verbatim>
<para>
The references you get from rule 2 are the same kind of
references that you get from rule 1:
</para>
<para>
ルール 2 によって得たリファレンスはルール 1 によって得た同種の
リファレンスと同じです:
</para>
<verbatim><![CDATA[
# This:
$aref = [ 1, 2, 3 ];
]]></verbatim>
<verbatim><![CDATA[
# これは:
$aref = [ 1, 2, 3 ];
]]></verbatim>
<verbatim><![CDATA[
# Does the same as this:
@array = (1, 2, 3);
$aref = \@array;
]]></verbatim>
<verbatim><![CDATA[
# これと同じ:
@array = (1, 2, 3);
$aref = \@array;
]]></verbatim>
<para>
The first line is an abbreviation for the following two lines, except
that it doesn't create the superfluous array variable <code>@array</code>.
</para>
<para>
最初の行は続く二行を短くしたもので、<code>@array</code> という余分な配列変数を
作りません。
</para>
<para>
If you write just <code>[]</code>, you get a new, empty anonymous array.
If you write just <code>{}</code>, you get a new, empty anonymous hash.
</para>
<para>
<code>[]</code> と書いた場合には新たな空の無名配列が得られます。
<code>{}</code> と書いた場合には新たな空の無名ハッシュが得られます。
</para>
</sect3>
</sect2>
<sect2>
<title>Using References</title>
<para>
(リファレンスを使う)
</para>
<para>
What can you do with a reference once you have it?  It's a scalar
value, and we've seen that you can store it as a scalar and get it back
again just like any scalar.  There are just two more ways to use it:
</para>
<para>
リファレンスを得た後でそれに対してできることは?
リファレンスはスカラ値であり、スカラであるかのように格納したり
値を得たりできることを見てきました。
リファレンスを使うには他に二つの方法があります。
</para>
<sect3>
<title><strong>Use Rule 1</strong></title>
<para>
(<strong>使用ルール 1</strong>)
</para>
<para>
You can always use an array reference, in curly braces, in place of
the name of an array.  For example, <code>@{$aref}</code> instead of <code>@array</code>.
</para>
<para>
配列のリファレンスを、配列の名前が置かれる場所でカーリーブレースの中で
使うことができます。
たとえば、<code>@array</code> の代わりに <code>@{$aref}</code> とします。
</para>
<para>
Here are some examples of that:
</para>
<para>
以下に例を挙げます:
</para>
<para>
Arrays:
</para>
<para>
配列:
</para>
<verbatim><![CDATA[
@a		@{$aref}		An array
reverse @a	reverse @{$aref}	Reverse the array
$a[3]		${$aref}[3]		An element of the array
$a[3] = 17;	${$aref}[3] = 17	Assigning an element
]]></verbatim>
<verbatim><![CDATA[
@a		@{$aref}		配列
reverse @a	reverse @{$aref}	配列を反転する
$a[3]		${$aref}[3]		配列の要素
$a[3] = 17;	${$aref}[3] = 17	要素の代入
]]></verbatim>
<para>
On each line are two expressions that do the same thing.  The
left-hand versions operate on the array <code>@a</code>.  The right-hand
versions operate on the array that is referred to by <code>$aref</code>.  Once
they find the array they're operating on, both versions do the same
things to the arrays.
</para>
<para>
各行の二つの式は同じことを行います。
左側のものは <code>@a</code> という配列に対する操作で、右側のものは <code>$aref</code> によって
参照される配列に対する操作です。
操作される配列を見つければ、両方のバージョンは配列に対して同じことを
行います。
</para>
<para>
Using a hash reference is <emphasis>exactly</emphasis> the same:
</para>
<para>
ハッシュのリファレンスを使うことも <emphasis>まったく</emphasis> 同じです:
</para>
<verbatim><![CDATA[
%h		%{$href}	      A hash
keys %h		keys %{$href}	      Get the keys from the hash
$h{'red'}	${$href}{'red'}	      An element of the hash
$h{'red'} = 17	${$href}{'red'} = 17  Assigning an element
]]></verbatim>
<verbatim><![CDATA[
%h		%{$href}	      ハッシュ
keys %h		keys %{$href}	      ハッシュからキーを得る
$h{'red'}	${$href}{'red'}       ハッシュの要素
$h{'red'} = 17	${$href}{'red'} = 17  要素への代入
]]></verbatim>
<para>
Whatever you want to do with a reference, <strong>Use Rule 1</strong> tells you how
to do it.  You just write the Perl code that you would have written
for doing the same thing to a regular array or hash, and then replace
the array or hash name with <code>{$reference}</code>.  &quot;How do I loop over an
array when all I have is a reference?&quot;  Well, to loop over an array, you
would write
</para>
<para>
リファレンスに対して行いたいことはすべて、<link xref='Use Rule 1'>Use Rule 1</link> で
どのように行うかが説明されています。
通常の配列やハッシュに対して同じことを行うような Perl コードを書き、その
配列やハッシュをリファレンス <code>{$reference}</code> で置き換えるのです。
「私が持っているのがリファレンスであるとき、配列に対してループするには?」
そう、配列に対してループするには次のように書くでしょう
</para>
<verbatim><![CDATA[
for my $element (@array) {
   ...
}
]]></verbatim>
<para>
so replace the array name, <code>@array</code>, with the reference:
</para>
<para>
そしてこの配列名 <code>@array</code> をリファレンスで置き換えます:
</para>
<verbatim><![CDATA[
for my $element (@{$aref}) {
   ...
}
]]></verbatim>
<para>
&quot;How do I print out the contents of a hash when all I have is a
reference?&quot;  First write the code for printing out a hash:
</para>
<para>
「私が持っているのがリファレンスであるとき、ハッシュの内容を出力するには?」
まずはじめにハッシュを出力するコードを書きます:
</para>
<verbatim><![CDATA[
for my $key (keys %hash) {
  print "$key => $hash{$key}\n";
}
]]></verbatim>
<para>
And then replace the hash name with the reference:
</para>
<para>
そしてハッシュの名前をリファレンスで置き換えます:
</para>
<verbatim><![CDATA[
for my $key (keys %{$href}) {
  print "$key => ${$href}{$key}\n";
}
]]></verbatim>
</sect3>
<sect3>
<title><strong>Use Rule 2</strong></title>
<para>
(<strong>使用ルール 2</strong>)
</para>
<para>
<strong>Use Rule 1</strong> is all you really need, because it tells you how to do
absolutely everything you ever need to do with references.  But the
most common thing to do with an array or a hash is to extract a single
element, and the <strong>Use Rule 1</strong> notation is cumbersome.  So there is an
abbreviation.
</para>
<para>
<link xref='Use Rule 1'>Use Rule 1</link> はあなたが実際に必要とするすべてです。
なぜなら、リファレンスについて必要となることすべてを説明しているからです。
しかし、配列やハッシュについて行いたいことの大部分は一つの要素を
取り出すことで、<link xref='Use Rule 1'>Use Rule 1</link> の記法は扱いにくいものです。
そのため、略記法があります。
</para>
<para>
<code>${$aref}[3]</code> is too hard to read, so you can write <code>$aref-&gt;[3]</code>
instead.
</para>
<para>
<code>${$aref}[3]</code> は読みづらいので、代わりに <code>$aref-&gt;[3]</code> と書くことが
できます。
</para>
<para>
<code>${$href}{red}</code> is too hard to read, so you can write
<code>$href-&gt;{red}</code> instead.
</para>
<para>
<code>${$href}{red}</code> は読みづらいので、代わりに <code>$href-&gt;{red}</code> と
書くことができます。
</para>
<para>
If <code>$aref</code> holds a reference to an array, then <code>$aref-&gt;[3]</code> is
the fourth element of the array.  Don't confuse this with <code>$aref[3]</code>,
which is the fourth element of a totally different array, one
deceptively named <code>@aref</code>.  <code>$aref</code> and <code>@aref</code> are unrelated the
same way that <code>$item</code> and <code>@item</code> are.
</para>
<para>
<code>$aref</code> が配列へのリファレンスを保持しているとき、<code>$aref-&gt;[3]</code> は
その配列の四番目の要素です。
これと <code>$aref[3]</code> を混同しないでください。
後者は <code>@aref</code> という名前のついた配列の四番目の要素です。
<code>$aref</code> と <code>@aref</code> は、<code>$item</code> と <code>@item</code> がそうであるように
無関係なものです。
</para>
<para>
Similarly, <code>$href-&gt;{'red'}</code> is part of the hash referred to by
the scalar variable <code>$href</code>, perhaps even one with no name.
<code>$href{'red'}</code> is part of the deceptively named <code>%href</code> hash.  It's
easy to forget to leave out the <code>-&gt;</code>, and if you do, you'll get
bizarre results when your program gets array and hash elements out of
totally unexpected hashes and arrays that weren't the ones you wanted
to use.
</para>
<para>
同様に、<code>$href-&gt;{'red'}</code> はスカラ変数 <code>$href</code> によって参照される
ハッシュ(おそらくは名前のないもの)の一部分です。
<code>$href{'red'}</code> は <code>%href</code> という名前のついたハッシュの一部です。
<code>-&gt;</code> はつけ忘れやすく、もしつけ忘れたならばあなたのプログラムが配列や
ハッシュの要素を取り出そうとしたときに、予期していないハッシュや配列を
アクセスしたことによる奇妙な結果を得ることになるでしょう。
</para>
</sect3>
</sect2>
<sect2>
<title>An Example</title>
<para>
(例)
</para>
<para>
Let's see a quick example of how all this is useful.
</para>
<para>
これがどんなに便利なことかを例を挙げてみてみましょう。
</para>
<para>
First, remember that <code>[1, 2, 3]</code> makes an anonymous array containing
<code>(1, 2, 3)</code>, and gives you a reference to that array.
</para>
<para>
まずはじめに、<code>[1, 2, 3]</code> が <code>(1, 2, 3)</code> から構成される無名配列を
作り出し、その配列に対するリファレンスを与えることを思い出してください。
</para>
<para>
Now think about
</para>
<para>
ここで以下について考えます
</para>
<verbatim><![CDATA[
@a = ( [1, 2, 3],
               [4, 5, 6],
       [7, 8, 9]
             );
]]></verbatim>
<para>
@a is an array with three elements, and each one is a reference to
another array.
</para>
<para>
@aは三つの要素をもつ配列で、その要素はそれぞれ別の配列に対する
リファレンスです。
</para>
<para>
<code>$a[1]</code> is one of these references.  It refers to an array, the array
containing <code>(4, 5, 6)</code>, and because it is a reference to an array,
<strong>Use Rule 2</strong> says that we can write <code>$a[1]-&gt;[2]</code> to get the
third element from that array.  <code>$a[1]-&gt;[2]</code> is the 6.
Similarly, <code>$a[0]-&gt;[1]</code> is the 2.  What we have here is like a
two-dimensional array; you can write <code>$a[ROW]-&gt;[COLUMN]</code> to get
or set the element in any row and any column of the array.
</para>
<para>
<code>$a[1]</code> はそのようなリファレンスの一つです。
これは <code>(4,5,6)</code> からなる配列を参照します。
これは配列へのリファレンスで、<link xref='Use Rule 2'>Use Rule 2</link> はそのような配列の第三要素を
得るために <code>$a[1]-&gt;[2]</code> と書けることを述べていたので、
<code>$a[1]-&gt;[2]</code> は 6 になります。
同様に、<code>$a[0]-&gt;[1]</code> は 2 です。
ここで私たちが得たものは二次元配列のようなものです;
配列の任意の行の任意の列にある要素を得たり、それにセットしたりするのに
<code>$a[ROW]-&gt;[COLUMN]</code> と書くことができます。
</para>
<para>
The notation still looks a little cumbersome, so there's one more
abbreviation:
</para>
<para>
この記法はまだ少々扱いにくいものなので、略記法があります:
</para>
</sect2>
<sect2>
<title>Arrow Rule</title>
<para>
(矢印のルール)
</para>
<para>
In between two <strong>subscripts</strong>, the arrow is optional.
</para>
<para>
矢印は、二つの <strong>添え字</strong> の間にあるのなら、省略できます。
</para>
<para>
Instead of <code>$a[1]-&gt;[2]</code>, we can write <code>$a[1][2]</code>; it means the
same thing.  Instead of <code>$a[0]-&gt;[1] = 23</code>, we can write
<code>$a[0][1] = 23</code>; it means the same thing.
</para>
<para>
<code>$a[1]-&gt;[2]</code> は <code>$a[1][2]</code> と書くことができます;
これらは同じことを意味します。
<code>$a[0]-&gt;[1] = 23</code> と書く代わりに <code>$a[0][1] = 23</code> とできます。
これらは同じことです。
</para>
<para>
Now it really looks like two-dimensional arrays!
</para>
<para>
これで本当に二次元配列らしくなりました!
</para>
<para>
You can see why the arrows are important.  Without them, we would have
had to write <code>${$a[1]}[2]</code> instead of <code>$a[1][2]</code>.  For
three-dimensional arrays, they let us write <code>$x[2][3][5]</code> instead of
the unreadable <code>${${$x[2]}[3]}[5]</code>.
</para>
<para>
矢印が重要なことがこれでわかります。
もし矢印がなければ、<code>$a[1][2]</code> の代わりに <code>${$a[1]}[2]</code> と
書かなければなりません。
三次元配列では、<code>${${$x[2]}[3]}[5]</code> のような読みづらいものではなくて
<code>$x[2][3][5]</code> とできます。
</para>
</sect2>
</sect1>
<sect1>
<title>Solution</title>
<para>
(答え)
</para>
<para>
Here's the answer to the problem I posed earlier, of reformatting a
file of city and country names.
</para>
<para>
以下は先に保留していた問題に対する解答です。
都市と国の名前のファイルの再フォーマットを行うものです。
</para>
<verbatim><![CDATA[
1   my %table;
]]></verbatim>
<verbatim><![CDATA[
2   while (<>) {
3    chomp;
4     my ($city, $country) = split /, /;
5     $table{$country} = [] unless exists $table{$country};
6     push @{$table{$country}}, $city;
7   }
]]></verbatim>
<verbatim><![CDATA[
8   foreach $country (sort keys %table) {
9     print "$country: ";
   10     my @cities = @{$table{$country}};
   11     print join ', ', sort @cities;
   12     print ".\n";
   13	}
]]></verbatim>
<para>
The program has two pieces: Lines 2--7 read the input and build a data
structure, and lines 8-13 analyze the data and print out the report.
We're going to have a hash, <code>%table</code>, whose keys are country names,
and whose values are references to arrays of city names.  The data
structure will look like this:
</para>
<para>
プログラムは二つの部分から構成されています: 2 行目から 7 行目は入力を
読み込んでデータ構造を構築します。
そして 8 行目から 13 行目でデータを解析して結果を出力します。
わたしたちはここで、キーとして国の名前を持ち、値として都市名のリストへの
リファレンスを持つハッシュ <code>%table</code> を作ろうとしています。
データ構造は以下のようなものです:
</para>
<verbatim><![CDATA[
%table
        +-------+---+
        |       |   |   +-----------+--------+
        |Germany| *---->| Frankfurt | Berlin |
        |       |   |   +-----------+--------+
        +-------+---+
        |       |   |   +----------+
        |Finland| *---->| Helsinki |
        |       |   |   +----------+
        +-------+---+
        |       |   |   +---------+------------+----------+
        |  USA  | *---->| Chicago | Washington | New York |
        |       |   |   +---------+------------+----------+
        +-------+---+
]]></verbatim>
<para>
We'll look at output first.  Supposing we already have this structure,
how do we print it out?
</para>
<para>
最初に出力を見ましょう。
ここで、すでに上記の構造ができているとします。
どのように出力するのでしょうか?
</para>
<verbatim><![CDATA[
8   foreach $country (sort keys %table) {
9     print "$country: ";
   10     my @cities = @{$table{$country}};
   11     print join ', ', sort @cities;
   12     print ".\n";
   13	}
]]></verbatim>
<para>
<code>%table</code> is an
ordinary hash, and we get a list of keys from it, sort the keys, and
loop over the keys as usual.  The only use of references is in line 10.
<code>$table{$country}</code> looks up the key <code>$country</code> in the hash
and gets the value, which is a reference to an array of cities in that country.
<strong>Use Rule 1</strong> says that
we can recover the array by saying
<code>@{$table{$country}}</code>.  Line 10 is just like
</para>
<para>
<code>%table</code> は通常のハッシュで、そこからキーのリストを得てそれをソートして
通常通りキーに対してループします。
リファレンスは 10 行目でだけ使われています。
<code>$table{$country}</code> はハッシュの <code>$country</code> キーを参照します。
これはその国の都市の配列に対するリファレンスです。
<link xref='Use Rule 1'>Use Rule 1</link> は配列を <code>@{$table{$country}}</code> で取り出せるといっています。
10行目は
</para>
<verbatim><![CDATA[
@cities = @array;
]]></verbatim>
<para>
except that the name <code>array</code> has been replaced by the reference
<code>{$table{$country}}</code>.  The <code>@</code> tells Perl to get the entire array.
Having gotten the list of cities, we sort it, join it, and print it
out as usual.
</para>
<para>
と同じようなものですが、<code>array</code> という名前が <code>{$table{$country}}</code> という
リファレンスに置き換えられています。
<code>@</code> は Perl に配列全体を取り出すことを指示しています。
都市のリストを得たらそれをソートして、つなげ、そして通常と同じように
出力します。
</para>
<para>
Lines 2-7 are responsible for building the structure in the first
place.  Here they are again:
</para>
<para>
2 行目から 7 行目は構造を構築している部分です。
再掲します:
</para>
<verbatim><![CDATA[
2   while (<>) {
3    chomp;
4     my ($city, $country) = split /, /;
5     $table{$country} = [] unless exists $table{$country};
6     push @{$table{$country}}, $city;
7   }
]]></verbatim>
<para>
Lines 2-4 acquire a city and country name.  Line 5 looks to see if the
country is already present as a key in the hash.  If it's not, the
program uses the <code>[]</code> notation (<strong>Make Rule 2</strong>) to manufacture a new,
empty anonymous array of cities, and installs a reference to it into
the hash under the appropriate key.
</para>
<para>
2 行目から 4 行目は都市と国の名前を得ています。
5p行目はその国がすでにハッシュのキーとして存在しているかどうかを見ています。
もし存在していなければ、プログラムは[]記法(<link xref='Make Rule 2'>Make Rule 2</link>)を使って新しい
空の都市が格納される無名配列を作り出します。
そして、リファレンスを配列の適切なキーにセットします。
</para>
<para>
Line 6 installs the city name into the appropriate array.
<code>$table{$country}</code> now holds a reference to the array of cities seen
in that country so far.  Line 6 is exactly like
</para>
<para>
6行目は都市名を対応する配列にインストールします。
<code>$table{$country}</code> はここでその国の都市の配列に対するリファレンスを
保持しています。
6 行目は
</para>
<verbatim><![CDATA[
push @array, $city;
]]></verbatim>
<para>
except that the name <code>array</code> has been replaced by the reference
<code>{$table{$country}}</code>.  The <code>push</code> adds a city name to the end of the
referred-to array.
</para>
<para>
のようなものですが、異なるのは <code>array</code> が <code>{$table{$country}}</code> という
リファレンスに置き換わっている点です。
<code>push</code> は都市名を参照されている配列の末尾に追加します。
</para>
<para>
There's one fine point I skipped.  Line 5 is unnecessary, and we can
get rid of it.
</para>
<para>
スキップした点があります。
5 行目は不必要なので、取り除くことができます。
</para>
<verbatim><![CDATA[
2   while (<>) {
3    chomp;
4     my ($city, $country) = split /, /;
5   ####  $table{$country} = [] unless exists $table{$country};
6     push @{$table{$country}}, $city;
7   }
]]></verbatim>
<para>
If there's already an entry in <code>%table</code> for the current <code>$country</code>,
then nothing is different.  Line 6 will locate the value in
<code>$table{$country}</code>, which is a reference to an array, and push
<code>$city</code> into the array.  But
what does it do when
<code>$country</code> holds a key, say <code>Greece</code>, that is not yet in <code>%table</code>?
</para>
<para>
<code>%table</code> の中に現在の <code>$country</code> のためのエントリがすでに存在していれば
異なる点はありません。
6 行目は配列へのリファレンスである <code>$table{$country}</code> の値に注目し、
その配列に <code>$city</code> をプッシュします。
しかし、<code>$country</code> が <code>%table</code> の中にない <code>Greece</code> のようなキーを
保持していたら何をするのでしょうか?
</para>
<para>
This is Perl, so it does the exact right thing.  It sees that you want
to push <code>Athens</code> onto an array that doesn't exist, so it helpfully
makes a new, empty, anonymous array for you, installs it into
<code>%table</code>, and then pushes <code>Athens</code> onto it.  This is called
`autovivification'--bringing things to life automatically.  Perl saw
that they key wasn't in the hash, so it created a new hash entry
automatically. Perl saw that you wanted to use the hash value as an
array, so it created a new empty array and installed a reference to it
in the hash automatically.  And as usual, Perl made the array one
element longer to hold the new city name.
</para>
<para>
これは Perl です; ですから、本当に正しいことを行います。
存在していない配列に Athens をプッシュしようとするので、新しく空の
無名配列をあなたのために作り出してそれを <code>%table</code> にインストールします。
そしてそれから <code>Athens</code> をそこにプッシュします。
これは `autovivification' と呼ばれます。
Perl はハッシュの中にそれらのキーが存在しないことを確認し、新しいハッシュ
エントリを自動的に作り出します。
Perl はあなたがハッシュの値を配列として扱いたがっていることを
知っているので、新しい空の配列を作り出してハッシュの中にそれに対する
リファレンスを自動的にインストールします。
いつもと同じように、Perlは新たな都市名を保持する一要素の配列を
作り出します。
</para>
</sect1>
<sect1>
<title>The Rest</title>
<para>
(残り)
</para>
<para>
I promised to give you 90% of the benefit with 10% of the details, and
that means I left out 90% of the details.  Now that you have an
overview of the important parts, it should be easier to read the
<link xref='perlref'>perlref</link> manual page, which discusses 100% of the details.
</para>
<para>
わたしはあなたに 10% の詳細で 90% の利益を得ることを約束しました。
そしてそれは詳細の 90% をそのままにしているということです。
今、あなたは重要な部分を見てきました。
それにより詳細の100% を述べている <link xref='perlref'>perlref</link> man ページをより簡単に
読むことができるようになったでしょう。
</para>
<para>
Some of the highlights of <link xref='perlref'>perlref</link>:
</para>
<para>
<link xref='perlref'>perlref</link> のハイライトの幾つかを挙げておきます:
</para>
<list>
<item><para>
You can make references to anything, including scalars, functions, and
other references.
</para>
<para>
任意のものに対するリファレンスを作成することができます。
そこにはスカラ、関数、他のリファレンスも含まれます。
</para>
</item>
<item><para>
In <strong>Use Rule 1</strong>, you can omit the curly brackets whenever the thing
inside them is an atomic scalar variable like <code>$aref</code>.  For example,
<code>@$aref</code> is the same as <code>@{$aref}</code>, and <code>$$aref[1]</code> is the same as
<code>${$aref}[1]</code>.  If you're just starting out, you may want to adopt
the habit of always including the curly brackets.
</para>
<para>
<link xref='Use Rule 1'>Use Rule 1</link> の中で、その中にあるものが <code>$aref</code> のようなアトミックな
スカラ変数である場合にはカーリーブラケットを省略することができます。
たとえば、<code>@$aref</code> は <code>@{$aref}</code> と同じで、<code>$$aref[1]</code> は
<code>${$aref}[1]</code> と同じです。
始めたばかりなのであれば、常にカーリーブラケットで囲むことを
習慣付けたくなるかもしれません。
</para>
</item>
<item><para>
This doesn't copy the underlying array:
</para>
<para>
以下は配列の内容をコピーしません:
</para>
<verbatim><![CDATA[
$aref2 = $aref1;
]]></verbatim>
<para>
You get two references to the same array.  If you modify
<code>$aref1-&gt;[23]</code> and then look at
<code>$aref2-&gt;[23]</code> you'll see the change.
</para>
<para>
同じ配列に対する二つのリファレンスが得られます。
もし <code>$aref1-&gt;[23]</code> を変更して、<code>$aref2-&gt;[23]</code> を
参照したならば変更したものが見えるでしょう。
</para>
<para>
To copy the array, use
</para>
<para>
配列をコピーするには以下のようにします
</para>
<verbatim><![CDATA[
$aref2 = [@{$aref1}];
]]></verbatim>
<para>
This uses <code>[...]</code> notation to create a new anonymous array, and
<code>$aref2</code> is assigned a reference to the new array.  The new array is
initialized with the contents of the array referred to by <code>$aref1</code>.
</para>
<para>
これは新たな無名配列を作り出すために <code>[...]</code> 記法を使っています。
そして、<code>$aref2</code> は新たな配列に対するリファレンスが代入されます。
新たな配列は <code>$aref1</code> によって参照される配列の内容によって初期化されます。
</para>
<para>
Similarly, to copy an anonymous hash, you can use
</para>
<para>
同様に、無名ハッシュをコピーするには以下のようにします
</para>
<verbatim><![CDATA[
$href2 = {%{$href1}};
]]></verbatim>
</item>
<item><para>
To see if a variable contains a reference, use the <code>ref</code> function.  It
returns true if its argument is a reference.  Actually it's a little
better than that: It returns <code>HASH</code> for hash references and <code>ARRAY</code>
for array references.
</para>
<para>
配列がリファレンスを保持しているときにそれを確認するには、<code>ref</code> 関数を
使います。
この関数はその引数がリファレンスであるときには真を返します。
実際にはもうちょっと良くて、ハッシュリファレンスであれば <code>HASH</code> を、
配列リファレンスであれば <code>ARRAY</code> を返します。
</para>
</item>
<item><para>
If you try to use a reference like a string, you get strings like
</para>
<para>
リファレンスを文字列のように使った場合には、以下のような文字列が得られます
</para>
<verbatim><![CDATA[
ARRAY(0x80f5dec)   or    HASH(0x826afc0)
]]></verbatim>
<para>
If you ever see a string that looks like this, you'll know you
printed out a reference by mistake.
</para>
<para>
もしこのような文字列を見たならば、リファレンスを間違って出力したことを
知ることとなるでしょう。
</para>
<para>
A side effect of this representation is that you can use <code>eq</code> to see
if two references refer to the same thing.  (But you should usually use
<code>==</code> instead because it's much faster.)
</para>
<para>
この表現の副作用は、<code>eq</code> を二つのリファレンスが同じものを
参照しているかどうかを確認するために使うことができるということです
(しかし、通常はより早い <code>==</code> を代わりに使うべきでしょう)。
</para>
</item>
<item><para>
You can use a string as if it were a reference.  If you use the string
<code>&quot;foo&quot;</code> as an array reference, it's taken to be a reference to the
array <code>@foo</code>.  This is called a <emphasis>soft reference</emphasis> or <emphasis>symbolic
reference</emphasis>.  The declaration <code>use strict 'refs'</code> disables this
feature, which can cause all sorts of trouble if you use it by accident.
</para>
<para>
文字列をリファレンスであるかのように使うことができます。
文字列 <code>&quot;foo&quot;</code> を配列リファレンスとして使うとき、<code>@foo</code> への
参照であるかのように受け付けられます。
これは <emphasis>ソフトリファレンス</emphasis> または <emphasis>シンボリックリファレンス</emphasis> と
呼ばれます。
<code>use strict 'refs'</code> と宣言することによって、アクシデントによって問題が
引き起こされる場合があるこの機能を禁止することができます。
</para>
</item>
</list>
<para>
You might prefer to go on to <link xref='perllol'>perllol</link> instead of <link xref='perlref'>perlref</link>; it
discusses lists of lists and multidimensional arrays in detail.  After
that, you should move on to <link xref='perldsc'>perldsc</link>; it's a Data Structure Cookbook
that shows recipes for using and printing out arrays of hashes, hashes
of arrays, and other kinds of data.
</para>
<para>
<link xref='perlref'>perlref</link> よりも <link xref='perllol'>perllol</link> に行きたいと思うかもしれません。
そこではリストのリストや多次元配列について詳しく述べられています。
その後で、<link xref='perldsc'>perldsc</link> に行くと良いでしょう。
これはデータ構造クックブック(Data Structure Cookbook)で、ハッシュの配列、
配列のハッシュ、その他のデータの使用や出力についてのレシピがあります。
</para>
</sect1>
<sect1>
<title>Summary</title>
<para>
(まとめ)
</para>
<para>
Everyone needs compound data structures, and in Perl the way you get
them is with references.  There are four important rules for managing
references: Two for making references and two for using them.  Once
you know these rules you can do most of the important things you need
to do with references.
</para>
<para>
すべての人が複合データ構造を必要としていて、Perlでのそれを得るやり方は
リファレンスです。
リファレンスを扱うにあたって四つの重要なルールがあります: 二つは
リファレンスの作成についてで、二つはリファレンスの使用についてです。
これらのルールを知ってしまえば、あなたがリファレンスを使って行う必要が
あることの重要な部分のほとんどを行うことができます。
</para>
</sect1>
<sect1>
<title>Credits</title>
<para>
Author: Mark Jason Dominus, Plover Systems (<code>mjd-perl-ref+@plover.com</code>)
</para>
<para>
作者: Mark Jason Dominus, Plover Systems (<code>mjd-perl-ref+@plover.com</code>)
</para>
<para>
This article originally appeared in <emphasis>The Perl Journal</emphasis>
( <xlink uri='http://www.tpj.com/'>http://www.tpj.com/</xlink> ) volume 3, #2.  Reprinted with permission.
</para>
<para>
この記事は最初は <emphasis>The Perl Journal</emphasis> ( <xlink uri='http://www.tpj.com/'>http://www.tpj.com/</xlink> )
volume 3, #2 に登場しました。
許可を得て転載しています。
</para>
<para>
The original title was <emphasis>Understand References Today</emphasis>.
</para>
<para>
元のタイトルは <emphasis>Understand References Today</emphasis> でした。
</para>
<sect2>
<title>Distribution Conditions</title>
<para>
Copyright 1998 The Perl Journal.
</para>
<para>
This documentation is free; you can redistribute it and/or modify it
under the same terms as Perl itself.
</para>
<para>
Irrespective of its distribution, all code examples in these files are
hereby placed into the public domain.  You are permitted and
encouraged to use this code in your own programs for fun or for profit
as you see fit.  A simple comment in the code giving credit would be
courteous but is not required.
</para>
<para>
Created: KIMURA Koichi
Updated: Kentaro Shirakata &lt;argrath@ub32.org&gt; (5.10.0-)
</para>
</sect2>
</sect1>
</pod>
