5.14.1

NAME

perlref - Perl references and nested data structures

perlref - Perlのリファレンスとネストしたデータ構造

注意

This is complete documentation about all aspects of references. For a shorter, tutorial introduction to just the essential features, see perlreftut.

本ドキュメントはリファレンスに関するものです。 チュートリアルに関しては perlreftut を参照してください。

説明

Before release 5 of Perl it was difficult to represent complex data structures, because all references had to be symbolic--and even then it was difficult to refer to a variable instead of a symbol table entry. Perl now not only makes it easier to use symbolic references to variables, but also lets you have "hard" references to any piece of data or code. Any scalar may hold a hard reference. Because arrays and hashes contain scalars, you can now easily build arrays of arrays, arrays of hashes, hashes of arrays, arrays of hashes of functions, and so on.

リリース 5 以前の Perl ではすべてのリファレンスはシンボリックでなければ ならなかったために、複雑なデータ構造を表現することが困難でした。 そしてシンボルテーブルのエントリーではなく変数を参照したいと望んだときも 困難であったのです。 Perl はシンボリックリファレンスを変数として使うことを簡単にしただけでなく、 任意のデータについて「ハード」リファレンスを持つことを可能としたのです。 任意のスカラはハードリファレンスを保持することができます。 配列とハッシュはスカラから構成されているので、あなたはいまや配列の配列、 ハッシュの配列、配列のハッシュ、関数のハッシュの配列等々を簡単に 組み立てることができるのです。

Hard references are smart--they keep track of reference counts for you, automatically freeing the thing referred to when its reference count goes to zero. (Reference counts for values in self-referential or cyclic data structures may not go to zero without a little help; see "Two-Phased Garbage Collection" in perlobj for a detailed explanation.) If that thing happens to be an object, the object is destructed. See perlobj for more about objects. (In a sense, everything in Perl is an object, but we usually reserve the word for references to objects that have been officially "blessed" into a class package.)

ハードリファレンスは賢く実際に参照されている数を管理していて、その数が 0 になれば自動的に解放を行ないます。 (自己参照や循環データ(cyclic data)にある値に対する参照カウントは、 ちょっとした手助けなしにはゼロにはなりません。 詳しくは "Two-Phased Garbage Collection" in perlobj を参照してください。) そのものがオブジェクトであるときには、デストラクタが動作します。 オブジェクトについてより詳しくは、perlobj を参照してください。 (ある意味では、Perl のすべてがオブジェクトですが、通常、 クラスパッケージ内で公に "bless" されているものへのリファレンスに対して、 この用語を用います。)

Symbolic references are names of variables or other objects, just as a symbolic link in a Unix filesystem contains merely the name of a file. The *glob notation is something of a symbolic reference. (Symbolic references are sometimes called "soft references", but please don't call them that; references are confusing enough without useless synonyms.)

UNIX ファイルシステム上でのシンボリックリンクが単にファイルの名前を 持っているだけであるのと同様に、シンボリックリファレンスは変数の 名前を保持します。 *glob の記法は、シンボリックリファレンスの一種です (シンボリックリファレンスは時折“ソフトリファレンス”と 呼ばれますが、そういう呼びかたをしないでください。 リファレンスは同義語を使わないでいてさえ混乱を招くのですから)。

In contrast, hard references are more like hard links in a Unix file system: They are used to access an underlying object without concern for what its (other) name is. When the word "reference" is used without an adjective, as in the following paragraph, it is usually talking about a hard reference.

対照的に、 ハードリファレンスはUNIXのファイルシステム上のハードリンクに 似ています。 ハードリンクはそれがなんの名前であるのかを気にせずに 基礎をなすオブジェクトにアクセスするために使われます。 以下の節にあるように“リファレンス”と言う言葉を形容なしに使った 場合、通常はハードリファレンスのことを指します。

References are easy to use in Perl. There is just one overriding principle: Perl does no implicit referencing or dereferencing. When a scalar is holding a reference, it always behaves as a simple scalar. It doesn't magically start being an array or hash or subroutine; you have to tell it explicitly to do so, by dereferencing it.

Perlでリファレンスを使うのは非常に簡単です。 原則のオーバーライドが一つあるだけです。 Perl はリファレンス(referencing)やデリファレンス(defreferencing)を 暗黙に行うことはありません。 スカラがリファレンスを保持しているとき、それは常に単純なスカラとして 振る舞います。 勝手に配列や、ハッシュ、サブルーチンとして振る舞うようなことはありません。 デリファレンスをすることによって、自分で明示的に Perl に 教える必要があります。

リファレンスを作る

References can be created in several ways.

リファレンスは幾つかのやり方で構築することができます。

1.

By using the backslash operator on a variable, subroutine, or value. (This works much like the & (address-of) operator in C.) This typically creates another reference to a variable, because there's already a reference to the variable in the symbol table. But the symbol table reference might go away, and you'll still have the reference that the backslash returned. Here are some examples:

変数、サブルーチン、値にバックスラッシュ演算子を使うことによる (これは C での & (アドレス) 演算子に似た働きをします)。 既にシンボルテーブルには変数へのリファレンスが存在していますから、 この方法は 別の リファレンスを作るものです。 しかし、シンボルテーブルのリファレンスがなくなったとしても、 バックスラッシュが返したリファレンスが存在することになります。 例をいくつかあげます:

    $scalarref = \$foo;
    $arrayref  = \@ARGV;
    $hashref   = \%ENV;
    $coderef   = \&handler;
    $globref   = \*foo;

It isn't possible to create a true reference to an IO handle (filehandle or dirhandle) using the backslash operator. The most you can get is a reference to a typeglob, which is actually a complete symbol table entry. But see the explanation of the *foo{THING} syntax below. However, you can still use type globs and globrefs as though they were IO handles.

バックスラッシュ演算子を使って IO ハンドル(ファイルハンドルまたは ディレクトリハンドル)へのリファレンスを生成することはできません。 もっとも良く扱うリファレンスは型グロブに対するリファレンス(実際には シンボルテーブルのエントリである)でしょう。 後述する *foo{THING} 構文の説明を参照してください。 しかしながら、IO ハンドルであったものとして型グロブや型グロブの リファレンス(grobref)を使うこともできます。

2.

A reference to an anonymous array can be created using square brackets:

名前の無い配列へのリファレンスは、大かっこを使って作ることができます:

    $arrayref = [1, 2, ['a', 'b', 'c']];

Here we've created a reference to an anonymous array of three elements whose final element is itself a reference to another anonymous array of three elements. (The multidimensional syntax described later can be used to access this. For example, after the above, $arrayref->[2][1] would have the value "b".)

ここでは、『「名前の無い 3 個の要素を持つ配列」を最後の要素として持つ 3 個要素の名前の無い配列』へのリファレンスを作っています。 (あとで述べる多次元構文を使って、これをアクセスすることができます。 たとえば、上記のようにした後では、 $arrayref->[2][1] が "b" となります。)

Taking a reference to an enumerated list is not the same as using square brackets--instead it's the same as creating a list of references!

列挙リストに対するリファレンスを取るということは、大かっこを使うことと 同じではありません。 これはリファレンスのリストを生成することと同じなのです!

    @list = (\$a, \@b, \%c);
    @list = \($a, @b, %c);      # same thing!

As a special case, \(@foo) returns a list of references to the contents of @foo, not a reference to @foo itself. Likewise for %foo, except that the key references are to copies (since the keys are just strings rather than full-fledged scalars).

特殊な場合として、\(@foo)@foo 自身へのリファレンスではなく、 @foo の内容のそれぞれへのリファレンスのリストを返します。 %foo も同様ですが、キーのコピーに対するリファレンスである点が 異なります(これはキーが完全なスカラではなく単なる文字列であるためです)。

3.

A reference to an anonymous hash can be created using curly brackets:

名前の無いハッシュへのリファレンスは、中かっこを使って作ることができます:

    $hashref = {
        'Adam'  => 'Eve',
        'Clyde' => 'Bonnie',
    };

Anonymous hash and array composers like these can be intermixed freely to produce as complicated a structure as you want. The multidimensional syntax described below works for these too. The values above are literals, but variables and expressions would work just as well, because assignment operators in Perl (even within local() or my()) are executable statements, not compile-time declarations.

無名ハッシュと配列のコンストラクタは、複雑な構造を作るために自由に 組み合わせることができます。 後述する多次元構文は、そのようなものに対しても使うことができます。 上記の値はリテラルですが、変数や式であってもかまいません。 Perl での代入演算は、(たとえ、local() や my() の中でも) コンパイル時の 宣言文ではなく、実行文だからです。

Because curly brackets (braces) are used for several other things including BLOCKs, you may occasionally have to disambiguate braces at the beginning of a statement by putting a + or a return in front so that Perl realizes the opening brace isn't starting a BLOCK. The economy and mnemonic value of using curlies is deemed worth this occasional extra hassle.

中かっこは、BLOCK を始めとして他のことにも使われますから、 開きの中かっこが BLOCK の開始でないことを Perl に教える ために文の最初の中かっこの前に +return をつけて、 曖昧さをなくすようにする必要がある場合があります。 このちょっとした余分な作業は、中かっこの使用に関連して 実際に使ってみる価値や覚えておくだけの価値があるでしょう。

For example, if you wanted a function to make a new hash and return a reference to it, you have these options:

たとえば、新しいハッシュを作って、それへのリファレンスを返す関数が欲しければ、 以下のような選択肢があります:

    sub hashem {        { @_ } }   # silently wrong
    sub hashem {       +{ @_ } }   # ok
    sub hashem { return { @_ } }   # ok

On the other hand, if you want the other meaning, you can do this:

その一方で、以下のようにすることもできます:

    sub showem {        { @_ } }   # ambiguous (currently ok, but may change)
    sub showem {       {; @_ } }   # ok
    sub showem { { return @_ } }   # ok

The leading +{ and {; always serve to disambiguate the expression to mean either the HASH reference, or the BLOCK.

先頭にある +{{; が、その式が実際には ハッシュのリファレンスなのかブロックなのかの 曖昧さを除去するためにあります。

4.

A reference to an anonymous subroutine can be created by using sub without a subname:

無名サブルーチンのへのリファレンスは、サブルーチン名の無い sub を使って 作ることができます:

    $coderef = sub { print "Boink!\n" };

Note the semicolon. Except for the code inside not being immediately executed, a sub {} is not so much a declaration as it is an operator, like do{} or eval{}. (However, no matter how many times you execute that particular line (unless you're in an eval("...")), $coderef will still have a reference to the same anonymous subroutine.)

セミコロンに注意してください。 内部のコードが即座に実行されるのではないということを除けば、sub{} は、 宣言というよりもむしろ、do{}eval{} のような演算子です(しかし、 eval("...") の中でなければ、何回その行を実行しようとも $coderef は、同一の 無名サブルーチンをリファレンスすることになります)。

Anonymous subroutines act as closures with respect to my() variables, that is, variables lexically visible within the current scope. Closure is a notion out of the Lisp world that says if you define an anonymous function in a particular lexical context, it pretends to run in that context even when it's called outside the context.

無名サブルーチンは my() 変数に関連するクロージャのように振る舞います。 つまり、変数はカレントのスコープの中においてレキシカルに見えます。 クロージャは、無名関数をある特定のレキシカルコンテキストで 定義した場合にたとえそのコンテキストの外側で呼び出されたとしても 定義されたときのコンテキストで実行されることを要求するという Lisp の世界の概念です。

In human terms, it's a funny way of passing arguments to a subroutine when you define it as well as when you call it. It's useful for setting up little bits of code to run later, such as callbacks. You can even do object-oriented stuff with it, though Perl already provides a different mechanism to do that--see perlobj.

わかりやすく言えば、あなたがサブルーチンを呼び出すときと同じように、 サブルーチンを定義するときに引数を渡すという奇妙なやり方ということです。 あなたはこれでオブジェクト指向的性質を実現することも できます。 が、Perl はすでにこれとは異なる仕組みを提供しています -- perlobj を参照してください。

You might also think of closure as a way to write a subroutine template without using eval(). Here's a small example of how closures work:

クロージャは eval なしにサブルーチンのテンプレートを記述する方法だという 考え方もできます。 以下に示すのは、クロージャがどのように動作するのかの例です。

    sub newprint {
        my $x = shift;
        return sub { my $y = shift; print "$x, $y!\n"; };
    }
    $h = newprint("Howdy");
    $g = newprint("Greetings");

    # Time passes...

    &$h("world");
    &$g("earthlings");

This prints

出力はこうなります。

    Howdy, world!
    Greetings, earthlings!

Note particularly that $x continues to refer to the value passed into newprint() despite "my $x" having gone out of scope by the time the anonymous subroutine runs. That's what a closure is all about.

ここで特に、無名サブルーチンの実行時には“my $x”がスコープの外にあるにも かかわらず、$x が newprint() に渡された値を参照しつづけていることに 注意してください。 これがクロージャがクロージャたる由縁です。

This applies only to lexical variables, by the way. Dynamic variables continue to work as they have always worked. Closure is not something that most Perl programmers need trouble themselves about to begin with.

これはレキシカル変数にのみ適用されます。 動的変数はこれまでと同じように動作します。 クロージャは、大部分の Perl プログラマーがそれを使いはじめるために トラブルをしょいこんでしまうような代物ではありません。

5.

References are often returned by special subroutines called constructors. Perl objects are just references to a special type of object that happens to know which package it's associated with. Constructors are just special subroutines that know how to create that association. They do so by starting with an ordinary reference, and it remains an ordinary reference even while it's also being an object. Constructors are often named new(). You can call them indirectly:

リファレンスはコンストラクタと呼ばれる特別なサブルーチンが返すようにして いることが多くなっています。 Perlのオブジェクトは、自分がどのパッケージと関係を持っているかを 知っているものへのリファレンスでしかありません。 コンストラクタは、その関係付けをどのように行なうかを知っているという意味で、 特別なサブルーチンにすぎません。 単なるリファレンスとしてスタートし、オブジェクトといわれている間でも 通常のリファレンスであることに変わりはありません。 コンストラクタは、慣習的に new() と名前を付けられます。 間接的に呼び出すことも 可能です:

    $objref = new Doggie( Tail => 'short', Ears => 'long' );

But that can produce ambiguous syntax in certain cases, so it's often better to use the direct method invocation approach:

しかし、これは場合によってはあいまいな文法となる場合があるので、 たいていは直接メソッド起動手法を使う方がよいです:

    $objref   = Doggie->new(Tail => 'short', Ears => 'long');

    use Term::Cap;
    $terminal = Term::Cap->Tgetent( { OSPEED => 9600 });

    use Tk;
    $main    = MainWindow->new();
    $menubar = $main->Frame(-relief              => "raised",
                            -borderwidth         => 2)
6.

References of the appropriate type can spring into existence if you dereference them in a context that assumes they exist. Because we haven't talked about dereferencing yet, we can't show you any examples yet.

適切な型のリファレンスは、そういったリファレンスが存在するかのような文脈で デリファレンスを行うと、実際に存在するようになります。 デリファレンスについてはまだ話していないので、まだ例を示すことができません。

7.

A reference can be created by using a special syntax, lovingly known as the *foo{THING} syntax. *foo{THING} returns a reference to the THING slot in *foo (which is the symbol table entry which holds everything known as foo).

リファレンスは、*foo{THING} 構文として知られている 特殊な構文を使って生成することができます。 *foo{THING} はリファレンスを *foo の THING スロット(これは foo として知られる全てのものを保持するシンボルテーブルのエントリです)に 返します。

    $scalarref = *foo{SCALAR};
    $arrayref  = *ARGV{ARRAY};
    $hashref   = *ENV{HASH};
    $coderef   = *handler{CODE};
    $ioref     = *STDIN{IO};
    $globref   = *foo{GLOB};
    $formatref = *foo{FORMAT};

All of these are self-explanatory except for *foo{IO}. It returns the IO handle, used for file handles ("open" in perlfunc), sockets ("socket" in perlfunc and "socketpair" in perlfunc), and directory handles ("opendir" in perlfunc). For compatibility with previous versions of Perl, *foo{FILEHANDLE} is a synonym for *foo{IO}, though it is deprecated as of 5.8.0. If deprecation warnings are in effect, it will warn of its use.

これら全ては、*foo{IO} を除いて自己説明的です。 ファイルハンドル("open" in perlfunc)、ソケット("socket" in perlfunc"socketpair" in perlfunc)、ディレクトリハンドル("opendir" in perlfunc) として使われる IO ハンドルを返します。 過去のバージョンの Perl に対する互換性のために、 *foo{FILEHANDLE}*foo{IO} の同義語ですが、5.8.0 からは 非推奨です。 非推奨警告が有効になっていれば、使用すると警告が出ます。

*foo{THING} returns undef if that particular THING hasn't been used yet, except in the case of scalars. *foo{SCALAR} returns a reference to an anonymous scalar if $foo hasn't been used yet. This might change in a future release.

*foo{THING} は、スカラの場合を除いた特定の THING がまだ 使われていない場合には undef を返します。 *foo{SCALAR} は、$foo がまだ使われていなかった場合には 無名スカラへのリファレンスを返します。 これは将来のリリースでは変わる可能性があります。

*foo{IO} is an alternative to the *HANDLE mechanism given in "Typeglobs and Filehandles" in perldata for passing filehandles into or out of subroutines, or storing into larger data structures. Its disadvantage is that it won't create a new filehandle for you. Its advantage is that you have less risk of clobbering more than you want to with a typeglob assignment. (It still conflates file and directory handles, though.) However, if you assign the incoming value to a scalar instead of a typeglob as we do in the examples below, there's no risk of that happening.

*foo{IO} は、"Typeglobs and Filehandles" in perldata にある ファイルハンドルをサブルーチンに渡したり、あるいは逆に サブルーチンから返すために、あるいは大きなデータ構造を格納する ために用いられる *HANDLE 機構の代替です。 その不利な点は新しいハンドルをあなたのために作り出すことはしないと いうことです。 有利な点は、型グロブの代入を使うよりも気をつかう必要があまりないということです。 (しかし、これはまだファイルハンドルとディレクトリハンドルを融合します。) しかし、もし以下の例で行っているように、値を型グロブではなくスカラに 代入すると、起きることに対するリスクはありません。

    splutter(*STDOUT);          # pass the whole glob
    splutter(*STDOUT{IO});      # pass both file and dir handles

    sub splutter {
        my $fh = shift;
        print $fh "her um well a hmmm\n";
    }

    $rec = get_rec(*STDIN);     # pass the whole glob
    $rec = get_rec(*STDIN{IO}); # pass both file and dir handles

    sub get_rec {
        my $fh = shift;
        return scalar <$fh>;
    }

リファレンスを使う

That's it for creating references. By now you're probably dying to know how to use references to get back to your long-lost data. There are several basic methods.

リファレンスの作り方はこれだけです。 ここまでくると、どこか参照のかなたへ行ってしまったデータを取り戻すために、 どうやってリファレンスを使うかを知りたいことでしょう。 基本的な方法がいくつかあります。

  1. Anywhere you'd