perlfaq-5.0150039

名前

perlfaq7 - General Perl Language Issues

perlfaq7 - Perl 言語一般に関することがら

説明

This section deals with general Perl language issues that don't clearly fit into any of the other sections.

このセクションでは、他のセクションにはきっちりとあてはまらないような Perl 言語に関する一般的な事柄を扱います。

Perl のための BNF/yacc/RE は入手できますか?

There is no BNF, but you can paw your way through the yacc grammar in perly.y in the source distribution if you're particularly brave. The grammar relies on very smart tokenizing code, so be prepared to venture into toke.c as well.

BNFはありませんが、もし多少の勇気を持ちあわせているのであれば 配布ソースに含まれている perly.y にある yacc 文法をいじくりまわすことが できます。 その文法は非常に賢い字句解析ルーチンに依存したものなので、 toke.c を眺める準備もしておきましょう。

In the words of Chaim Frenkel: "Perl's grammar can not be reduced to BNF. The work of parsing perl is distributed between yacc, the lexer, smoke and mirrors."

reduce Chaim Frenkel の言葉を借りればこうです: 「Perl の文法は BNF まで縮小することができない。 perl の構文解析の作業は yacc、字句解析器、煙と鏡とに分配される。」

$@%&* のマークはなんですか、これらをいつ使えばいいのかを知るにはどうすればいいですか?

They are type specifiers, as detailed in perldata:

これらは型指定子(type specifiers)で、perldata で説明されています:

    $ for scalar values (number, string or reference)
    @ for arrays
    % for hashes (associative arrays)
    & for subroutines (aka functions, procedures, methods)
    * for all types of that symbol name. In version 4 you used them like
      pointers, but in modern perls you can just use references.
    $ スカラ値(数値、文字列、リファレンス)に対するもの
    @ 配列に対するもの
    % ハッシュ(連想配列)に対するもの
    & サブルーチン(またの名を関数、手続き、メソッド)に対するもの
    * シンボル名に対する全ての型。バージョン 4 ではポインタのように
      使われていましたが、新しい perl ではリファレンスが使えます。

There are a couple of other symbols that you're likely to encounter that aren't really type specifiers:

実際には型指定子として見ることはないであろう二つのものが この他にもあります:

    <> are used for inputting a record from a filehandle.
    \  takes a reference to something.
    <> あるファイルハンドルからレコードを入力するのに使われます。
    \  なにかのリファレンスを取ります。

Note that <FILE> is neither the type specifier for files nor the name of the handle. It is the <> operator applied to the handle FILE. It reads one line (well, record--see "$/" in perlvar) from the handle FILE in scalar context, or all lines in list context. When performing open, close, or any other operation besides <> on files, or even when talking about the handle, do not use the brackets. These are correct: eof(FH), seek(FH, 0, 2) and "copying from STDIN to FILE".

<FILE> は、ファイルに対する型指定子にもハンドルの名前の どちらでもない ということに注意してください。 これはハンドル FILE に対する <> 演算子です。 一行(そう、レコードですね -- "$/" in perlvar を参照してください) を FILE というハンドルからスカラコンテキストで読み出します; リストコンテキストの場合は 全ての 行を読み出します。 ファイルの <> に関係する open、close などの操作を行うときには、 ハンドルについて行っている場合であっても アングルブラケットを使っては いけませんeof(FH), seek(FH, 0,2) や "copying from STDIN to FILE" は 正しいものなのです。

文字列ではクォートしたりセミコロンやカンマを使うのは常に必要/常に不要ですか?

Normally, a bareword doesn't need to be quoted, but in most cases probably should be (and must be under use strict). But a hash key consisting of a simple word and the left-hand operand to the => operator both count as though they were quoted:

通常は、裸の単語(barewords)はクォートする必要はありませんが、 ほとんど場合はクォートすべきでしょう(そして、use strcit しているときは しなければなりません)。 しかし、単純な単語から 構成されるハッシュと、=> 演算子の左側にあるオペランドは 両方ともクォートされているとみなされます:

    This                    is like this
    ------------            ---------------
    $foo{line}              $foo{'line'}
    bar => stuff            'bar' => stuff

The final semicolon in a block is optional, as is the final comma in a list. Good style (see perlstyle) says to put them in except for one-liners:

ブロックの最後にあるセミコロンは、リストの最後にあるカンマと同じく 省略可能です。 良いスタイル(perlstyle を参照)は一行野郎(one-liners)でなければ それらを使うようにしましょうと言っています。

    if ($whoops) { exit 1 }
    my @nums = (1, 2, 3);

    if ($whoops) {
        exit 1;
    }

    my @lines = (
        "There Beren came from mountains cold",
        "And lost he wandered under leaves",
    );

戻り値の一部をスキップするには?

One way is to treat the return values as a list and index into it:

方法の一つは、戻り値をリストとみなして、それに添え字づけするというものです:

    $dir = (getpwnam($user))[7];

Another way is to use undef as an element on the left-hand-side:

もう一つのやりかたは、左辺の要素として undef を使うというものです:

    ($dev, $ino, undef, undef, $uid, $gid) = stat($file);

You can also use a list slice to select only the elements that you need:

必要な要素だけを選択するために、リストスライスも使えます:

    ($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5];

一時的に警告をブロックするには?

If you are running Perl 5.6.0 or better, the use warnings pragma allows fine control of what warnings are produced. See perllexwarn for more details.

Perl 5.6.0 以降を使っているなら、use warnings プラグマで どんな警告を生成するかをうまく制御できます。 詳細については perllexwarn を参照してください。

    {
        no warnings;          # temporarily turn off warnings
        $x = $y + $z;         # I know these might be undef
    }

Additionally, you can enable and disable categories of warnings. You turn off the categories you want to ignore and you can still get other categories of warnings. See perllexwarn for the complete details, including the category names and hierarchy.

さらに、警告の分野毎に警告を有効または無効にできます。 無視したいカテゴリを無効にしても、残りのカテゴリの警告は受けられます。 カテゴリ名と階層を含む、完全な詳細については perllexwarn を 参照してください。

    {
        no warnings 'uninitialized';
        $x = $y + $z;
    }

If you have an older version of Perl, the $^W variable (documented in perlvar) controls runtime warnings for a block:

より古いバージョンの場合は、変数 $^W(perlvar に説明があります)は 実行時の警告のブロックを制御します:

    {
        local $^W = 0;        # temporarily turn off warnings
        $x = $y + $z;         # I know these might be undef
    }
    {
        local $^W = 0;    # 一時的に警告をオフにする
        $a = $b + $c;     # これらが undef かもしれないことを知っている
    }

Note that like all the punctuation variables, you cannot currently use my() on $^W, only local().

全ての句読点変数(punctuation variable)と同様、現時点では $^W に対して my() を使うことはできず、local() だけしか使えないということに 注意してください。

エクステンションてなんですか?

An extension is a way of calling compiled C code from Perl. Reading perlxstut is a good place to learn more about extensions.

エクステンションとは、Perl からコンパイル済みの C コードを呼び出すための 方法です。 エクステンションについて知るには perlxstut を読むのが良いでしょう。

なぜ Perl の演算子は C の演算子とは異なった優先順位を持っているのでしょうか?

Actually, they don't. All C operators that Perl copies have the same precedence in Perl as they do in C. The problem is with operators that C doesn't have, especially functions that give a list context to everything on their right, eg. print, chmod, exec, and so on. Such functions are called "list operators" and appear as such in the precedence table in perlop.

実際はそうではありません。 Perl に持ち込まれた C の演算子はすべて、C と Perl とで同じ優先順位を 持っています。 問題は、C にはない演算子、特にその右辺に対してつねにリストコンテキストを 与える関数、例えば print、chmod、exce などです。 そういった関数は「リスト演算子」と呼ばれ、perlop にある優先順位テーブルに あります。

A common mistake is to write:

ありがちな間違いは以下のようにのように書いてしまうことです:

    unlink $file || die "snafu";

This gets interpreted as:

これは以下のように解釈されます:

    unlink ($file || die "snafu");

To avoid this problem, either put in extra parentheses or use the super low precedence or operator:

この問題を避けるためには、余計な括弧をつけるかより優先順位の低い or 演算子を使うようにします:

    (unlink $file) || die "snafu";
    unlink $file or die "snafu";

The "English" operators (and, or, xor, and not) deliberately have precedence lower than that of list operators for just such situations as the one above.

"English" 演算子(and, or, xor, not) は先に説明している 同じ働きをするリスト演算子よりも低い優先順位を故意に持たされています。

Another operator with surprising precedence is exponentiation. It binds more tightly even than unary minus, making -2**2 produce a negative four and not a positive one. It is also right-associating, meaning that 2**3**2 is two raised to the ninth power, not eight squared.

もう一つの、びっくりするような優先順位を持っている演算子は べき乗(exponentiation)です。 これは単項のマイナスよりも強く結び付くので、-2**2 はプラス 4 ではなく、 マイナス 4 を生成します。 この演算子は右結合するので、2**3**2 は 8 の 2 乗ではなく、 2 の 9 乗です。

Although it has the same precedence as in C, Perl's ?: operator produces an lvalue. This assigns $x to either $if_true or $if_false, depending on the trueness of $maybe:

C と同じ優先順位を持っているにも関らず、Perl では ?: 演算子は 左辺値を作り出します。 以下の代入では、$maybe の値に応じて、$if_true か $if_false のいずれかに $x の値を代入します:

    ($maybe ? $if_true : $if_false) = $x;

構造体を宣言したり生成するには?

In general, you don't "declare" a structure. Just use a (probably anonymous) hash reference. See perlref and perldsc for details. Here's an example:

一般的には、構造体を“宣言”することはありません。 単に(おそらくは無名の)ハッシュリファレンスを使うだけです。 詳しくは perlrefperldsc を参照してください。 例を挙げましょう:

    $person = {};                   # new anonymous hash
    $person->{AGE}  = 24;           # set field AGE to 24
    $person->{NAME} = "Nat";        # set field NAME to "Nat"

If you're looking for something a bit more rigorous, try perltoot.

もうちょっと正確ななにかを求めているのなら、 perltoot に挑戦してみてください。

モジュールを作成するには?

perlnewmod is a good place to start, ignore the bits about uploading to CPAN if you don't want to make your module publicly available.

perlnewmod が始めるのに良い場所です; 作成したモジュールを公開しようと 思っていない場合は CPAN へのアップロードに関する部分については 無視してください。

ExtUtils::ModuleMaker and Module::Starter are also good places to start. Many CPAN authors now use Dist::Zilla to automate as much as possible.

ExtUtils::ModuleMakerModule::Starter も始めるのによい場所です。 多くの CPAN 作者は今ではできるだけ自動化するために Dist::Zilla を 使っています。

Detailed documentation about modules can be found at: perlmod, perlmodlib, perlmodstyle.

モジュールに関する詳しい文書は以下にあります: perlmod, perlmodlib, perlmodstyle

If you need to include C code or C library interfaces use h2xs. h2xs will create the module distribution structure and the initial interface files. perlxs and perlxstut explain the details.

C コードや C ライブラリインターフェースを含める必要があるなら、 h2xs を使ってください。 h2xs はモジュール配布構造と書記インターフェースファイルを作成します。 perlxsperlxstut は詳細を説明しています。

すでに CPAN にあるモジュールを引き継ぐには?

Ask the current maintainer to make you a co-maintainer or transfer the module to you.

共同メンテナにしてもらうか、モジュールを引き渡してもらうように現在の メンテナに訊ねてください。

If you can not reach the author for some reason contact the PAUSE admins at modules@perl.org who may be able to help, but each case it treated seperatly.

もし何らかの理由で作者と連絡が取れない場合、助けることができるかも知れない PAUSE 管理者である modules@perl.org に連絡してください; 但しどのように 扱われるかは個々の場合によります。

  • Get a login for the Perl Authors Upload Server (PAUSE) if you don't already have one: http://pause.perl.org

    まだ持っていないなら、the Perl Authors Upload Server (PAUSE) のアカウントを 取ります: http://pause.perl.org

  • Write to modules@perl.org explaining what you did to contact the current maintainer. The PAUSE admins will also try to reach the maintainer.

    現在のメンテナに連絡するためにしたことの説明を modules@perl.org に書きます。 PAUSE 管理者もメンテナに連絡を試みます。

  • Post a public message in a heavily trafficked site announcing your intention to take over the module.

    モジュールを引き継ぎたいという意思を表明するために、トラフィックの多い サイトに公的なメッセージを投稿します。

  • Wait a bit. The PAUSE admins don't want to act too quickly in case the current maintainer is on holiday. If there's no response to private communication or the public post, a PAUSE admin can transfer it to you.

    しばらく待ちます。 PAUSE 管理者は、現在のメンテナが休暇中の場合に、あまりに性急に行動したいとは 思いません。 もし私的な通信や公的な投稿に反応がない場合、PAUSE 管理者はモジュールを あなたに移行できます。

クラスを作るには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

In Perl, a class is just a package, and methods are just subroutines. Perl doesn't get more formal than that and lets you set up the package just the way that you like it (that is, it doesn't set up anything for you).

Perl では、クラスは単なるパッケージで、メソッドは単なるサブルーチンです。 Perl はそれ以上に形式的なことはしませんし、あなたの好きな方法でパッケージを 設定できるようにします (つまり、Perl はあなたのために何の設定もしません)。

The Perl documentation has several tutorials that cover class creation, including perlboot (Barnyard Object Oriented Tutorial), perltoot (Tom's Object Oriented Tutorial), perlbot (Bag o' Object Tricks), and perlobj.

Perl の文書には、 perlboot (Barnyard Object Oriented Tutorial), perltoot (Tom's Object Oriented Tutorial), perlbot (Bag o' Object Tricks), perlobj といった、クラス生成に対応する いくつかのチュートリアルがあります。

変数が汚染されているかどうかを確かめるには?

You can use the tainted() function of the Scalar::Util module, available from CPAN (or included with Perl since release 5.8.0). See also "Laundering and Detecting Tainted Data" in perlsec.

CPAN にある (リリース 5.8.0 からは Perl に含まれている) Scalar::Util モジュールの tainted() 関数が使えます。 "Laundering and Detecting Tainted Data" in perlsec も参照してください。

クロージャ(closure)ってなんですか?

Closures are documented in perlref.

クロージャは perlref に説明があります。

Closure is a computer science term with a precise but hard-to-explain meaning. Usually, closures are implemented in Perl as anonymous subroutines with lasting references to lexical variables outside their own scopes. These lexicals magically refer to the variables that were around when the subroutine was defined (deep binding).

クロージャ は、きちんとした定義を持ったコンピュータ科学の用語ですが その意味を説明するのはとても難しいのです。 クロージャは Perl では、そのスコープの外側でもレキシカル変数に対する リファレンスを保持しつづける無名サブルーチンとして実装されています。 これらのレキシカルは、サブルーチンが定義されたときの変数に対して、 魔法のような参照(magically refer)を行います(深い束縛、deep binding)。

Closures are most often used in programming languages where you can have the return value of a function be itself a function, as you can in Perl. Note that some languages provide anonymous functions but are not capable of providing proper closures: the Python language, for example. For more information on closures, check out any textbook on functional programming. Scheme is a language that not only supports but encourages closures.

クロージャは、Perl ができるような関数の戻り値として関数それ自身を返す関数を 持つことができるプログラミング言語でもっともよく使われます。 一部の言語では、無名関数を提供しているけれども適切なクロージャを提供する 能力はないということに注意してください: たとえば Python がそうです。 クロージャに関するより詳しいことは、関数言語に関するなんらかの教科書を みてください。 Scheme はクロージャをサポートするだけでなく、それを推奨している言語です。

Here's a classic non-closure function-generating function:

以下は、古典的な、クロージャではない関数を生成する関数です:

    sub add_function_generator {
        return sub { shift() + shift() };
    }

    my $add_sub = add_function_generator();
    my $sum = $add_sub->(4,5);                # $sum is 9 now.

The anonymous subroutine returned by add_function_generator() isn't technically a closure because it refers to no lexicals outside its own scope. Using a closure gives you a function template with some customization slots left out to be filled later.

add_function_generator() が返した無名サブルーチンは技術的には クロージャではありません; なぜなら、あれはスコープの外側で 参照するようなレキシカルがないからです。 クロージャを使うことによって、後で埋めることのできるカスタマイズ可能な 幾つかのスロットを持つ 関数テンプレート のように働きます。

Contrast this with the following make_adder() function, in which the returned anonymous function contains a reference to a lexical variable outside the scope of that function itself. Such a reference requires that Perl return a proper closure, thus locking in for all time the value that the lexical had when the function was created.

それとは対照的に、次の関数 make_adder() では、関数自身のスコープの外側で レキシカル変数に対するリファレンスを持つ無名関数を返します。 そのようなリファレンスは Perl が適切なクロージャを返すように要求するので、 その変数を参照するときはいつでも関数が生成されたときの レキシカルが参照されます。

    sub make_adder {
        my $addpiece = shift;
        return sub { shift() + $addpiece };
    }

    my $f1 = make_adder(20);
    my $f2 = make_adder(555);

Now $f1->($n) is always 20 plus whatever $n you pass in, whereas $f2->($n) is always 555 plus whatever $n you pass in. The $addpiece in the closure sticks around.

これで、$f1->($n) は それに渡した $n に対して常に 20 を加え、 $f2->($n) は渡された $n に常に 555 を加えます。 クロージャの中にある $addpiece が仕事をしています。

Closures are often used for less esoteric purposes. For example, when you want to pass in a bit of code into a function:

クロージャは、それほど難しくない状況でよく使われます。 たとえば、関数にちょっとしたコードを押しこみたいときがそうです:

    my $line;
    timeout( 30, sub { $line = <STDIN> } );

If the code to execute had been passed in as a string, '$line = <STDIN>', there would have been no way for the hypothetical timeout() function to access the lexical variable $line back in its caller's scope.

もし実行すべきコードが文字列として渡されていたのであれば、 '$line = <STDIN>' としているところは、仮想的な timeout() 関数が アクセスするレキシカル変数 $line を呼び出し元のスコープのものに戻す 手段がなくなってしまいます。

Another use for a closure is to make a variable private to a named subroutine, e.g. a counter that gets initialized at creation time of the sub and can only be modified from within the sub. This is sometimes used with a BEGIN block in package files to make sure a variable doesn't get meddled with during the lifetime of the package:

もう一つのクロージャの使用法は、ある変数を名前つきサブルーチンで プライベート にすることです; 例えば、サブルーチンの作成時に初期化され、 サブルーチン内でのみ変更可能なカウンタです。 これは、パッケージの生存期間中に変数が干渉されることがないように、とき毒 パッケージファイルの BEGIN ブロックで使われます:

    BEGIN {
        my $id = 0;
        sub next_id { ++$id }
    }

This is discussed in more detail in perlsub; see the entry on Persistent Private Variables.

これは perlsub でより詳しく議論されています; Persistent Private Variables のエントリを参照してください。

変数の自殺(variable suicide)って何で、それをどうすれば防げますか?

This problem was fixed in perl 5.004_05, so preventing it means upgrading your version of perl. ;)

この問題は 5.004_05 で修正されたので、防ぐためには perl を バージョンアップします。 ;)

Variable suicide is when you (temporarily or permanently) lose the value of a variable. It is caused by scoping through my() and local() interacting with either closures or aliased foreach() iterator variables and subroutine arguments. It used to be easy to inadvertently lose a variable's value this way, but now it's much harder. Take this code:

変数の自殺とは、(一時的にしろ、恒久的にしろ)変数の値を失ったときのことを 指します。 これは、クロージャ、もしくは別名つけされた foreach イテレータ変数や サブルーチンの引数と相互作用している my() や local() を通した スコープによって引き起こされます。 以前はこのやり方で変数の値をうっかりとなくしてしまうように 使われがちでしたが、現在は非常に難しくなっています。 以下のコードを考えてみましょう:

    my $f = 'foo';
    sub T {
        while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" }
    }

    T;
    print "Finally $f\n";

If you are experiencing variable suicide, that my $f in the subroutine doesn't pick up a fresh copy of the $f whose value is 'foo'. The output shows that inside the subroutine the value of $f leaks through when it shouldn't, as in this output:

もし変数の自殺に遭遇したら、サブルーチン内の my $f は、値が 'foo' である $f の最新のコピーをではありません。 この出力は、漏れてはいけないサブルーチン内の $f の値が漏れていることを 示し、以下のようになります:

    foobar
    foobarbar
    foobarbarbar
    Finally foo

The $f that has "bar" added to it three times should be a new $f my $f should create a new lexical variable each time through the loop. The expected output is:

"bar" を保持している $f は三回 new $f されるべきものです (my $f は、 ループが通る度に新たなレキシカル変数を生成すべきなのです)。 予想される出力は以下のものです:

    foobar
    foobar
    foobar
    Finally foo

{関数, ファイルハンドル, 配列, ハッシュ, メソッド, 正規表現} を渡したり返したりするには?

You need to pass references to these objects. See "Pass by Reference" in perlsub for this particular question, and perlref for information on references.

これらのオブジェクトのリファレンスを渡す必要があります。 "Pass by Reference" in perlsub にある関連した質問と、 perlref にあるリファレンスに関する情報を参照してください。

Passing Variables and Functions

(変数や関数を渡す)

Regular variables and functions are quite easy to pass: just pass in a reference to an existing or anonymous variable or function:

普通の変数や関数はとても簡単に渡せます: 既に存在している変数や関数に対する リファレンスか、無名変数や無名関数に対するリファレンスを渡せばよいのです。

    func( \$some_scalar );

    func( \@some_array  );
    func( [ 1 .. 10 ]   );

    func( \%some_hash   );
    func( { this => 10, that => 20 }   );

    func( \&some_func   );
    func( sub { $_[0] ** $_[1] }   );
Passing Filehandles

As of Perl 5.6, you can represent filehandles with scalar variables which you treat as any other scalar.

Perl 5.6 から、他のスカラと同様にファイルハンドルもスカラ変数で扱えます。

    open my $fh, $filename or die "Cannot open $filename! $!";
    func( $fh );

    sub func {
        my $passed_fh = shift;

        my $line = <$passed_fh>;
    }

Before Perl 5.6, you had to use the *FH or \*FH notations. These are "typeglobs"--see "Typeglobs and Filehandles" in perldata and especially "Pass by Reference" in perlsub for more information.

Perl 5.6 より前では、*FH\*FH といった記法を使う必要があります。 これらは「型グロブ」(typeglob)です; "Typeglobs and Filehandles" in perldata) と "Pass by Reference" in perlsub に詳しい説明があります。

Passing Regexes

(正規表現を渡す)

Here's an example of how to pass in a string and a regular expression for it to match against. You construct the pattern with the qr// operator:

以下の例は、文字列とマッチングする正規表現を渡す方法です。 パターンを qr// 演算子で構築します:

    sub compare($$) {
        my ($val1, $regex) = @_;
        my $retval = $val1 =~ /$regex/;
        return $retval;
    }
    $match = compare("old McDonald", qr/d.*D/i);
Passing Methods

(メソッドを渡す)

To pass an object method into a subroutine, you can do this:

サブルーチンにオブジェクトメソッドを渡すには、以下のようにできます:

    call_a_lot(10, $some_obj, "methname")
    sub call_a_lot {
        my ($count, $widget, $trick) = @_;
        for (my $i = 0; $i < $count; $i++) {
            $widget->$trick();
        }
    }

Or, you can use a closure to bundle up the object, its method call, and arguments:

オブジェクトとそのメソッド呼び出しと引数とをまとめるために クロージャを使うこともできます:

    my $whatnot = sub { $some_obj->obfuscate(@args) };
    func($whatnot);
    sub func {
        my $code = shift;
        &$code();
    }

You could also investigate the can() method in the UNIVERSAL class (part of the standard perl distribution).

UNIVERSAL クラスにある can() メソッドを試すこともできます (これは標準の perl 配布キットの一部です)。

静的変数を作るには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

In Perl 5.10, declare the variable with state. The state declaration creates the lexical variable that persists between calls to the subroutine:

Perl 5.10 では、state で変数を宣言します。 state 宣言は、サブルーチンの呼び出しの間で永続するレキシカル変数を 作成します:

    sub counter { state $count = 1; $count++ }

You can fake a static variable by using a lexical variable which goes out of scope. In this example, you define the subroutine counter, and it uses the lexical variable $count. Since you wrap this in a BEGIN block, $count is defined at compile-time, but also goes out of scope at the end of the BEGIN block. The BEGIN block also ensures that the subroutine and the value it uses is defined at compile-time so the subroutine is ready to use just like any other subroutine, and you can put this code in the same place as other subroutines in the program text (i.e. at the end of the code, typically). The subroutine counter still has a reference to the data, and is the only way you can access the value (and each time you do, you increment the value). The data in chunk of memory defined by $count is private to counter.

スコープ外でレキシカル変数を使うことでスタティック変数を でっち上げることができます。 この例では、サブルーチン counter を定義し、そこでレキシカル変数 $count を使います。 これを BEGIN ブロックで囲っているので、$count はコンパイル時に 定義されますが、BEGIN ブロックの終わりでスコープから外れます。 BEGIN ブロックはまた、サブルーチンとそこで使われている値はコンパイル時に 定義されるので、このサブルーチンはその他のどのサブルーチンからも 使える準備が出来ていて、このコードをプログラムテキスト中の他のサブルーチンと 同様に同じ場所(典型的には、コードの最後)にこのコードを置けることを保証します。 サブルーチン counter は未だにデータへのリファレンスを持っていて、 これが値にアクセスできる唯一の方法です(そしてそうする度に、値が インクリメントされます)。 $count で定義されたメモリの塊にあるデータは counter に プライベートです。

    BEGIN {
        my $count = 1;
        sub counter { $count++ }
    }

    my $start = counter();

    .... # code that calls counter();

    my $end = counter();

In the previous example, you created a function-private variable because only one function remembered its reference. You could define multiple functions while the variable is in scope, and each function can share the "private" variable. It's not really "static" because you can access it outside the function while the lexical variable is in scope, and even create references to it. In this example, increment_count and return_count share the variable. One function adds to the value and the other simply returns the value. They can both access $count, and since it has gone out of scope, there is no other way to access it.

前述の例では、関数でプライベートな変数を作っています; ただ一つの関数だけがこのリファレンスを覚えているからです。 変数がスコープ内にある間に複数の関数を定義でき、各関数は「プライベート」 変数を共有できます。 レキシカル変数がスコープ内ではあるけれども関数の外側から変数にアクセスでき、 それに対するリファレンスすら作成できるため、これは実際には 「静的」変数ではありません。 この例では、increment_countreturn_count は変数を共有しています。 片方の関数が値を加え、もう片方は単に値を返します。 これらは両方とも $count にアクセスでき、スコープ外から離れるため、 これにアクセスするその他の方法はありません。

    BEGIN {
        my $count = 1;
        sub increment_count { $count++ }
        sub return_count    { $count }
    }

To declare a file-private variable, you still use a lexical variable. A file is also a scope, so a lexical variable defined in the file cannot be seen from any other file.

ファイルプライベートな変数を宣言するには、やはりレキシカル変数が使えます。 ファイルもスコープとなるので、あるファイルで定義されたレキシカル変数は その他のファイルからは見えません。

See "Persistent Private Variables" in perlsub for more information. The discussion of closures in perlref may help you even though we did not use anonymous subroutines in this answer. See "Persistent Private Variables" in perlsub for details.

さらなる情報については "Persistent Private Variables" in perlsub を 参照してください。 perlref でのクロージャに関する議論は、この答えには無名サブルーチンは 使っていないですが、助けになるかもしれません。 詳細については "Persistent Private Variables" in perlsub を参照してください。

動的スコープとレキシカル(または静的)スコープとの間の違いは? local() と my() との違いは?

local($x) saves away the old value of the global variable $x and assigns a new value for the duration of the subroutine which is visible in other functions called from that subroutine. This is done at run-time, so is called dynamic scoping. local() always affects global variables, also called package variables or dynamic variables.

local($x) は、グローバル変数 $x の古い値を保存して、 そのサブルーチンから呼び出された関数から参照できる サブルーチンの 存在する間の新たな値を代入します。 これはコンパイル時ではなく、実行時に行われるので、動的スコープと呼ばれます。 local() は常にグローバル変数に対して作用し、 パッケージ変数とか動的変数と呼ばれることもあります。

my($x) creates a new variable that is only visible in the current subroutine. This is done at compile-time, so it is called lexical or static scoping. my() always affects private variables, also called lexical variables or (improperly) static(ly scoped) variables.

my($x) は、現在のサブルーチンにおいてのみ参照できる変数を新たに 生成します。 これはコンパイル時に行われるので、レキシカルスコープだとか 静的スコープと呼ばれます。 my() はプライベート変数に作用し、レキシカル変数とか、(間違って)静的 (スコープを持った)変数と呼ばれることもあります。

For instance:

例を挙げましょう:

    sub visible {
        print "var has value $var\n";
    }

    sub dynamic {
        local $var = 'local';    # new temporary value for the still-global
        visible();              #   variable called $var
    }

    sub lexical {
        my $var = 'private';    # new private variable, $var
        visible();              # (invisible outside of sub scope)
    }

    $var = 'global';

    visible();              # prints global
    dynamic();              # prints local
    lexical();              # prints global

Notice how at no point does the value "private" get printed. That's because $var only has that value within the block of the lexical() function, and it is hidden from the called subroutine.

"private"という値を出力させる方法がないということに注目してください。 これは、$var が関数の lexical() なブロックの内側でのみその値を持っていて、 そこから呼び出されたサブルーチンからは隠されてしまうからです。

In summary, local() doesn't make what you think of as private, local variables. It gives a global variable a temporary value. my() is what you're looking for if you want private variables.

まとめると、local() はあなたがプライベートと考えるようなことをローカルな 変数に対して行うようなことはありません。 これはグローバル変数に一時的な値を与えるだけです。 あなたがプライベート変数を必要としている場合、my() があなたが 探し求めているものです。

このことをより詳しく説明している "Private Variables via my()" in perlsub"Temporary Values via local()" in perlsub を参照してください。

どうやれば同じ名前のレキシカル変数がスコープにあるときに動的変数にアクセスできますか?

If you know your package, you can just mention it explicitly, as in $Some_Pack::var. Note that the notation $::var is not the dynamic $var in the current package, but rather the one in the "main" package, as though you had written $main::var.

自分のパッケージを知っているのなら、これを $Some_Pack::var と明示的に 記述できます。 $::var という記法はカレントパッケージにおける動的な $var ではなく、 "main" パッケージの中にあるそれなのだということに注意してください。

    use vars '$var';
    local $var = "global";
    my    $var = "lexical";

    print "lexical is $var\n";
    print "global  is $main::var\n";

Alternatively you can use the compiler directive our() to bring a dynamic variable into the current lexical scope.

あるいは、動的変数を現在のレキシカルスコープにもたらすために、コンパイラ 指示子 our() を使えます。

    require 5.006; # our() did not exist before 5.6
    use vars '$var';

    local $var = "global";
    my $var    = "lexical";

    print "lexical is $var\n";

    {
        our $var;
        print "global  is $var\n";
    }

深い束縛(deep binding)と浅い束縛(shallow binding)との間の違いとは?

In deep binding, lexical variables mentioned in anonymous subroutines are the same ones that were in scope when the subroutine was created. In shallow binding, they are whichever variables with the same names happen to be in scope when the subroutine is called. Perl always uses deep binding of lexical variables (i.e., those created with my()). However, dynamic variables (aka global, local, or package variables) are effectively shallowly bound. Consider this just one more reason not to use them. See the answer to "What's a closure?".

深い束縛では、無名サブルーチンに置かれているレキシカル変数は そのサブルーチンが生成されたときのものと同一のものになります。 浅い束縛では、これはそのサブルーチンが呼び出されたときのスコープに 存在している同じ名前を持った変数のどれか、になります。 Perl はレキシカル変数(つまり、my() によって作られるもの)に対しては 常に深い束縛を使います。 それに対し動的変数(つまりグローバル変数か、ローカル変数か、 パッケージ変数)では、浅い束縛がなされます。 こういったものを使わない理由がもう一つあります。 その答えは "What's a closure?" を参照してください。

なぜ "my($foo) = <$fh>;" が正しく動作しないのでしょうか?

my() and local() give list context to the right hand side of =. The <$fh> read operation, like so many of Perl's functions and operators, can tell which context it was called in and behaves appropriately. In general, the scalar() function can help. This function does nothing to the data itself (contrary to popular myth) but rather tells its argument to behave in whatever its scalar fashion is. If that function doesn't have a defined scalar behavior, this of course doesn't help you (such as with sort()).

my()local()= の右辺に対してリストコンテキストを与えます。 読み込み操作 <$fh> は Perlの関数や演算子の多くと同じくそれが呼び出されたときの コンテキストを見分けることができて、それに応じて適切に振る舞います。 一般的には、scalar() 関数が助けになるでしょう。 その関数は(一般的な神話とは反して)引数となるデータに対して 何も行いませんが、引数がスカラとして振る舞うように指示します。 関数のスカラ時の振る舞いが定義されていないのであれば、 当然ながらこれはあなたの助けにはなりません(sort() がそうです)。

To enforce scalar context in this particular case, however, you need merely omit the parentheses:

しかしながら特定のケースにおいては、スカラコンテキストを強制するために 単に括弧を取り除く必要があります:

    local($foo) = <$fh>;        # WRONG
    local($foo) = scalar(<$fh>);   # ok
    local $foo  = <$fh>;        # right

You should probably be using lexical variables anyway, although the issue is the same here:

これと同じ問題があるものの、なんにしろレキシカル変数を使うべきでしょう。

    my($foo) = <$fh>;    # WRONG
    my $foo  = <$fh>;    # right

組み込みの関数や演算子、メソッドを再定義するには?

Why do you want to do that? :-)

なんだってそんなことをしたがるのですか? :-)

If you want to override a predefined function, such as open(), then you'll have to import the new definition from a different module. See "Overriding Built-in Functions" in perlsub.

open() のようなあらかじめ定義されている関数をオーバーライドしたいのであれば、 異なるモジュールから新しい定義をインポートする必要があります。 "Overriding Built-in Functions" in perlsub を参照してください。

If you want to overload a Perl operator, such as + or **, then you'll want to use the use overload pragma, documented in overload.

+** のような Perl の演算子をオーバーロードしたいのであれば overload で説明されているような use overload プラグマを 使いたくなるでしょう。

If you're talking about obscuring method calls in parent classes, see "Overridden Methods" in perltoot.

親クラスにおける不明瞭なメソッド呼び出しについて考えているのなら、 "Overridden Methods" in perltoot を参照してください。

関数呼び出しを &foo で行ったときと foo() で行ったときとの違いはなんですか?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

Calling a subroutine as &foo with no trailing parentheses ignores the prototype of foo and passes it the current value of the argument list, @_. Here's an example; the bar subroutine calls &foo, which prints its arguments list:

&foo の形で、引き続くかっこなしでサブルーチンを呼び出すと、 foo のプロトタイプを無視して、引数リスト @_ の現在の値を渡します。 以下は例です: bar サブルーチンは、引数リストを表示する &foo を 呼び出します:

    sub bar { &foo }

    sub foo { print "Args in foo are: @_\n" }

    bar( qw( a b c ) );

When you call bar with arguments, you see that foo got the same @_:

bar を引数付きで呼び出した場合、foo も同じ @_ を得ます:

    Args in foo are: a b c

Calling the subroutine with trailing parentheses, with or without arguments, does not use the current @_ and respects the subroutine prototype. Changing the example to put parentheses after the call to foo changes the program:

サブルーチンをかっこ付きで呼び出した場合、引数のありなしに関わらず、 現在の @_ は使わずに、サブルーチンのプロトタイプに従います。 foo を呼び出すときにかっこをつけるように例を変更します:

    sub bar { &foo() }

    sub foo { print "Args in foo are: @_\n" }

    bar( qw( a b c ) );

Now the output shows that foo doesn't get the @_ from its caller.

今度は、foo が呼び出し元から @_ を得ていないことが分かります:

    Args in foo are:

The main use of the @_ pass-through feature is to write subroutines whose main job it is to call other subroutines for you. For further details, see perlsub.

@_ パススルー機能の主な利用法は、他のサブルーチンを呼び出すのが 主な仕事であるサブルーチンを書くためです。 更なる詳細については、perlsub を参照してください。

switch 文や case 文を作るには?

In Perl 5.10, use the given-when construct described in perlsyn:

Perl 5.10 では、perlsyn に記述されている given-when 構造を 使ってください:

    use 5.010;

    given ( $string ) {
        when( 'Fred' )        { say "I found Fred!" }
        when( 'Barney' )      { say "I found Barney!" }
        when( /Bamm-?Bamm/ )  { say "I found Bamm-Bamm!" }
        default               { say "I don't recognize the name!" }
    };

If one wants to use pure Perl and to be compatible with Perl versions prior to 5.10, the general answer is to use if-elsif-else:

もしピュア Perl を使って、バージョン 5.10 より前と互換性を持たせたいなら、 構造文を書くための一般的な答えは if-elsif-else を使うことです:

    for ($variable_to_test) {
        if    (/pat1/)  { }     # do something
        elsif (/pat2/)  { }     # do something else
        elsif (/pat3/)  { }     # do something else
        else            { }     # default
    }

Here's a simple example of a switch based on pattern matching, lined up in a way to make it look more like a switch statement. We'll do a multiway conditional based on the type of reference stored in $whatchamacallit:

以下の例は、パターンマッチングに基づいた単純な switch の例です。 $whatchamacallit に格納されたリファレンスの型に基づいて多様なやり方の 条件判断を行っています:

    SWITCH: for (ref $whatchamacallit) {

        /^$/           && die "not a reference";

        /SCALAR/       && do {
                        print_scalar($$ref);
                        last SWITCH;
                      };

        /ARRAY/        && do {
                        print_array(@$ref);
                        last SWITCH;
                      };

        /HASH/        && do {
                        print_hash(%$ref);
                        last SWITCH;
                      };

        /CODE/        && do {
                        warn "can't print function ref";
                        last SWITCH;
                      };

        # DEFAULT

        warn "User defined type skipped";

    }

See perlsyn for other examples in this style.

このスタイルに関するその他の例については perlsyn を参照してください。

Sometimes you should change the positions of the constant and the variable. For example, let's say you wanted to test which of many answers you were given, but in a case-insensitive way that also allows abbreviations. You can use the following technique if the strings all start with different characters or if you want to arrange the matches so that one takes precedence over another, as "SEND" has precedence over "STOP" here:

定数や変数の位置を変えた方が良いことがあるかもしれません。 たとえば、与えられたたくさんの答についてテストを行いたいとしましょう; この場合大小文字を無視することもできますし、略記することもあります。 もし全て文字列が異なるキャラクターで始まっていたり、 "SEND""STOP" より高い優先順位を持つように調整したいのなら マッチの順序をアレンジしたいのであれば以下に示すようなテクニックを 使うことができます。

    chomp($answer = <>);
    if    ("SEND"  =~ /^\Q$answer/i) { print "Action is send\n"  }
    elsif ("STOP"  =~ /^\Q$answer/i) { print "Action is stop\n"  }
    elsif ("ABORT" =~ /^\Q$answer/i) { print "Action is abort\n" }
    elsif ("LIST"  =~ /^\Q$answer/i) { print "Action is list\n"  }
    elsif ("EDIT"  =~ /^\Q$answer/i) { print "Action is edit\n"  }

A totally different approach is to create a hash of function references.

まったく異なるアプローチに、関数のリファレンスのハッシュを作成するという やり方があります。

    my %commands = (
        "happy" => \&joy,
        "sad",  => \&sullen,
        "done"  => sub { die "See ya!" },
        "mad"   => \&angry,
    );

    print "How are you? ";
    chomp($string = <STDIN>);
    if ($commands{$string}) {
        $commands{$string}->();
    } else {
        print "No such command: $string\n";
    }

Starting from Perl 5.8, a source filter module, Switch, can also be used to get switch and case. Its use is now discouraged, because it's not fully compatible with the native switch of Perl 5.10, and because, as it's implemented as a source filter, it doesn't always work as intended when complex syntax is involved.

Perl 5.8 から、ソースフィルタモジュール Switch も switch と case を 使うために使えます。 Perl 5.10 には完全互換のネイティブな switch があり、また、これはソース フィルタとして実装されているので、複雑な文法の場合はいつも想定通りに 動くとは限らないからです。

どうすれば未定義な変数, 関数, メソッドに対するアクセスを捕捉できますか?

The AUTOLOAD method, discussed in "Autoloading" in perlsub and "AUTOLOAD: Proxy Methods" in perltoot, lets you capture calls to undefined functions and methods.

"Autoloading" in perlsub"AUTOLOAD: Proxy Methods" in perltoot で 言及されている AUTOLOAD メソッドは、未定義な関数やメソッドに対する 呼び出しを捕捉させてくれます。

When it comes to undefined variables that would trigger a warning under use warnings, you can promote the warning to an error.

use warnings が有効なときに警告の引き金になるような未定義変数への アクセスがあったとき、警告をエラーに昇格させることができます。

    use warnings FATAL => qw(uninitialized);

なぜ同じファイルにあるメソッドが見つけられないのでしょうか?

Some possible reasons: your inheritance is getting confused, you've misspelled the method name, or the object is of the wrong type. Check out perltoot for details about any of the above cases. You may also use print ref($object) to find out the class $object was blessed into.

幾つかの理由が考えられます: あなたが継承したものが混乱していているか、 メソッド名を間違えたか、あるいはオブジェクトの型が間違っていたか。 上記の場合に関する詳細は perltoot をチェックしてみてください。 $object が bless されているクラスは print ref($object) として 見分けることができます。

Another possible reason for problems is that you've used the indirect object syntax (eg, find Guru "Samy") on a class name before Perl has seen that such a package exists. It's wisest to make sure your packages are all defined before you start using them, which will be taken care of if you use the use statement instead of require. If not, make sure to use arrow notation (eg., Guru->find("Samy")) instead. Object notation is explained in perlobj.

もう一つありうる理由は、Perl がパッケージを見いだす前にクラス名を使った 間接オブジェクト構文(find Guru "Samy" のようなもの)を使ったためでしょう。 パッケージは、それを使うよりも前に全てが定義されているようにします。 これは require 文ではなく use 文を使えば考慮されます。 あるいは、代わりに矢印記法(arrow notation、 Guru->find("Samy") のようなもの)を使うようにしてください。 オブジェクトの記法は perlobj で説明されています。

Make sure to read about creating modules in perlmod and the perils of indirect objects in "Method Invocation" in perlobj.

モジュールの作り方については perlmod を、間接オブジェクトの問題点に ついては "WARNING" in perlobj を確認してください。

カレントのパッケージや呼び出しパッケージはどうすればわかりますか?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

To find the package you are currently in, use the special literal __PACKAGE__, as documented in perldata. You can only use the special literals as separate tokens, so you can't interpolate them into strings like you can with variables:

今いるパッケージを知るには、perldata に記述されている特殊リテラル __PACKAGE__ を使ってください。 特殊リテラルは独立したトークンとしてのみ使えるので、変数のように 文字列に展開できません:

    my $current_package = __PACKAGE__;
    print "I am in package $current_package\n";

If you want to find the package calling your code, perhaps to give better diagnostics as Carp does, use the caller built-in:

あるコードを呼び出したパッケージを知りたい場合 (おそらく Carp のように よりよい診断メッセージのためでしょう) caller 組み込み関数を 使ってください:

    sub foo {
        my @args = ...;
        my( $package, $filename, $line ) = caller;

        print "I was called from package $package\n";
        );

By default, your program starts in package main, so you will always be in some package.

デフォルトでは、プログラムはパッケージ main で開始されるので、 いつもなんらかのパッケージ内にいるはずです。

This is different from finding out the package an object is blessed into, which might not be the current package. For that, use blessed from Scalar::Util, part of the Standard Library since Perl 5.8:

これはオブジェクトが bless されているパッケージを知ることとは違います; これは現在のパッケージではないかもしれません。 この目的のためには、Perl 5.8 から標準ライブラリの一部となっている Scalar::Utilblessed を使ってください:

    use Scalar::Util qw(blessed);
    my $object_package = blessed( $object );

Most of the time, you shouldn't care what package an object is blessed into, however, as long as it claims to inherit from that class:

しかし、ほとんどの場合では、オブジェクトがそのクラスから継承していると 主張している限りは、どのパッケージが bless したかを 気にするべきではありません:

    my $is_right_class = eval { $object->isa( $package ) }; # true or false

And, with Perl 5.10 and later, you don't have to check for an inheritance to see if the object can handle a role. For that, you can use DOES, which comes from UNIVERSAL:

また、Perl 5.10 以降では、オブジェクトがロールを扱うかどうかを見るために 継承をチェックする必要はありません。 このために、UNIVERSAL にある DOES を使えます:

    my $class_does_it = eval { $object->DOES( $role ) }; # true or false

You can safely replace isa with DOES (although the converse is not true).

安全に isaDOES に置き換えられます (しかし逆は真ではありません)。

Perl プログラムの大きなブロックをコメントアウトするには?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with =cut, ending the Pod section:

Perl の複数行をコメントアウトするための、汚いけれども簡単な方法は、 コメントアウトしたい部分を Pod 指示子で囲むことです。 これらの指示子は、行の先頭、かつ、Perl が新しい文が始まると 想定する場所に置く必要があります(従って、# コメントのように文の途中には 置けません)。 Pod セクションの終了を示す =cut でコメントを終了します:

    =pod

    my $object = NotGonnaHappen->new();

    ignored_sub();

    $wont_be_assigned = 37;

    =cut

The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, you're multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.

汚いけれども簡単な方法は、ソースにコメントされたコードを残す予定が ない(つまりいずれ消す)場合にのみうまく働きます。 もし Pod パーサを使うと、複数行コメントは Pod によって表示されます。 よりよい方法は、Pod パーサからも隠すことです。

The =begin directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments with comment. End the comment using =end with the same label. You still need the =cut to go back to Perl code from the Pod comment:

=begin 指示子で、段落を特定の目的のためにマークできます。 Pod パーサがこれを扱えない場合、単に無視されます。 コメントは comment でラベル付けします。 コメントの終了は同じラベルで =end を使います。 Pod コメントから Perl コードに戻るにはやはり =cut が必要です:

    =begin comment

    my $object = NotGonnaHappen->new();

    ignored_sub();

    $wont_be_assigned = 37;

    =end comment

    =cut

For more information on Pod, check out perlpod and perlpodspec.

Pod に関するさらなる情報については、perlpodperlpodspec を 調べてください。

パッケージをクリアするには?

Use this code, provided by Mark-Jason Dominus:

Mark-Jason Dominus による以下のコードを使います:

    sub scrub_package {
        no strict 'refs';
        my $pack = shift;
        die "Shouldn't delete main package"
            if $pack eq "" || $pack eq "main";
        my $stash = *{$pack . '::'}{HASH};
        my $name;
        foreach $name (keys %$stash) {
            my $fullname = $pack . '::' . $name;
            # Get rid of everything with that name.
            undef $$fullname;
            undef @$fullname;
            undef %$fullname;
            undef &$fullname;
            undef *$fullname;
        }
    }

Or, if you're using a recent release of Perl, you can just use the Symbol::delete_package() function instead.

あるいは、あなたが使っている Perl が最近のリリースのものであれば、 単に Symbol::delete_package() という関数を代わりに使うことができます。

変数を変数名として使うには?

Beginners often think they want to have a variable contain the name of a variable.

初心者はしばしば変数名が入った変数を使いたいと考えます。

    $fred    = 23;
    $varname = "fred";
    ++$$varname;         # $fred now 24

This works sometimes, but it is a very bad idea for two reasons.

これは 時には 動作します; しかしこれは二つの理由により悪い考えです。

The first reason is that this technique only works on global variables. That means that if $fred is a lexical variable created with my() in the above example, the code wouldn't work at all: you'd accidentally access the global and skip right over the private lexical altogether. Global variables are bad because they can easily collide accidentally and in general make for non-scalable and confusing code.

一つ目の理由は、このテクニックは グローバル変数でのみ動作する からです。 つまり、もし上記の例において $fred が my() で作成されたレキシカル変数の 場合、このコードは全く動作しません; プライベートなレキシカル変数を飛ばして、 思いがけずグローバル変数にアクセスすることになります。 グローバル変数は、簡単に衝突し、一般に拡張性がなく、混乱するコードを 作ることになるので、よくないものです。

Symbolic references are forbidden under the use strict pragma. They are not true references and consequently are not reference-counted or garbage-collected.

シンボリックリファレンスは use strict プラグマの元では禁止されます。 これは真のリファレンスではないので、リファレンスカウントに含まれず、 ガベージゴレクションもされません。

The other reason why using a variable to hold the name of another variable is a bad idea is that the question often stems from a lack of understanding of Perl data structures, particularly hashes. By using symbolic references, you are just using the package's symbol-table hash (like %main::) instead of a user-defined hash. The solution is to use your own hash or a real reference instead.

変数に他の変数の名前を記録するというのがよくない考えであるという 別の理由としては、このような疑問はしばしば Perl のデータ構造、 特にハッシュに関する理解の不足から発生するからです。 シンボリックリファレンスを使うことによって、ユーザー定義のハッシュの代わりに パッケージのシンボルテーブルハッシュ(%main:: など)を使うことができます。 解決法は、代わりに自分自身のハッシュや真のリファレンスを使うことです。

    $USER_VARS{"fred"} = 23;
    my $varname = "fred";
    $USER_VARS{$varname}++;  # not $$varname++

There we're using the %USER_VARS hash instead of symbolic references. Sometimes this comes up in reading strings from the user with variable references and wanting to expand them to the values of your perl program's variables. This is also a bad idea because it conflates the program-addressable namespace and the user-addressable one. Instead of reading a string and expanding it to the actual contents of your program's own variables:

ここではシンボリックリファレンスの代わりに %USER_VARS ハッシュを 使っています。 時々これはユーザーから文字列を変数へのリファレンスとして読み込んで、 それを perl プログラムの変数の値として拡張することがあります。 これもよくない考えです; なぜなら、プログラムが指定する名前空間とユーザーが 指定する名前空間を融合させることになるからです。 以下のように文字列を読み込んであなたのプログラムの変数の実際の内容の ために拡張するのではなく:

    $str = 'this has a $fred and $barney in it';
    $str =~ s/(\$\w+)/$1/eeg;          # need double eval

it would be better to keep a hash around like %USER_VARS and have variable references actually refer to entries in that hash:

%USER_VARS のようなハッシュを保存し、このハッシュのエントリを参照する 変数リファレンスを持つよりよい方法です:

    $str =~ s/\$(\w+)/$USER_VARS{$1}/g;   # no /e here at all

That's faster, cleaner, and safer than the previous approach. Of course, you don't need to use a dollar sign. You could use your own scheme to make it less confusing, like bracketed percent symbols, etc.

これは前述の手法よりも、より高速で、より明快で、より安全です。 もちろん、ドル記号を使う必要はありません。 パーセント記号で囲むなどのより混乱しにくい独自のスキームを使えます。

    $str = 'this has a %fred% and %barney% in it';
    $str =~ s/%(\w+)%/$USER_VARS{$1}/g;   # no /e here at all

Another reason that folks sometimes think they want a variable to contain the name of a variable is that they don't know how to build proper data structures using hashes. For example, let's say they wanted two hashes in their program: %fred and %barney, and that they wanted to use another scalar variable to refer to those by name.

人々が時々変数名が入った変数を欲しがるもう一つの理由は、 ハッシュを使った適切なデータ構造を構築する方法を知らないからです。 例えば、プログラムで %fred と %barney が必要で、 さらにこれらを名前で参照するスカラへ変数が必要だとします。

    $name = "fred";
    $$name{WIFE} = "wilma";     # set %fred

    $name = "barney";
    $$name{WIFE} = "betty";    # set %barney

This is still a symbolic reference, and is still saddled with the problems enumerated above. It would be far better to write:

これはやはりシンボリックリファレンスで、やはり上記の問題を抱えたままです。 以下のように書けば遥かに改善します:

    $folks{"fred"}{WIFE}   = "wilma";
    $folks{"barney"}{WIFE} = "betty";

And just use a multilevel hash to start with.

そして始めるのに単に多段ハッシュを使います。

The only times that you absolutely must use symbolic references are when you really must refer to the symbol table. This may be because it's something that one can't take a real reference to, such as a format name. Doing so may also be important for method calls, since these always go through the symbol table for resolution.

唯一あなたが完全にシンボリックリファレンスを 使わなければならない 場合は、 シンボルテーブルに対するリファレンスが必要なときだけです。 これは、フォーマット名といったものに対する真のリファレンスを得ることが できないからです。 そうすることはメソッド呼び出しのためにも重要です; なぜなら名前解決のために シンボルテーブルを使うからです。

In those cases, you would turn off strict 'refs' temporarily so you can play around with the symbol table. For example:

これらの場合、一時的に strict 'refs' にしてシンボルテーブルを 使うようにできます。 例えば:

    @colors = qw(red blue green yellow orange purple violet);
    for my $name (@colors) {
        no strict 'refs';  # renege for the block
        *$name = sub { "<FONT COLOR='$name'>@_</FONT>" };
    }

All those functions (red(), blue(), green(), etc.) appear to be separate, but the real code in the closure actually was compiled only once.

これら(red(), blue(), green() など)の関数全ては別々に現れますが、 クロージャの中の実際のコードは一回だけコンパイルされます。

So, sometimes you might want to use symbolic references to manipulate the symbol table directly. This doesn't matter for formats, handles, and subroutines, because they are always global--you can't use my() on them. For scalars, arrays, and hashes, though--and usually for subroutines-- you probably only want to use hard references.

シンボルテーブルを直接操作するためにシンボリックリファレンスを 使いたくなることがあるかもしれません。 これには、フォーマット、ハンドル、サブルーチンには関係ありません; これらは 常にグローバルだからです--これらに my() を使うことはできません。 おそらく、スカラ、配列、ハッシュのために--そして普通はサブルーチンの ために--だけ、ハードリファレンスが必要でしょう。

"bad interpreter" とはどういう意味ですか?

(contributed by brian d foy)

(brian d foy によって寄贈されました)

The "bad interpreter" message comes from the shell, not perl. The actual message may vary depending on your platform, shell, and locale settings.

"bad interpreter" というメッセージは perl ではなく、シェルが出力しています。 実際のメッセージはプラットフォーム、シェル、ロケール設定によって 様々です。

If you see "bad interpreter - no such file or directory", the first line in your perl script (the "shebang" line) does not contain the right path to perl (or any other program capable of running scripts). Sometimes this happens when you move the script from one machine to another and each machine has a different path to perl--/usr/bin/perl versus /usr/local/bin/perl for instance. It may also indicate that the source machine has CRLF line terminators and the destination machine has LF only: the shell tries to find /usr/bin/perl<CR>, but can't.

"bad interpreter - no such file or directory" と表示されたら、perl スクリプトの最初の行 ("#!" 行) に perl (あるいはスクリプトを実行する 機能のあるその他のプログラム) への正しいパスが含まれていません。 スクリプトをあるマシンから、perl のパスが異なる -- 例えば /usr/bin/perl と /usr/local/bin/perl -- 他のマシンに移動させた場合に時々起こります。 これはまた、元のマシンの行終端が CRLF で、移動先のマシンが LF のみの場合にも 起こります; シェルが /usr/bin/perl<CR> を探そうとしますが、失敗します。

If you see "bad interpreter: Permission denied", you need to make your script executable.

"bad interpreter: Permission denied" と表示されたら、スクリプトを 実行可能にする必要があります。

In either case, you should still be able to run the scripts with perl explicitly:

どちらの場合でも、明示的に perl でスクリプトを実行できるようにするべきです:

    % perl script.pl

If you get a message like "perl: command not found", perl is not in your PATH, which might also mean that the location of perl is not where you expect it so you need to adjust your shebang line.

"perl: command not found" のようなメッセージが出た場合、perl が PATH に ありません; つまりおそらくは perl の位置があなたの想定している 場所ではないことも意味しているので、#! 行を調整する必要があります。

AUTHOR AND COPYRIGHT

Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved.

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 this file 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.