5.38.0

名前

perlreftut - Mark's very short tutorial about references

perlreftut - Mark によるリファレンスに関するとても短いチュートリアル

説明

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.

Perl 5 における最も重要な新機能の一つは、多次元配列やネストした ハッシュのような複雑なデータ構造を扱うことのできる能力です。 これらを可能とするために、Perl 5 は リファレンス と呼ばれる機能を導入し、 そしてリファレンスを使うことは、複雑で構造化されたデータを Perl で扱うことの 鍵です。 残念なことに、学ぶにはおかしな構文がたくさんあり、メインの マニュアルページはフォローするのが難しい状態です。 マニュアルはほぼ完璧で、ときとして読者は何が重要で何が重要でないかを 説明するのが難しいので問題を見つけることがあります。

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%.

幸運にも、メインページにあることの 10% を知るだけで 90% の恩恵を 受けることができます。 このページではあなたにその 10% をお見せします。

誰が複合データ構造を必要としているの?

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.

いつもあった問題の一つが、リストの値を持ったハッシュの必要性でした。 Perl はもちろんハッシュを持っていましたが、その値は スカラでなければならず、リストを使うことはできませんでした。

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:

リストのハッシュをなぜ使いたいのでしょうか? 簡単な例で考えてみましょう: あなたが以下のような都市と国の名前のファイルを持っていたとします:

        Chicago, USA
        Frankfurt, Germany
        Berlin, Germany
        Washington, USA
        Helsinki, Finland
        New York, USA

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:

そして、以下のように、国は一度だけ現れてその国の都市がアルファベット順に 現れるような出力を得たかったとします:

        Finland: Helsinki.
        Germany: Berlin, Frankfurt.
        USA:  Chicago, New York, Washington.

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.

これを行う自然な方法は、キーが国の名前であるハッシュを使うことです。 国の名前はその国の都市のリストに関連付けられます。 入力を読むたびに国と都市に分割し、新たな都市をリストに追加します。 入力を読み終えたら通常通りハッシュをイテレートして、出力の前に都市の 各リストをソートしてやります。

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.

もしハッシュの値がリストにできなければあなたの負けです。 おそらくはすべての都市を一つの文字列に連結し、出力するときにその文字列を リストに分解してからそのリストをソートして、その結果を再度文字列へ戻す 必要があるでしょう。 これはわかりにくくて、エラーを持ち込みやすいやり方です。 ハッシュの値をリストにできさえすれば、問題を解決できる完璧なリストを すでに Perl は持っているので、これは不満がたまります。

解決法

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.

Perl 5 の時代でも、すでにこのデザインに困っていました: ハッシュの値は スカラでなければならないのです。 これを解決するのがリファレンスです。

A reference is a scalar value that refers to 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".

リファレンスは配列全体やハッシュ全体(もしくはそれ以外の何か)を 参照する スカラです。 名前はすでになじみの深いリファレンスの一種です。 全ての人間は厄介で不自由な、細胞の集合体です。 しかし、特定の人間、例えば最初のコンピュータプログラマを参照するとき、 そのそれぞれの細胞について記述する必要はありません; 必要なのは、簡単で、便利なスカラ文字列「Ada Lovelace」なのです。

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.

Perl におけるリファレンスは配列やハッシュの名前に似ています。 それらは Perl のプライベートで内部的な名前なので曖昧さがないことを 保証できます。 人名とは異なり、一つのリファレンスは一つのものしか参照しません。 配列全体を一つの名前でリカバーできます。 ハッシュへのリファレンスを持っていれば、ハッシュ全体をリカバーできます。 しかし、リファレンスは簡単で、コンパクトなスカラ値なのです。

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.

あなたは値が配列であるハッシュを持つことはできません; ハッシュの値は スカラのみ可能です。 わたしたちはそれに困っています。 しかし、一つのリファレンスは配列全体を参照することができ、リファレンスは スカラなので、配列へのリファレンスのハッシュを持つことができます; そしてそれは配列のハッシュのように振る舞い、配列のハッシュであるかのように 便利なのです。

We'll come back to this city-country problem later, after we've seen some syntax for managing references.

この都市と国の問題にはリファレンスを扱うための幾つかの構文を見た後で 戻ります。

文法

There are just two ways to make a reference, and just two ways to use it once you have it.

リファレンスを作るには二つの方法があり、使うにも二つの方法があります。

リファレンスを作る

Make Rule 1

(作成ルール 1)

If you put a \ in front of a variable, you get a reference to that variable.

ある変数の先頭に \ をつければ、その変数へのリファレンスを 得ることができます。

    $aref = \@array;         # $aref now holds a reference to @array
    $href = \%hash;          # $href now holds a reference to %hash
    $aref = \@array;         # $aref は @array へのリファレンスを保持する
    $href = \%hash;          # $href は %hash へのリファレンスを保持する

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:

$aref や $href のような変数にリファレンスを格納してしまえば、 スカラ変数のようにコピーしたり格納することができます:

    $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
    $xy = $aref;             # $xy は @array へのリファレンスを保持する
    $p[3] = $href;           # $p[3] は %hash へのリファレンスを保持する
    $z = $p[3];              # $z は %hash へのリファレンスを保持する

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 "\n" or the number 80 without having to store it in a named variable first.

これらの例は、名前を使って変数へのリファレンスを作る方法を 例示するものでした。 ときとして、名前を持っていない配列やハッシュを作りたいときが あるかもしれません。 これは、文字列 "\n" や、数値 80 を、一旦名前付き変数に保管する 必要なしに使えるようにする方法と似ています。

Make Rule 2

[ ITEMS ] makes a new, anonymous array, and returns a reference to that array. { ITEMS } makes a new, anonymous hash, and returns a reference to that hash.

[ ITEMS ] は新たな無名配列を作り、その配列へのリファレンスを返します。 { ITEMS } は新たな無名ハッシュを作り、そのハッシュへのリファレンスを 返します。

    $aref = [ 1, "foo", undef, 13 ];
    # $aref now holds a reference to an array
    $aref = [ 1, "foo", undef, 13 ];  
    # $aref は配列へのリファレンスを保持している
    $href = { APR => 4, AUG => 8 };
    # $href now holds a reference to a hash
    $href = { APR => 4, AUG => 8 };   
    # $href はハッシュへのリファレンスを保持している

The references you get from rule 2 are the same kind of references that you get from rule 1:

ルール 2 によって得たリファレンスはルール 1 によって得た同種の リファレンスと同じです:

        # This:
        $aref = [ 1, 2, 3 ];
        # これは:
        $aref = [ 1, 2, 3 ];
        # Does the same as this:
        @array = (1, 2, 3);
        $aref = \@array;
        # これと同じ:
        @array = (1, 2, 3);
        $aref = \@array;

The first line is an abbreviation for the following two lines, except that it doesn't create the superfluous array variable @array.

最初の行は続く二行を短くしたもので、@array という余分な配列変数を 作りません。

If you write just [], you get a new, empty anonymous array. If you write just {}, you get a new, empty anonymous hash.

[] と書いた場合には新たな空の無名配列が得られます。 {} と書いた場合には新たな空の無名ハッシュが得られます。

リファレンスを使う

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:

リファレンスを得た後でそれに対してできることは? リファレンスはスカラ値であり、スカラであるかのように格納したり 値を得たりできることを見てきました。 リファレンスを使うには他に二つの方法があります。

Use Rule 1

(使用ルール 1)

You can always use an array reference, in curly braces, in place of the name of an array. For example, @{$aref} instead of @array.

配列のリファレンスを、配列の名前が置かれる場所でカーリーブレースの中で 使うことができます。 たとえば、@array の代わりに @{$aref} とします。

Here are some examples of that:

以下に例を挙げます:

Arrays:

配列:

        @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
        @a              @{$aref}                配列
        reverse @a      reverse @{$aref}        配列を反転する
        $a[3]           ${$aref}[3]             配列の要素
        $a[3] = 17;     ${$aref}[3] = 17        要素の代入

On each line are two expressions that do the same thing. The left-hand versions operate on the array @a. The right-hand versions operate on the array that is referred to by $aref. Once they find the array they're operating on, both versions do the same things to the arrays.

各行の二つの式は同じことを行います。 左側のものは @a という配列に対する操作です。 右側のものは $aref によって参照される配列に対する操作です。 操作される配列を見つければ、両方のバージョンは配列に対して同じことを 行います。

Using a hash reference is exactly the same:

ハッシュのリファレンスを使うことも まったく 同じです:

        %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
        %h              %{$href}              ハッシュ
        keys %h         keys %{$href}         ハッシュからキーを得る
        $h{'red'}       ${$href}{'red'}       ハッシュの要素
        $h{'red'} = 17  ${$href}{'red'} = 17  要素への代入

Whatever you want to do with a reference, Use Rule 1 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 {$reference}. "How do I loop over an array when all I have is a reference?" Well, to loop over an array, you would write

リファレンスに対して行いたいことはすべて、"Use Rule 1" で どのように行うかが説明されています。 通常の配列やハッシュに対して同じことを行うような Perl コードを書き、その 配列やハッシュをリファレンス {$reference} で置き換えるのです。 「私が持っているのがリファレンスであるとき、配列に対してループするには?」 そう、配列に対してループするには次のように書くでしょう

        for my $element (@array) {
          ...
        }

so replace the array name, @array, with the reference:

そしてこの配列名 @array をリファレンスで置き換えます:

        for my $element (@{$aref}) {
          ...
        }

"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:

「私が持っているのがリファレンスであるとき、ハッシュの内容を出力するには?」 まずはじめにハッシュを出力するコードを書きます:

        for my $key (keys %hash) {
          print "$key => $hash{$key}\n";
        }

And then replace the hash name with the reference:

そしてハッシュの名前をリファレンスで置き換えます:

        for my $key (keys %{$href}) {
          print "$key => ${$href}{$key}\n";
        }

Use Rule 2

(使用ルール 2)

Use Rule 1 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 Use Rule 1 notation is cumbersome. So there is an abbreviation.

Use Rule 1 はあなたが実際に必要とするすべてです; なぜなら、リファレンスについて必要となることすべてを説明しているからです。 しかし、配列やハッシュについて行いたいことの大部分は一つの要素を 取り出すことで、Use Rule 1 の記法は扱いにくいものです。 そのため、略記法があります。

${$aref}[3] is too hard to read, so you can write $aref->[3] instead.

${$aref}[3] は読みづらいので、代わりに $aref->[3] と書くことが できます。

${$href}{red} is too hard to read, so you can write $href->{red} instead.

${$href}{red} は読みづらいので、代わりに $href->{red} と 書くことができます。

If $aref holds a reference to an array, then $aref->[3] is the fourth element of the array. Don't confuse this with $aref[3], which is the fourth element of a totally different array, one deceptively named @aref. $aref and @aref are unrelated the same way that $item and @item are.

$aref が配列へのリファレンスを保持しているとき、$aref->[3] は その配列の四番目の要素です。 これと $aref[3] を混同しないでください; 後者は @aref という 名前のついた配列の四番目の要素です。 $aref@aref は、$item@item がそうであるように 無関係なものです。

Similarly, $href->{'red'} is part of the hash referred to by the scalar variable $href, perhaps even one with no name. $href{'red'} is part of the deceptively named %href hash. It's easy to forget to leave out the ->, 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.

同様に、$href->{'red'} はスカラ変数 $href によって参照される ハッシュ(おそらくは名前のないもの)の一部分です。 $href{'red'}%href という名前のついたハッシュの一部です。 -> はつけ忘れやすく、もしつけ忘れたならばあなたのプログラムが配列や ハッシュの要素を取り出そうとしたときに、予期していないハッシュや配列を アクセスしたことによる奇妙な結果を得ることになるでしょう。

Let's see a quick example of how all this is useful.

これがどんなに便利なことかを例を挙げてみてみましょう。

First, remember that [1, 2, 3] makes an anonymous array containing (1, 2, 3), and gives you a reference to that array.

まずはじめに、[1, 2, 3](1, 2, 3) から構成される無名配列を 作り出し、その配列に対するリファレンスを与えることを思い出してください。

Now think about

ここで以下について考えます

        @a = ( [1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]
             );

@a is an array with three elements, and each one is a reference to another array.

@a は三つの要素をもつ配列で、その要素はそれぞれ別の配列に対する リファレンスです。

$a[1] is one of these references. It refers to an array, the array containing (4, 5, 6), and because it is a reference to an array, Use Rule 2 says that we can write $a[1]->[2] to get the third element from that array. $a[1]->[2] is the 6. Similarly, $a[0]->[1] is the 2. What we have here is like a two-dimensional array; you can write $a[ROW]->[COLUMN] to get or set the element in any row and any column of the array.

$a[1] はそのようなリファレンスの一つです。 これは (4,5,6) からなる配列を参照します。 これは配列へのリファレンスで、Use Rule 2 はそのような 配列の第三要素を得るために $a[1]->[2] と書けることを述べていたので、 $a[1]->[2] は 6 になります。 同様に、$a[0]->[1] は 2 です。 ここで私たちが得たものは二次元配列のようなものです; 配列の任意の行の任意の列にある要素を得たり、それにセットしたりするのに $a[ROW]->[COLUMN] と書くことができます。

The notation still looks a little cumbersome, so there's one more abbreviation:

この記法はまだ少々扱いにくいものなので、略記法があります:

矢印のルール

In between two subscripts, the arrow is optional.

矢印は、二つの 添え字 の間にあるのなら、省略できます。

Instead of $a[1]->[2], we can write $a[1][2]; it means the same thing. Instead of $a[0]->[1] = 23, we can write $a[0][1] = 23; it means the same thing.

$a[1]->[2]$a[1][2] と書くことができます; これらは同じことを意味します。 $a[0]->[1] = 23 と書く代わりに $a[0][1] = 23 とできます; これらは同じことです。

Now it really looks like two-dimensional arrays!

これで本当に二次元配列らしくなりました!

You can see why the arrows are important. Without them, we would have had to write ${$a[1]}[2] instead of $a[1][2]. For three-dimensional arrays, they let us write $x[2][3][5] instead of the unreadable ${${$x[2]}[3]}[5].

矢印が重要なことがこれでわかります。 もし矢印がなければ、$a[1][2] の代わりに ${$a[1]}[2] と 書かなければなりません。 三次元配列では、${${$x[2]}[3]}[5] のような読みづらいものではなくて $x[2][3][5] とできます。

答え

Here's the answer to the problem I posed earlier, of reformatting a file of city and country names.

以下は先に保留していた問題に対する解答です; 都市と国の名前のファイルの 再フォーマットを行うものです。

    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   }

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, %table, whose keys are country names, and whose values are references to arrays of city names. The data structure will look like this:

プログラムは二つの部分から構成されています: 2 行目から 7 行目は入力を 読み込んでデータ構造を構築します; そして 8 行目から 13 行目でデータを 解析して結果を出力します。 わたしたちはここで、キーとして国の名前を持ち、値として都市名のリストへの リファレンスを持つハッシュ %table を作ろうとしています。 データ構造は以下のようなものです:

           %table
        +-------+---+
        |       |   |   +-----------+--------+
        |Germany| *---->| Frankfurt | Berlin |
        |       |   |   +-----------+--------+
        +-------+---+
        |       |   |   +----------+
        |Finland| *---->| Helsinki |
        |       |   |   +----------+
        +-------+---+
        |       |   |   +---------+------------+----------+
        |  USA  | *---->| Chicago | Washington | New York |
        |       |   |   +---------+------------+----------+
        +-------+---+

We'll look at output first. Supposing we already have this structure, how do we print it out?

最初に出力を見ましょう。 ここで、すでに上記の構造ができているとします; どのように 出力するのでしょうか?

    8   for my $country (sort keys %table) {
    9     print "$country: ";
   10     my @cities = @{$table{$country}};
   11     print join ', ', sort @cities;
   12     print ".\n";
   13   }

%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. $table{$country} looks up the key $country in the hash and gets the value, which is a reference to an array of cities in that country. Use Rule 1 says that we can recover the array by saying @{$table{$country}}. Line 10 is just like

%table は通常のハッシュで、そこからキーのリストを得てそれをソートして 通常通りキーに対してループします。 リファレンスは 10 行目でだけ使われています。 $table{$country} はハッシュの $country キーを参照します; これは その国の都市の配列に対するリファレンスです。 Use Rule 1 は配列を @{$table{$country}} で 取り出せるといっています。 10 行目は

        @cities = @array;

except that the name array has been replaced by the reference {$table{$country}}. The @ tells Perl to get the entire array. Having gotten the list of cities, we sort it, join it, and print it out as usual.

と同じようなものですが、array という名前が {$table{$country}} という リファレンスに置き換えられています。 @ は Perl に配列全体を取り出すことを指示しています。 都市のリストを得たらそれをソートして、つなげ、そして通常と同じように 出力します。

Lines 2-7 are responsible for building the structure in the first place. Here they are again:

2 行目から 7 行目は構造を構築している部分です。 再掲します:

    2   while (<>) {
    3     chomp;
    4     my ($city, $country) = split /, /;
    5     $table{$country} = [] unless exists $table{$country};
    6     push @{$table{$country}}, $city;
    7   }

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 [] notation (Make Rule 2) to manufacture a new, empty anonymous array of cities, and installs a reference to it into the hash under the appropriate key.

2 行目から 4 行目は都市と国の名前を得ています。 5 行目はその国がすでにハッシュのキーとして存在しているかどうかを見ています。 もし存在していなければ、プログラムは [] 記法 (Make Rule 2) を使って新しい 空の都市が格納される無名配列を作り出します; そして、リファレンスを配列の 適切なキーにセットします。

Line 6 installs the city name into the appropriate array. $table{$country} now holds a reference to the array of cities seen in that country so far. Line 6 is exactly like

6行目は都市名を対応する配列にインストールします。 $table{$country} はここでその国の都市の配列に対するリファレンスを 保持しています。 6 行目は

        push @array, $city;

except that the name array has been replaced by the reference {$table{$country}}. The push adds a city name to the end of the referred-to array.

と同じようなものですが、array という名前が {$table{$country}} という リファレンスに置き換えられています。 push は都市名を参照されている配列の末尾に 追加します。

There's one fine point I skipped. Line 5 is unnecessary, and we can get rid of it.

スキップした点があります。 5 行目は不必要なので、取り除くことができます。

    2   while (<>) {
    3     chomp;
    4     my ($city, $country) = split /, /;
    5   ####  $table{$country} = [] unless exists $table{$country};
    6     push @{$table{$country}}, $city;
    7   }

If there's already an entry in %table for the current $country, then nothing is different. Line 6 will locate the value in $table{$country}, which is a reference to an array, and push $city into the array. But what does it do when $country holds a key, say Greece, that is not yet in %table?

%table の中に現在の $country のためのエントリがすでに存在していれば 異なる点はありません。 6 行目は配列へのリファレンスである $table{$country} の値に注目し、 その配列に $city をプッシュします。 しかし、$country%table の中にない Greece のようなキーを 保持していたら何をするのでしょうか?

This is Perl, so it does the exact right thing. It sees that you want to push Athens onto an array that doesn't exist, so it helpfully makes a new, empty, anonymous array for you, installs it into %table, and then pushes Athens onto it. This is called autovivification--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.

これは Perl です; ですから、本当に正しいことを行います。 存在していない配列に Athens をプッシュしようとするので、新しく空の 無名配列をあなたのために作り出してそれを %table にインストールします; そしてそれから Athens をそこにプッシュします。 これは 自動有効化(autovivification) と呼ばれます。 Perl はハッシュの中にそれらのキーが存在しないことを確認し、新しいハッシュ エントリを自動的に作り出します。 Perl はあなたがハッシュの値を配列として扱いたがっていることを 知っているので、新しい空の配列を作り出してハッシュの中にそれに対する リファレンスを自動的にインストールします。 いつもと同じように、Perlは新たな都市名を保持する一要素の配列を 作り出します。

残り

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 perlref manual page, which discusses 100% of the details.

わたしはあなたに 10% の詳細で 90% の利益を得ることを約束しました; そしてそれは詳細の 90% をそのままにしているということです。 今、あなたは重要な部分を見てきました; それにより詳細の 100% を述べている perlref man ページをより簡単に読むことができるようになったでしょう。

Some of the highlights of perlref:

perlref のハイライトの幾つかを挙げておきます:

  • You can make references to anything, including scalars, functions, and other references.

    任意のものに対するリファレンスを作成することができます; そこにはスカラ、関数、他のリファレンスも含まれます。

  • In Use Rule 1, you can omit the curly brackets whenever the thing inside them is an atomic scalar variable like $aref. For example, @$aref is the same as @{$aref}, and $$aref[1] is the same as ${$aref}[1]. If you're just starting out, you may want to adopt the habit of always including the curly brackets.

    Use Rule 1 の中で、その中にあるものが $aref のような アトミックなスカラ変数である場合にはカーリーブラケットを 省略することができます。 たとえば、@$aref@{$aref} と同じで、$$aref[1]${$aref}[1] と同じです。 始めたばかりなのであれば、常にカーリーブラケットで囲むことを 習慣付けたくなるかもしれません。

  • This doesn't copy the underlying array:

    以下は配列の内容をコピーしません:

            $aref2 = $aref1;

    You get two references to the same array. If you modify $aref1->[23] and then look at $aref2->[23] you'll see the change.

    同じ配列に対する二つのリファレンスが得られます。 もし $aref1->[23] を変更して、$aref2->[23] を 参照したならば変更したものが見えるでしょう。

    To copy the array, use

    配列をコピーするには以下のようにします

            $aref2 = [@{$aref1}];

    This uses [...] notation to create a new anonymous array, and $aref2 is assigned a reference to the new array. The new array is initialized with the contents of the array referred to by $aref1.

    これは新たな無名配列を作り出すために [...] 記法を使っています; そして、$aref2 は新たな配列に対するリファレンスが代入されます。 新たな配列は $aref1 によって参照される配列の内容によって初期化されます。

    Similarly, to copy an anonymous hash, you can use

    同様に、無名ハッシュをコピーするには以下のようにします

            $href2 = {%{$href1}};
  • To see if a variable contains a reference, use the ref function. It returns true if its argument is a reference. Actually it's a little better than that: It returns HASH for hash references and ARRAY for array references.

    変数がリファレンスを保持しているときにそれを確認するには、 ref 関数を使います。 この関数はその引数がリファレンスであるときには真を返します。 実際にはもうちょっと良くて、ハッシュリファレンスであれば HASH を、 配列リファレンスであれば ARRAY を返します。

  • If you try to use a reference like a string, you get strings like

    リファレンスを文字列のように使った場合には、以下のような文字列が得られます

            ARRAY(0x80f5dec)   or    HASH(0x826afc0)

    If you ever see a string that looks like this, you'll know you printed out a reference by mistake.

    もしこのような文字列を見たならば、リファレンスを間違って出力したことを 知ることとなるでしょう。

    A side effect of this representation is that you can use eq to see if two references refer to the same thing. (But you should usually use == instead because it's much faster.)

    この表現の副作用は、eq を二つの リファレンスが同じものを参照しているかどうかを確認するために 使うことができるということです。 (しかし、通常はより早い == を代わりに 使うべきでしょう。)

  • You can use a string as if it were a reference. If you use the string "foo" as an array reference, it's taken to be a reference to the array @foo. This is called a symbolic reference. The declaration use strict 'refs' disables this feature, which can cause all sorts of trouble if you use it by accident.

    文字列をリファレンスであるかのように使うことができます。 文字列 "foo" を配列リファレンスとして使うとき、@foo への 参照であるかのように受け付けられます。 これは シンボリックリファレンス と呼ばれます。 use strict 'refs' と宣言することによって、アクシデントによって 問題が引き起こされる場合があるこの機能を禁止することができます。

You might prefer to go on to perllol instead of perlref; it discusses lists of lists and multidimensional arrays in detail. After that, you should move on to perldsc; 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.

perlref よりも perllol に行きたいと思うかもしれません; そこではリストのリストや多次元配列について詳しく述べられています。 その後で、perldsc に行くと良いでしょう; これはデータ構造クックブック (Data Structure Cookbook)で、ハッシュの配列、配列のハッシュ、その他の データの使用や出力についてのレシピがあります。

まとめ

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.

すべての人が複合データ構造を必要としていて、Perlでのそれを得るやり方は リファレンスです。 リファレンスを扱うにあたって四つの重要なルールがあります: 二つは リファレンスの作成についてで、二つはリファレンスの使用についてです。 これらのルールを知ってしまえば、あなたがリファレンスを使って行う必要が あることの重要な部分のほとんどを行うことができます。

Credits

Author: Mark Jason Dominus, Plover Systems (mjd-perl-ref+@plover.com)

作者: Mark Jason Dominus, Plover Systems (mjd-perl-ref+@plover.com)

This article originally appeared in The Perl Journal ( http://www.tpj.com/ ) volume 3, #2. Reprinted with permission.

この記事は最初は The Perl Journal ( http://www.tpj.com/ ) volume 3, #2 に登場しました。 許可を得て転載しています。

The original title was Understand References Today.

元のタイトルは Understand References Today でした。

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.