=encoding euc-jp =head1 NAME =begin original perlreftut - Mark's very short tutorial about references =end original perlreftut - Mark によるリファレンスに関するとても短いチュートリアル =head1 DESCRIPTION =begin original 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 I, 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. =end original Perl 5 における最も重要な新機能の一つは、多次元配列やネストした ハッシュのような複雑なデータ構造を扱うことのできる能力です。 これらを可能とするために、Perl 5 は I<リファレンス> と呼ばれる機能を導入し、 そしてリファレンスを使うことは、複雑で構造化されたデータを Perl で扱うことの 鍵です。 残念なことに、学ぶにはおかしな構文がたくさんあり、メインの マニュアルページはフォローするのが難しい状態です。 マニュアルはほぼ完璧で、ときとして読者は何が重要で何が重要でないかを 説明するのが難しいので問題を見つけることがあります。 =begin original 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%. =end original 幸運にも、メインページにあることの 10% を知るだけで 90% の恩恵を 受けることができます。 このページではあなたにその 10% をお見せします。 =head1 Who Needs Complicated Data Structures? (誰が複合データ構造を必要としているの?) =begin original One problem that comes up all the time is needing a hash whose values are lists. Perl has hashes, of course, but the values have to be scalars; they can't be lists. =end original いつもあった問題の一つが、リストの値を持ったハッシュの必要性でした。 Perl はもちろんハッシュを持っていましたが、その値は スカラでなければならず、リストを使うことはできませんでした。 =begin original 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: =end original リストのハッシュをなぜ使いたいのでしょうか? 簡単な例で考えてみましょう: あなたが以下のような都市と国の名前のファイルを持っていたとします: Chicago, USA Frankfurt, Germany Berlin, Germany Washington, USA Helsinki, Finland New York, USA =begin original 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: =end original そして、以下のように、国は一度だけ現れてその国の都市がアルファベット順に 現れるような出力を得たかったとします: Finland: Helsinki. Germany: Berlin, Frankfurt. USA: Chicago, New York, Washington. =begin original 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. =end original これを行う自然な方法は、キーが国の名前であるハッシュを使うことです。 国の名前はその国の都市のリストに関連付けられます。 入力を読むたびに国と都市に分割し、新たな都市をリストに追加します。 入力を読み終えたら通常通りハッシュをイテレートして、出力の前に都市の 各リストをソートしてやります。 =begin original If hash values couldn't be lists, 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. =end original もしハッシュの値がリストにできなければあなたの負けです。 おそらくはすべての都市を一つの文字列に連結し、出力するときにその文字列を リストに分解してからそのリストをソートして、その結果を再度文字列へ戻す 必要があるでしょう。 これはわかりにくくて、エラーを持ち込みやすいやり方です。 ハッシュの値をリストにできさえすれば、問題を解決できる完璧なリストを すでに Perl は持っているので、これは不満がたまります。 =head1 The Solution (解決法) =begin original 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. =end original Perl 5 の時代でも、すでにこのデザインに困っていました: ハッシュの値は スカラでなければならないのです。 これを解決するのがリファレンスです。 =begin original A reference is a scalar value that I 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. Each human being is a messy, inconvenient collection of cells. But to refer to a particular human, for instance the first computer programmer, it isn't necessary to describe each of their cells; all you need is the easy, convenient scalar string "Ada Lovelace". =end original リファレンスは配列全体やハッシュ全体(もしくはそれ以外の何か)を I<参照する> スカラです。 名前はすでになじみの深いリファレンスの一種です。 全ての人間は厄介で不自由な、細胞の集合体です。 しかし、特定の人間、例えば最初のコンピュータプログラマを参照するとき、 そのそれぞれの細胞について記述する必要はありません; 必要なのは、簡単で、便利なスカラ文字列「Ada Lovelace」なのです。 =begin original 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 a human name, 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. =end original Perl におけるリファレンスは配列やハッシュの名前に似ています。 それらは Perl のプライベートで内部的な名前なので曖昧さがないことを 保証できます。 人名とは異なり、一つのリファレンスは一つのものしか参照しません。 配列全体を一つの名前でリカバーできます。 ハッシュへのリファレンスを持っていれば、ハッシュ全体をリカバーできます。 しかし、リファレンスは簡単で、コンパクトなスカラ値なのです。 =begin original 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. =end original あなたは値が配列であるハッシュを持つことはできません; ハッシュの値は スカラのみ可能です。 わたしたちはそれに困っています。 しかし、一つのリファレンスは配列全体を参照することができ、リファレンスは スカラなので、配列へのリファレンスのハッシュを持つことができます; そしてそれは配列のハッシュのように振る舞い、配列のハッシュであるかのように 便利なのです。 =begin original We'll come back to this city-country problem later, after we've seen some syntax for managing references. =end original この都市と国の問題にはリファレンスを扱うための幾つかの構文を見た後で 戻ります。 =head1 Syntax (文法) =begin original There are just two ways to make a reference, and just two ways to use it once you have it. =end original リファレンスを作るには二つの方法があり、使うにも二つの方法があります。 =head2 Making References (リファレンスを作る) =head3 B (B<作成ルール 1>) =begin original If you put a C<\> in front of a variable, you get a reference to that variable. =end original ある変数の先頭に C<\> をつければ、その変数へのリファレンスを 得ることができます。 =begin original $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 =end original $aref = \@array; # $aref は @array へのリファレンスを保持する $href = \%hash; # $href は %hash へのリファレンスを保持する $sref = \$scalar; # $sref は $scalar へのリファレンスを保持する =begin original 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: =end original $aref や $href のような変数にリファレンスを格納してしまえば、 スカラ変数のようにコピーしたり格納することができます: =begin original $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 =end original $xy = $aref; # $xy は @array へのリファレンスを保持する $p[3] = $href; # $p[3] は %hash へのリファレンスを保持する $z = $p[3]; # $z は %hash へのリファレンスを保持する =begin original 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 C<"\n"> or the number 80 without having to store it in a named variable first. =end original これらの例は、名前を使って変数へのリファレンスを作る方法を 例示するものでした。 ときとして、名前を持っていない配列やハッシュを作りたいときが あるかもしれません。 これは、文字列 C<"\n"> や、数値 80 を、一旦名前付き変数に保管する 必要なしに使えるようにする方法と似ています。 =head3 B =begin original C<[ ITEMS ]> makes a new, anonymous array, and returns a reference to that array. C<{ ITEMS }> makes a new, anonymous hash, and returns a reference to that hash. =end original C<[ ITEMS ]> は新たな無名配列を作り、その配列へのリファレンスを返します。 C<{ ITEMS }> は新たな無名ハッシュを作り、そのハッシュへのリファレンスを 返します。 =begin original $aref = [ 1, "foo", undef, 13 ]; # $aref now holds a reference to an array =end original $aref = [ 1, "foo", undef, 13 ]; # $aref は配列へのリファレンスを保持している =begin original $href = { APR => 4, AUG => 8 }; # $href now holds a reference to a hash =end original $href = { APR => 4, AUG => 8 }; # $href はハッシュへのリファレンスを保持している =begin original The references you get from rule 2 are the same kind of references that you get from rule 1: =end original ルール 2 によって得たリファレンスはルール 1 によって得た同種の リファレンスと同じです: =begin original # This: $aref = [ 1, 2, 3 ]; =end original # これは: $aref = [ 1, 2, 3 ]; =begin original # Does the same as this: @array = (1, 2, 3); $aref = \@array; =end original # これと同じ: @array = (1, 2, 3); $aref = \@array; =begin original The first line is an abbreviation for the following two lines, except that it doesn't create the superfluous array variable C<@array>. =end original 最初の行は続く二行を短くしたもので、C<@array> という余分な配列変数を 作りません。 =begin original If you write just C<[]>, you get a new, empty anonymous array. If you write just C<{}>, you get a new, empty anonymous hash. =end original C<[]> と書いた場合には新たな空の無名配列が得られます。 C<{}> と書いた場合には新たな空の無名ハッシュが得られます。 =head2 Using References (リファレンスを使う) =begin original 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: =end original リファレンスを得た後でそれに対してできることは? リファレンスはスカラ値であり、スカラであるかのように格納したり 値を得たりできることを見てきました。 リファレンスを使うには他に二つの方法があります。 =head3 B (B<使用ルール 1>) =begin original You can always use an array reference, in curly braces, in place of the name of an array. For example, C<@{$aref}> instead of C<@array>. =end original 配列のリファレンスを、配列の名前が置かれる場所でカーリーブレースの中で 使うことができます。 たとえば、C<@array> の代わりに C<@{$aref}> とします。 =begin original Here are some examples of that: =end original 以下に例を挙げます: =begin original Arrays: =end original 配列: =begin original @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 =end original @a @{$aref} 配列 reverse @a reverse @{$aref} 配列を反転する $a[3] ${$aref}[3] 配列の要素 $a[3] = 17; ${$aref}[3] = 17 要素の代入 =begin original On each line are two expressions that do the same thing. The left-hand versions operate on the array C<@a>. The right-hand versions operate on the array that is referred to by C<$aref>. Once they find the array they're operating on, both versions do the same things to the arrays. =end original 各行の二つの式は同じことを行います。 左側のものは C<@a> という配列に対する操作です。 右側のものは C<$aref> によって参照される配列に対する操作です。 操作される配列を見つければ、両方のバージョンは配列に対して同じことを 行います。 =begin original Using a hash reference is I the same: =end original ハッシュのリファレンスを使うことも I<まったく> 同じです: =begin original %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 =end original %h %{$href} ハッシュ keys %h keys %{$href} ハッシュからキーを得る $h{'red'} ${$href}{'red'} ハッシュの要素 $h{'red'} = 17 ${$href}{'red'} = 17 要素への代入 =begin original Whatever you want to do with a reference, B 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 C<{$reference}>. "How do I loop over an array when all I have is a reference?" Well, to loop over an array, you would write =end original リファレンスに対して行いたいことはすべて、L で どのように行うかが説明されています。 通常の配列やハッシュに対して同じことを行うような Perl コードを書き、その 配列やハッシュをリファレンス C<{$reference}> で置き換えるのです。 「私が持っているのがリファレンスであるとき、配列に対してループするには?」 そう、配列に対してループするには次のように書くでしょう for my $element (@array) { ... } =begin original so replace the array name, C<@array>, with the reference: =end original そしてこの配列名 C<@array> をリファレンスで置き換えます: for my $element (@{$aref}) { ... } =begin original "How do I print out the contents of a hash when all I have is a reference?" First write the code for printing out a hash: =end original 「私が持っているのがリファレンスであるとき、ハッシュの内容を出力するには?」 まずはじめにハッシュを出力するコードを書きます: for my $key (keys %hash) { print "$key => $hash{$key}\n"; } =begin original And then replace the hash name with the reference: =end original そしてハッシュの名前をリファレンスで置き換えます: for my $key (keys %{$href}) { print "$key => ${$href}{$key}\n"; } =head3 B (B<使用ルール 2>) =begin original L|/B> 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 L|/B> notation is cumbersome. So there is an abbreviation. =end original L|/B> はあなたが実際に必要とするすべてです; なぜなら、リファレンスについて必要となることすべてを説明しているからです。 しかし、配列やハッシュについて行いたいことの大部分は一つの要素を 取り出すことで、L|/B> の記法は扱いにくいものです。 そのため、略記法があります。 =begin original C<${$aref}[3]> is too hard to read, so you can write C<< $aref->[3] >> instead. =end original C<${$aref}[3]> は読みづらいので、代わりに C<< $aref->[3] >> と書くことが できます。 =begin original C<${$href}{red}> is too hard to read, so you can write C<< $href->{red} >> instead. =end original C<${$href}{red}> は読みづらいので、代わりに C<< $href->{red} >> と 書くことができます。 =begin original If C<$aref> holds a reference to an array, then C<< $aref->[3] >> is the fourth element of the array. Don't confuse this with C<$aref[3]>, which is the fourth element of a totally different array, one deceptively named C<@aref>. C<$aref> and C<@aref> are unrelated the same way that C<$item> and C<@item> are. =end original C<$aref> が配列へのリファレンスを保持しているとき、C<< $aref->[3] >> は その配列の四番目の要素です。 これと C<$aref[3]> を混同しないでください; 後者は C<@aref> という 名前のついた配列の四番目の要素です。 C<$aref> と C<@aref> は、C<$item> と C<@item> がそうであるように 無関係なものです。 =begin original Similarly, C<< $href->{'red'} >> is part of the hash referred to by the scalar variable C<$href>, perhaps even one with no name. C<$href{'red'}> is part of the deceptively named C<%href> hash. It's easy to forget to leave out the C<< -> >>, 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. =end original 同様に、C<< $href->{'red'} >> はスカラ変数 C<$href> によって参照される ハッシュ(おそらくは名前のないもの)の一部分です。 C<$href{'red'}> は C<%href> という名前のついたハッシュの一部です。 C<< -> >> はつけ忘れやすく、もしつけ忘れたならばあなたのプログラムが配列や ハッシュの要素を取り出そうとしたときに、予期していないハッシュや配列を アクセスしたことによる奇妙な結果を得ることになるでしょう。 =head2 An Example (例) =begin original Let's see a quick example of how all this is useful. =end original これがどんなに便利なことかを例を挙げてみてみましょう。 =begin original First, remember that C<[1, 2, 3]> makes an anonymous array containing C<(1, 2, 3)>, and gives you a reference to that array. =end original まずはじめに、C<[1, 2, 3]> が C<(1, 2, 3)> から構成される無名配列を 作り出し、その配列に対するリファレンスを与えることを思い出してください。 =begin original Now think about =end original ここで以下について考えます @a = ( [1, 2, 3], [4, 5, 6], [7, 8, 9] ); =begin original C<@a> is an array with three elements, and each one is a reference to another array. =end original C<@a> は三つの要素をもつ配列で、その要素はそれぞれ別の配列に対する リファレンスです。 =begin original C<$a[1]> is one of these references. It refers to an array, the array containing C<(4, 5, 6)>, and because it is a reference to an array, L|/B> says that we can write C<< $a[1]->[2] >> to get the third element from that array. C<< $a[1]->[2] >> is the 6. Similarly, C<< $a[0]->[1] >> is the 2. What we have here is like a two-dimensional array; you can write C<< $a[ROW]->[COLUMN] >> to get or set the element in any row and any column of the array. =end original C<$a[1]> はそのようなリファレンスの一つです。 これは C<(4,5,6)> からなる配列を参照します。 これは配列へのリファレンスで、L|/B> はそのような 配列の第三要素を得るために C<< $a[1]->[2] >> と書けることを述べていたので、 C<< $a[1]->[2] >> は 6 になります。 同様に、C<< $a[0]->[1] >> は 2 です。 ここで私たちが得たものは二次元配列のようなものです; 配列の任意の行の任意の列にある要素を得たり、それにセットしたりするのに C<< $a[ROW]->[COLUMN] >> と書くことができます。 =begin original The notation still looks a little cumbersome, so there's one more abbreviation: =end original この記法はまだ少々扱いにくいものなので、略記法があります: =head2 Arrow Rule (矢印のルール) =begin original In between two B, the arrow is optional. =end original 矢印は、二つの B<添え字> の間にあるのなら、省略できます。 =begin original Instead of C<< $a[1]->[2] >>, we can write C<$a[1][2]>; it means the same thing. Instead of C<< $a[0]->[1] = 23 >>, we can write C<$a[0][1] = 23>; it means the same thing. =end original C<< $a[1]->[2] >> は C<$a[1][2]> と書くことができます; これらは同じことを意味します。 C<< $a[0]->[1] = 23 >> と書く代わりに C<$a[0][1] = 23> とできます; これらは同じことです。 =begin original Now it really looks like two-dimensional arrays! =end original これで本当に二次元配列らしくなりました! =begin original You can see why the arrows are important. Without them, we would have had to write C<${$a[1]}[2]> instead of C<$a[1][2]>. For three-dimensional arrays, they let us write C<$x[2][3][5]> instead of the unreadable C<${${$x[2]}[3]}[5]>. =end original 矢印が重要なことがこれでわかります。 もし矢印がなければ、C<$a[1][2]> の代わりに C<${$a[1]}[2]> と 書かなければなりません。 三次元配列では、C<${${$x[2]}[3]}[5]> のような読みづらいものではなくて C<$x[2][3][5]> とできます。 =head1 Solution (答え) =begin original Here's the answer to the problem I posed earlier, of reformatting a file of city and country names. =end original 以下は先に保留していた問題に対する解答です; 都市と国の名前のファイルの 再フォーマットを行うものです。 1 my %table; 2 while (<>) { 3 chomp; 4 my ($city, $country) = split /, /; 5 $table{$country} = [] unless exists $table{$country}; 6 push @{$table{$country}}, $city; 7 } 8 for my $country (sort keys %table) { 9 print "$country: "; 10 my @cities = @{$table{$country}}; 11 print join ', ', sort @cities; 12 print ".\n"; 13 } =begin original 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, C<%table>, whose keys are country names, and whose values are references to arrays of city names. The data structure will look like this: =end original プログラムは二つの部分から構成されています: 2 行目から 7 行目は入力を 読み込んでデータ構造を構築します; そして 8 行目から 13 行目でデータを 解析して結果を出力します。 わたしたちはここで、キーとして国の名前を持ち、値として都市名のリストへの リファレンスを持つハッシュ C<%table> を作ろうとしています。 データ構造は以下のようなものです: %table +-------+---+ | | | +-----------+--------+ |Germany| *---->| Frankfurt | Berlin | | | | +-----------+--------+ +-------+---+ | | | +----------+ |Finland| *---->| Helsinki | | | | +----------+ +-------+---+ | | | +---------+------------+----------+ | USA | *---->| Chicago | Washington | New York | | | | +---------+------------+----------+ +-------+---+ =begin original We'll look at output first. Supposing we already have this structure, how do we print it out? =end original 最初に出力を見ましょう。 ここで、すでに上記の構造ができているとします; どのように 出力するのでしょうか? 8 for my $country (sort keys %table) { 9 print "$country: "; 10 my @cities = @{$table{$country}}; 11 print join ', ', sort @cities; 12 print ".\n"; 13 } =begin original C<%table> 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. C<$table{$country}> looks up the key C<$country> in the hash and gets the value, which is a reference to an array of cities in that country. L|/B> says that we can recover the array by saying C<@{$table{$country}}>. Line 10 is just like =end original C<%table> は通常のハッシュで、そこからキーのリストを得てそれをソートして 通常通りキーに対してループします。 リファレンスは 10 行目でだけ使われています。 C<$table{$country}> はハッシュの C<$country> キーを参照します; これは その国の都市の配列に対するリファレンスです。 L|/B> は配列を C<@{$table{$country}}> で 取り出せるといっています。 10行目は @cities = @array; =begin original except that the name C has been replaced by the reference C<{$table{$country}}>. The C<@> tells Perl to get the entire array. Having gotten the list of cities, we sort it, join it, and print it out as usual. =end original と同じようなものですが、C という名前が C<{$table{$country}}> という リファレンスに置き換えられています。 C<@> は Perl に配列全体を取り出すことを指示しています。 都市のリストを得たらそれをソートして、つなげ、そして通常と同じように 出力します。 =begin original Lines 2-7 are responsible for building the structure in the first place. Here they are again: =end original 2 行目から 7 行目は構造を構築している部分です。 再掲します: 2 while (<>) { 3 chomp; 4 my ($city, $country) = split /, /; 5 $table{$country} = [] unless exists $table{$country}; 6 push @{$table{$country}}, $city; 7 } =begin original 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 C<[]> notation (L|/B>) to manufacture a new, empty anonymous array of cities, and installs a reference to it into the hash under the appropriate key. =end original 2 行目から 4 行目は都市と国の名前を得ています。 5 行目はその国がすでにハッシュのキーとして存在しているかどうかを見ています。 もし存在していなければ、プログラムは [] 記法 (L|/B>) を使って新しい 空の都市が格納される無名配列を作り出します; そして、リファレンスを配列の 適切なキーにセットします。 =begin original Line 6 installs the city name into the appropriate array. C<$table{$country}> now holds a reference to the array of cities seen in that country so far. Line 6 is exactly like =end original 6行目は都市名を対応する配列にインストールします。 C<$table{$country}> はここでその国の都市の配列に対するリファレンスを 保持しています。 6 行目は push @array, $city; =begin original except that the name C has been replaced by the reference C<{$table{$country}}>. The L|perlfunc/push ARRAY,LIST> adds a city name to the end of the referred-to array. =end original のようなものですが、異なるのは C が C<{$table{$country}}> という リファレンスに置き換わっている点です。 L|perlfunc/push ARRAY,LIST> は都市名を参照されている配列の末尾に 追加します。 =begin original There's one fine point I skipped. Line 5 is unnecessary, and we can get rid of it. =end original スキップした点があります。 5 行目は不必要なので、取り除くことができます。 2 while (<>) { 3 chomp; 4 my ($city, $country) = split /, /; 5 #### $table{$country} = [] unless exists $table{$country}; 6 push @{$table{$country}}, $city; 7 } =begin original If there's already an entry in C<%table> for the current C<$country>, then nothing is different. Line 6 will locate the value in C<$table{$country}>, which is a reference to an array, and push C<$city> into the array. But what does it do when C<$country> holds a key, say C, that is not yet in C<%table>? =end original C<%table> の中に現在の C<$country> のためのエントリがすでに存在していれば 異なる点はありません。 6 行目は配列へのリファレンスである C<$table{$country}> の値に注目し、 その配列に C<$city> をプッシュします。 しかし、C<$country> が C<%table> の中にない C のようなキーを 保持していたら何をするのでしょうか? =begin original This is Perl, so it does the exact right thing. It sees that you want to push C onto an array that doesn't exist, so it helpfully makes a new, empty, anonymous array for you, installs it into C<%table>, and then pushes C onto it. This is called I--bringing things to life automatically. Perl saw that the 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. =end original これは Perl です; ですから、本当に正しいことを行います。 存在していない配列に Athens をプッシュしようとするので、新しく空の 無名配列をあなたのために作り出してそれを C<%table> にインストールします; そしてそれから C をそこにプッシュします。 これは I<自動有効化>(autovivification) と呼ばれます。 Perl はハッシュの中にそれらのキーが存在しないことを確認し、新しいハッシュ エントリを自動的に作り出します。 Perl はあなたがハッシュの値を配列として扱いたがっていることを 知っているので、新しい空の配列を作り出してハッシュの中にそれに対する リファレンスを自動的にインストールします。 いつもと同じように、Perlは新たな都市名を保持する一要素の配列を 作り出します。 =head1 The Rest (残り) =begin original 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 L manual page, which discusses 100% of the details. =end original わたしはあなたに 10% の詳細で 90% の利益を得ることを約束しました; そしてそれは詳細の 90% をそのままにしているということです。 今、あなたは重要な部分を見てきました; それにより詳細の 100% を述べている L man ページをより簡単に読むことができるようになったでしょう。 =begin original Some of the highlights of L: =end original L のハイライトの幾つかを挙げておきます: =over 4 =item * =begin original You can make references to anything, including scalars, functions, and other references. =end original 任意のものに対するリファレンスを作成することができます; そこにはスカラ、関数、他のリファレンスも含まれます。 =item * =begin original In L|/B>, you can omit the curly brackets whenever the thing inside them is an atomic scalar variable like C<$aref>. For example, C<@$aref> is the same as C<@{$aref}>, and C<$$aref[1]> is the same as C<${$aref}[1]>. If you're just starting out, you may want to adopt the habit of always including the curly brackets. =end original L|/B> の中で、その中にあるものが C<$aref> のような アトミックなスカラ変数である場合にはカーリーブラケットを 省略することができます。 たとえば、C<@$aref> は C<@{$aref}> と同じで、C<$$aref[1]> は C<${$aref}[1]> と同じです。 始めたばかりなのであれば、常にカーリーブラケットで囲むことを 習慣付けたくなるかもしれません。 =item * =begin original This doesn't copy the underlying array: =end original 以下は配列の内容をコピーしません: $aref2 = $aref1; =begin original You get two references to the same array. If you modify C<< $aref1->[23] >> and then look at C<< $aref2->[23] >> you'll see the change. =end original 同じ配列に対する二つのリファレンスが得られます。 もし C<< $aref1->[23] >> を変更して、C<< $aref2->[23] >> を 参照したならば変更したものが見えるでしょう。 =begin original To copy the array, use =end original 配列をコピーするには以下のようにします $aref2 = [@{$aref1}]; =begin original This uses C<[...]> notation to create a new anonymous array, and C<$aref2> is assigned a reference to the new array. The new array is initialized with the contents of the array referred to by C<$aref1>. =end original これは新たな無名配列を作り出すために C<[...]> 記法を使っています; そして、C<$aref2> は新たな配列に対するリファレンスが代入されます。 新たな配列は C<$aref1> によって参照される配列の内容によって初期化されます。 =begin original Similarly, to copy an anonymous hash, you can use =end original 同様に、無名ハッシュをコピーするには以下のようにします $href2 = {%{$href1}}; =item * =begin original To see if a variable contains a reference, use the L|perlfunc/ref EXPR> function. It returns true if its argument is a reference. Actually it's a little better than that: It returns C for hash references and C for array references. =end original 変数がリファレンスを保持しているときにそれを確認するには、 L|perlfunc/ref EXPR> 関数を使います。 この関数はその引数がリファレンスであるときには真を返します。 実際にはもうちょっと良くて、ハッシュリファレンスであれば C を、 配列リファレンスであれば C を返します。 =item * =begin original If you try to use a reference like a string, you get strings like =end original リファレンスを文字列のように使った場合には、以下のような文字列が得られます ARRAY(0x80f5dec) or HASH(0x826afc0) =begin original If you ever see a string that looks like this, you'll know you printed out a reference by mistake. =end original もしこのような文字列を見たならば、リファレンスを間違って出力したことを 知ることとなるでしょう。 =begin original A side effect of this representation is that you can use L|perlop/Equality Operators> to see if two references refer to the same thing. (But you should usually use L|perlop/Equality Operators> instead because it's much faster.) =end original この表現の副作用は、L|perlop/Equality Operators> を二つの リファレンスが同じものを参照しているかどうかを確認するために 使うことができるということです。 (しかし、通常はより早い L|perlop/Equality Operators> を代わりに 使うべきでしょう。) =item * =begin original You can use a string as if it were a reference. If you use the string C<"foo"> as an array reference, it's taken to be a reference to the array C<@foo>. This is called a I. The declaration L|strict> disables this feature, which can cause all sorts of trouble if you use it by accident. =end original 文字列をリファレンスであるかのように使うことができます。 文字列 C<"foo"> を配列リファレンスとして使うとき、C<@foo> への 参照であるかのように受け付けられます。 これは I<シンボリックリファレンス> と呼ばれます。 L|strict> と宣言することによって、アクシデントによって 問題が引き起こされる場合があるこの機能を禁止することができます。 =back =begin original You might prefer to go on to L instead of L; it discusses lists of lists and multidimensional arrays in detail. After that, you should move on to L; 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. =end original L よりも L に行きたいと思うかもしれません; そこではリストのリストや多次元配列について詳しく述べられています。 その後で、L に行くと良いでしょう; これはデータ構造クックブック (Data Structure Cookbook)で、ハッシュの配列、配列のハッシュ、その他の データの使用や出力についてのレシピがあります。 =head1 Summary (まとめ) =begin original 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. =end original すべての人が複合データ構造を必要としていて、Perlでのそれを得るやり方は リファレンスです。 リファレンスを扱うにあたって四つの重要なルールがあります: 二つは リファレンスの作成についてで、二つはリファレンスの使用についてです。 これらのルールを知ってしまえば、あなたがリファレンスを使って行う必要が あることの重要な部分のほとんどを行うことができます。 =head1 Credits =begin original Author: Mark Jason Dominus, Plover Systems (C) =end original 作者: Mark Jason Dominus, Plover Systems (C) =begin original This article originally appeared in I ( L ) volume 3, #2. Reprinted with permission. =end original この記事は最初は I ( L ) volume 3, #2 に登場しました。 許可を得て転載しています。 =begin original The original title was I. =end original 元のタイトルは I でした。 =head2 Distribution Conditions Copyright 1998 The Perl Journal. This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. 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. =cut =begin meta Translate: KIMURA Koichi Update: SHIRAKATA Kentaro (5.10.0-) Status: completed =end meta