=encoding euc-jp =head1 NAME =begin original perlfaq7 - General Perl Language Issues =end original perlfaq7 - Perl 言語一般に関することがら =head1 DESCRIPTION =begin original This section deals with general Perl language issues that don't clearly fit into any of the other sections. =end original このセクションでは、他のセクションにはきっちりとあてはまらないような Perl 言語に関する一般的な事柄を扱います。 =head2 Can I get a BNF/yacc/RE for the Perl language? (Perl のための BNF/yacc/RE は入手できますか?) =begin original 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. =end original BNFはありませんが、もし多少の勇気を持ちあわせているのであれば 配布ソースに含まれている perly.y にある yacc 文法をいじくりまわすことが できます。 その文法は非常に賢い字句解析ルーチンに依存したものなので、 toke.c を眺める準備もしておきましょう。 =begin original 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." =end original reduce Chaim Frenkel の言葉を借りればこうです: 「Perl の文法は BNF まで縮小することができない。 perl の構文解析の作業は yacc、字句解析器、煙と鏡とに分配される。」 =head2 What are all these $@%&* punctuation signs, and how do I know when to use them? ($@%&* のマークはなんですか? これらをいつ使えばいいのかを知るにはどうすればいいですか?) =begin original They are type specifiers, as detailed in L: =end original これらは型指定子(type specifiers)で、L で説明されています: =begin original $ 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. =end original $ スカラ値(数値、文字列、リファレンス)に対するもの @ 配列に対するもの % ハッシュ(連想配列)に対するもの & サブルーチン(またの名を関数、手続き、メソッド)に対するもの * シンボル名に対する全ての型。バージョン 4 ではポインタのように 使われていましたが、新しい perl ではリファレンスが使えます。 =begin original There are couple of other symbols that you're likely to encounter that aren't really type specifiers: =end original 実際には型指定子として見ることはないであろう二つのものが この他にもあります: =begin original <> are used for inputting a record from a filehandle. \ takes a reference to something. =end original <> あるファイルハンドルからレコードを入力するのに使われます。 \ なにかのリファレンスを取ります。 =begin original Note that is I the type specifier for files nor the name of the handle. It is the C<< <> >> operator applied to the handle FILE. It reads one line (well, record--see L>) from the handle FILE in scalar context, or I lines in list context. When performing open, close, or any other operation besides C<< <> >> on files, or even when talking about the handle, do I use the brackets. These are correct: C, C and "copying from STDIN to FILE". =end original は、ファイルに対する型指定子にもハンドルの名前の I<どちらでもない> ということに注意してください。 これはハンドル FILE に対する C<< <> >> 演算子です。 一行(そう、レコードですね。L> を参照してください) を FILE というハンドルからスカラコンテキストで読み出します。 リストコンテキストの場合は B<全ての> 行を読み出します。 ファイルの C<< <> >> に関係する open、close などの操作を行うときには、 ハンドルについて行っている場合であっても アングルブラケットを使っては B<いけません>。 C, C や "copying from STDIN to FILE" は 正しいものなのです。 =head2 Do I always/never have to quote my strings or use semicolons and commas? (文字列では常にクォートする/決してクォートしない必要があるのでしょうか? また、セミコロンやカンマについては?) =begin original Normally, a bareword doesn't need to be quoted, but in most cases probably should be (and must be under C). But a hash key consisting of a simple word (that isn't the name of a defined subroutine) and the left-hand operand to the C<< => >> operator both count as though they were quoted: =end original 通常は、裸の単語(barewords)はクォートする必要はありませんが、 ほとんど場合はクォートすべきでしょう(そして、C しているときは しなければなりません)。 しかし、単純な単語(サブルーチンの名前として定義されていないもの)から 構成されるハッシュと、C<< => >> 演算子の左側にあるオペランドは 両方ともクォートされているとみなされます: This is like this ------------ --------------- $foo{line} $foo{'line'} bar => stuff 'bar' => stuff =begin original The final semicolon in a block is optional, as is the final comma in a list. Good style (see L) says to put them in except for one-liners: =end original ブロックの最後にあるセミコロンは、リストの最後にあるカンマと同じく 省略可能です。 良いスタイル(L を参照)は一行野郎(one-liners)でなければ それらを使うようにしましょうと言っています。 if ($whoops) { exit 1 } @nums = (1, 2, 3); if ($whoops) { exit 1; } @lines = ( "There Beren came from mountains cold", "And lost he wandered under leaves", ); =head2 How do I skip some return values? (戻り値の一部をスキップするには?) =begin original One way is to treat the return values as a list and index into it: =end original 方法の一つは、戻り値をリストとみなして、それに添え字づけするというものです: $dir = (getpwnam($user))[7]; =begin original Another way is to use undef as an element on the left-hand-side: =end original もう一つのやりかたは、左辺の要素として undef を使うというものです: ($dev, $ino, undef, undef, $uid, $gid) = stat($file); =begin original You can also use a list slice to select only the elements that you need: =end original 必要な要素だけを選択するために、リストスライスも使えます: ($dev, $ino, $uid, $gid) = ( stat($file) )[0,1,4,5]; =head2 How do I temporarily block warnings? (一時的に警告をブロックするには?) =begin original If you are running Perl 5.6.0 or better, the C pragma allows fine control of what warning are produced. See L for more details. =end original Perl 5.6.0 以降を使っているなら、C プラグマで どんな警告を生成するかをうまく制御できます。 詳細については L を参照してください。 { no warnings; # temporarily turn off warnings $a = $b + $c; # I know these might be undef } =begin original 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 L for the complete details, including the category names and hierarchy. =end original さらに、警告の分野毎に警告を有効または無効にできます。 無視したいカテゴリを無効にしても、残りのカテゴリの警告は受けられます。 カテゴリ名と階層を含む、完全な詳細については L を 参照してください。 { no warnings 'uninitialized'; $a = $b + $c; } =begin original If you have an older version of Perl, the C<$^W> variable (documented in L) controls runtime warnings for a block: =end original より古いバージョンの場合は、変数 C<$^W>(L に説明があります)は 実行時の警告のブロックを制御します: =begin original { local $^W = 0; # temporarily turn off warnings $a = $b + $c; # I know these might be undef } =end original { local $^W = 0; # 一時的に警告をオフにする $a = $b + $c; # これらが undef かもしれないことを知っている } =begin original Note that like all the punctuation variables, you cannot currently use my() on C<$^W>, only local(). =end original 全ての句読点変数(punctuation variable)と同様、現時点では C<$^W> に対して my() を使うことはできず、local() だけしか使えないということに 注意してください。 =head2 What's an extension? (エクステンションてなんですか?) =begin original An extension is a way of calling compiled C code from Perl. Reading L is a good place to learn more about extensions. =end original エクステンションとは、Perl からコンパイル済みの C コードを呼び出すための 方法です。 エクステンションについて知るには L を読むのが良いでしょう。 =head2 Why do Perl operators have different precedence than C operators? (なぜ Perl の演算子は C の演算子とは異なった優先順位を持っているのでしょうか?) =begin original 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 L. =end original 実際はそうではありません。Perl に持ち込まれたCの演算子はすべて、 C と Perl とで同じ優先順位を持っています。 問題は、C にはない演算子、特にその右辺に対してつねにリストコンテキストを 与える関数、例えば print、chmod、exec などです。 そういった関数は「リスト演算子」と呼ばれ、 L にある優先順位テーブルにあります。 =begin original A common mistake is to write: =end original ありがちな間違いは以下のようにのように書いてしまうことです: unlink $file || die "snafu"; =begin original This gets interpreted as: =end original これは以下のように解釈されます: unlink ($file || die "snafu"); =begin original To avoid this problem, either put in extra parentheses or use the super low precedence C operator: =end original この問題を避けるためには、余計な括弧をつけるかより優先順位の低い C 演算子を使うようにします: (unlink $file) || die "snafu"; unlink $file or die "snafu"; =begin original The "English" operators (C, C, C, and C) deliberately have precedence lower than that of list operators for just such situations as the one above. =end original "English" 演算子(C, C, C, C) は先に説明している 同じ働きをするリスト演算子よりも低い優先順位を故意に持たされています。 =begin original Another operator with surprising precedence is exponentiation. It binds more tightly even than unary minus, making C<-2**2> produce a negative not a positive four. It is also right-associating, meaning that C<2**3**2> is two raised to the ninth power, not eight squared. =end original もう一つの、びっくりするような優先順位を持っている演算子は べき乗(exponentiation)です。 これは単項のマイナスよりも強く結び付くので、C<-2**2> はプラス 4 ではなく、 マイナス 4 を生成します。 この演算子は右結合するので、C<2**3**2> は 8 の 2 乗ではなく、 2 の 9 乗です。 =begin original Although it has the same precedence as in C, Perl's C operator produces an lvalue. This assigns $x to either $a or $b, depending on the trueness of $maybe: =end original C と同じ優先順位を持っているにも関らず、Perl では C 演算子は 左辺値を作り出します。 以下の代入では、$maybe の値に応じて、$a か $b のいずれかに $x の値を代入します: ($maybe ? $a : $b) = $x; =head2 How do I declare/create a structure? (構造体を宣言したり生成するには?) =begin original In general, you don't "declare" a structure. Just use a (probably anonymous) hash reference. See L and L for details. Here's an example: =end original 一般的には、構造体を“宣言”することはありません。 単に(おそらくは無名の)ハッシュリファレンスを使うだけです。 詳しくは Lと L を参照してください。 例を挙げましょう: $person = {}; # new anonymous hash $person->{AGE} = 24; # set field AGE to 24 $person->{NAME} = "Nat"; # set field NAME to "Nat" =begin original If you're looking for something a bit more rigorous, try L. =end original もうちょっと正確ななにかを求めているのなら、 L に挑戦してみてください。 =head2 How do I create a module? (モジュールを作成するには?) =begin original (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original L, L, L explain modules in all the gory details. L gives a brief overview of the process along with a couple of suggestions about style. =end original L, L, L はモジュールに関する全ての 不愉快な詳細について説明しています。 L にはこのプロセスに関する大まかな概要と、スタイルに関する いくつかの忠告があります。 =begin original If you need to include C code or C library interfaces in your module, you'll need h2xs. h2xs will create the module distribution structure and the initial interface files you'll need. L and L explain the details. =end original もしモジュールに C コードや C ライブラリインターフェースを含めたいなら、 h2xs が必要です。 h2xs は必要になるモジュール配布構造と初期インターフェースファイルを 作成します。 L と L は詳細を説明しています。 =begin original If you don't need to use C code, other tools such as ExtUtils::ModuleMaker and Module::Starter, can help you create a skeleton module distribution. =end original C のコードを使う必要がないのなら、ExtUtils::ModuleMaker や Module::Starter といったツールが、モジュール配布の骨格を作るのを 助けてくれます。 =begin original You may also want to see Sam Tregar's "Writing Perl Modules for CPAN" ( http://apress.com/book/bookDisplay.html?bID=14 ) which is the best hands-on guide to creating module distributions. =end original モジュール配布を作成するための最良の実践型ガイドである、Sam Tregar による "Writing Perl Modules for CPAN" ( http://apress.com/book/bookDisplay.html?bID=14 ) を見るのもよいでしょう。 =head2 How do I adopt or take over a module already on CPAN? (すでに CPAN にあるモジュールを引き継ぐには?) =begin original (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original The full answer to this can be found at http://cpan.org/modules/04pause.html#takeover =end original これに対する完全な答えは以下にあります: http://cpan.org/modules/04pause.html#takeover =begin original The easiest way to take over a module is to have the current module maintainer either make you a co-maintainer or transfer the module to you. =end original モジュールを引き継ぐのに一番簡単な方法は、現在のモジュールのメンテナに 連絡して、共同メンテナにしてもらうか、モジュールを引き渡してもらう ことです。 =begin original If you can't reach the author for some reason (e.g. email bounces), the PAUSE admins at modules@perl.org can help. The PAUSE admins treat each case individually. =end original もし何らかの理由(メールが返ってきたなど)で作者と連絡が取れない場合、 PAUSE 管理者である modules@perl.org が助けになるかもしれません。 PAUSE 管理者はそれぞれの場合を個別に扱います。 =over 4 =item =begin original Get a login for the Perl Authors Upload Server (PAUSE) if you don't already have one: http://pause.perl.org =end original まだ持っていないなら、the Perl Authors Upload Server (PAUSE) のアカウントを 取ります: http://pause.perl.org =item =begin original Write to modules@perl.org explaining what you did to contact the current maintainer. The PAUSE admins will also try to reach the maintainer. =end original 現在のメンテナに連絡するためにしたことの説明を modules@perl.org に書きます。 PAUSE 管理者もメンテナに連絡を試みます。 =item =begin original Post a public message in a heavily trafficked site announcing your intention to take over the module. =end original モジュールを引き継ぎたいという意思を表明するために、トラフィックの多い サイトに公的なメッセージを投稿します。 =item =begin original 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. =end original しばらく待ちます。 PAUSE 管理者は、現在のメンテナが休暇中の場合に、あまりに性急に行動したいとは 思いません。 もし私的な通信や公的な投稿に反応がない場合、PAUSE 管理者はモジュールを あなたに移行できます。 =back =head2 How do I create a class? X X (クラスを作るには?) =begin original (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original 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). =end original Perl では、クラスは単なるパッケージで、メソッドは単なるサブルーチンです。 Perl はそれ以上に形式的なことはしませんし、あなたの好きな方法でパッケージを 設定できるようにします (つまり、Perl はあなたのために何の設定もしません)。 =begin original The Perl documentation has several tutorials that cover class creation, including L (Barnyard Object Oriented Tutorial), L (Tom's Object Oriented Tutorial), L (Bag o' Object Tricks), and L. =end original Perl の文書には、 L (Barnyard Object Oriented Tutorial), L (Tom's Object Oriented Tutorial), L (Bag o' Object Tricks), L といった、クラス生成に対応する いくつかのチュートリアルがあります。 =head2 How can I tell if a variable is tainted? (変数が汚染されているかどうかを確かめるには?) =begin original 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 L. =end original CPAN にある (リリース 5.8.0 からは Perl に含まれている) Scalar::Util モジュールの tainted() 関数が使えます。 L も参照してください。 =head2 What's a closure? (クロージャ(closure)ってなんですか?) =begin original Closures are documented in L. =end original クロージャは L に説明があります。 =begin original I 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). =end original B<クロージャ> は、きちんとした定義を持ったコンピュータ科学の用語ですが その意味を説明するのはとても難しいのです。 クロージャは Perl では、そのスコープの外側でもレキシカル変数に対する リファレンスを保持しつづける無名サブルーチンとして実装されています。 これらのレキシカルは、サブルーチンが定義されたときの変数に対して、 魔法のような参照(magically refer)を行います(深い束縛、deep binding)。 =begin original 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. =end original クロージャは、Perl ができるような関数の戻り値として関数それ自身を返す関数を 持つことができるプログラミング言語でもっともよく使われます。 一部の言語では、無名関数を提供しているけれども適切なクロージャを提供する 能力はないということに注意してください。 たとえば Python がそうです。 クロージャに関するより詳しいことは、関数言語に関するなんらかの教科書を みてください。 Scheme はクロージャをサポートするだけでなく、それを推奨している言語です。 =begin original Here's a classic non-closure function-generating function: =end original 以下は、古典的な、クロージャではない関数を生成する関数です: sub add_function_generator { return sub { shift() + shift() }; } $add_sub = add_function_generator(); $sum = $add_sub->(4,5); # $sum is 9 now. =begin original 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 I with some customization slots left out to be filled later. =end original add_function_generator() が返した無名サブルーチンは技術的には クロージャではありません。 なぜなら、あれはスコープの外側で参照するようなレキシカルがないからです。 クロージャを使うことによって、後で埋めることのできるカスタマイズ可能な 幾つかのスロットを持つ B<関数テンプレート> のように働きます。 =begin original 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. =end original それとは対照的に、次の関数 make_adder() では、関数自身のスコープの外側で レキシカル変数に対するリファレンスを持つ無名関数を返します。 そのようなリファレンスは Perl が適切なクロージャを返すように要求するので、 その変数を参照するときはいつでも関数が生成されたときの レキシカルが参照されます。 sub make_adder { my $addpiece = shift; return sub { shift() + $addpiece }; } $f1 = make_adder(20); $f2 = make_adder(555); =begin original Now C<&$f1($n)> is always 20 plus whatever $n you pass in, whereas C<&$f2($n)> is always 555 plus whatever $n you pass in. The $addpiece in the closure sticks around. =end original これで、C<&$f1($n)> は それに渡した $n に対して常に 20 を加え、 C<&$f2($n)> は渡された $n に常に 555 を加えます。 クロージャの中にある $addpiece が仕事をしています。 =begin original Closures are often used for less esoteric purposes. For example, when you want to pass in a bit of code into a function: =end original クロージャは、それほど難しくない状況でよく使われます。 たとえば、関数にちょっとしたコードを押しこみたいときがそうです: my $line; timeout( 30, sub { $line = } ); =begin original If the code to execute had been passed in as a string, C<< '$line = ' >>, there would have been no way for the hypothetical timeout() function to access the lexical variable $line back in its caller's scope. =end original もし実行すべきコードが文字列として渡されていたのであれば、 C<< '$line = ' >> としているところは、仮想的な timeout() 関数が アクセスするレキシカル変数 $line を呼び出し元のスコープのものに戻す 手段がなくなってしまいます。 =begin original Another use for a closure is to make a variable I 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: =end original もう一つのクロージャの使用法は、ある変数を名前つきサブルーチンで I<プライベート> にすることです; 例えば、サブルーチンの作成時に初期化され、 サブルーチン内でのみ変更可能なカウンタです。 これは、パッケージの生存期間中に変数が干渉されることがないように、とき毒 パッケージファイルの BEGIN ブロックで使われます: BEGIN { my $id = 0; sub next_id { ++$id } } =begin original This is discussed in more detail in L, see the entry on I. =end original これは L でより詳しく議論されているので、 I のエントリを参照してください。 =head2 What is variable suicide and how can I prevent it? (変数の自殺(variable suicide)って何で、それをどうすれば防げますか?) =begin original This problem was fixed in perl 5.004_05, so preventing it means upgrading your version of perl. ;) =end original この問題は 5.004_05 で修正されたので、防ぐためには perl を バージョンアップします :) =begin original 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: =end original 変数の自殺とは、(一時的にしろ、恒久的にしろ)変数の値を失ったときのことを 指します。 これは、クロージャ、もしくは別名つけされた foreach イテレータ変数や サブルーチンの引数と相互作用している my() や local() を通した スコープによって引き起こされます。 以前はこのやり方で変数の値をうっかりとなくしてしまうように 使われがちでしたが、現在は非常に難しくなっています。 以下のコードを考えてみましょう: my $f = 'foo'; sub T { while ($i++ < 3) { my $f = $f; $f .= "bar"; print $f, "\n" } } T; print "Finally $f\n"; =begin original If you are experiencing variable suicide, that C in the subroutine doesn't pick up a fresh copy of the C<$f> whose value is . The output shows that inside the subroutine the value of C<$f> leaks through when it shouldn't, as in this output: =end original もし変数の自殺に遭遇したら、サブルーチン内の C は、値が C である C<$f> の最新のコピーをではありません。 この出力は、漏れてはいけないサブルーチン内の C<$f> の値が漏れていることを 示し、以下のようになります: foobar foobarbar foobarbarbar Finally foo =begin original The $f that has "bar" added to it three times should be a new C<$f> C should create a new lexical variable each time through the loop. The expected output is: =end original "bar" を保持している $f は三回 new C<$f> されるべきものです (C は、 ループが通る度に新たなレキシカル変数を生成すべきなのです)。 予想される出力は以下のものです: foobar foobar foobar Finally foo =head2 How can I pass/return a {Function, FileHandle, Array, Hash, Method, Regex}? ({関数, ファイルハンドル, 配列, ハッシュ, メソッド, 正規表現} を渡したり返したりするには?) =begin original With the exception of regexes, you need to pass references to these objects. See L for this particular question, and L for information on references. =end original 正規表現を除いて、これらのオブジェクトのリファレンスを渡す必要があります。 L にある関連した質問と、 L にあるリファレンスに関する情報を参照してください。 =begin original See "Passing Regexes", later in L, for information on passing regular expressions. =end original 正規表現を渡すための情報については、L で後述する "Passing Regexes" を参照して下さい。 =over 4 =item Passing Variables and Functions (変数や関数を渡す) =begin original Regular variables and functions are quite easy to pass: just pass in a reference to an existing or anonymous variable or function: =end original 普通の変数や関数はとても簡単に渡せます: 既に存在している変数や関数に対する リファレンスか、無名変数や無名関数に対するリファレンスを渡せばよいのです。 func( \$some_scalar ); func( \@some_array ); func( [ 1 .. 10 ] ); func( \%some_hash ); func( { this => 10, that => 20 } ); func( \&some_func ); func( sub { $_[0] ** $_[1] } ); =item Passing Filehandles =begin original As of Perl 5.6, you can represent filehandles with scalar variables which you treat as any other scalar. =end original Perl 5.6 から、他のスカラと同様にファイルハンドルもスカラ変数で扱えます。 open my $fh, $filename or die "Cannot open $filename! $!"; func( $fh ); sub func { my $passed_fh = shift; my $line = <$passed_fh>; } =begin original Before Perl 5.6, you had to use the C<*FH> or C<\*FH> notations. These are "typeglobs"--see L and especially L for more information. =end original Perl 5.6 より前では、C<*FH> や C<\*FH> といった記法を使う必要があります。 これらは“型グロブ”(typeglob)です。 L) と L に 詳しい説明があります。 =item Passing Regexes (正規表現を渡す) =begin original To pass regexes around, you'll need to be using a release of Perl sufficiently recent as to support the C construct, pass around strings and use an exception-trapping eval, or else be very, very clever. =end original 正規表現を渡すには、C 構造が利用可能な最近の Perl を使うか、 文字列を渡したあとで例外を捕らえる eval を使うか、 さもなければとてもとても賢明でなければなりません。 =begin original Here's an example of how to pass in a string to be regex compared using C: =end original 以下の例は、cを使って正規表現として比較すべき文字列を渡す方法の例です: sub compare($$) { my ($val1, $regex) = @_; my $retval = $val1 =~ /$regex/; return $retval; } $match = compare("old McDonald", qr/d.*D/i); =begin original Notice how C allows flags at the end. That pattern was compiled at compile time, although it was executed later. The nifty C notation wasn't introduced until the 5.005 release. Before that, you had to approach this problem much less intuitively. For example, here it is again if you don't have C: =end original C の末尾に付けることができるフラグに注意してください。 このパターンは一度だけコンパイル時にコンパイルされ、 実行時にはコンパイルされません。 このしゃれた C 記法は 5.005 リリースで初めて提供されました。 それまでは、この問題に対して遥かに直感的でない手法を とらなければなりませんでした。 例えば、先ほどのコードを C なしで書くと: sub compare($$) { my ($val1, $regex) = @_; my $retval = eval { $val1 =~ /$regex/ }; die if $@; return $retval; } $match = compare("old McDonald", q/($?i)d.*D/); =begin original Make sure you never say something like this: =end original 決して以下のようにしてはいけません: return eval "\$val =~ /$regex/"; # WRONG =begin original or someone can sneak shell escapes into the regex due to the double interpolation of the eval and the double-quoted string. For example: =end original あるいは、誰かが eval の二重展開とダブルクォートで括られた文字列のために、 正規表現に妙なシェルエスケープを押し込むかもしれません。 例を挙げましょう: $pattern_of_evil = 'danger ${ system("rm -rf * &") } danger'; eval "\$string =~ /$pattern_of_evil/"; =begin original Those preferring to be very, very clever might see the O'Reilly book, I, by Jeffrey Friedl. Page 273's Build_MatchMany_Function() is particularly interesting. A complete citation of this book is given in L. =end original これらのことに関してとてもとても賢明になるには、Jeffrey Friedl による O'Reilly の本 I を読むことでしょう。 特に 273 ページにある Build_MatchMany_Function() は興味深いものです。 この本に関する完全な情報は L にあります。 =item Passing Methods (メソッドを渡す) =begin original To pass an object method into a subroutine, you can do this: =end original サブルーチンにオブジェクトメソッドを渡すには、以下のようにできます: call_a_lot(10, $some_obj, "methname") sub call_a_lot { my ($count, $widget, $trick) = @_; for (my $i = 0; $i < $count; $i++) { $widget->$trick(); } } =begin original Or, you can use a closure to bundle up the object, its method call, and arguments: =end original オブジェクトとそのメソッド呼び出しと引数とをまとめるために クロージャを使うこともできます: my $whatnot = sub { $some_obj->obfuscate(@args) }; func($whatnot); sub func { my $code = shift; &$code(); } =begin original You could also investigate the can() method in the UNIVERSAL class (part of the standard perl distribution). =end original UNIVERSAL クラスにある can() メソッドを試すこともできます (これは標準の perl 配布キットの一部です)。 =back =head2 How do I create a static variable? (静的変数を作るには?) =begin original (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original In Perl 5.10, declare the variable with C. The C declaration creates the lexical variable that persists between calls to the subroutine: =end original Perl 5.10 では、C で変数を宣言します。 C 宣言は、サブルーチンの呼び出しの間で永続するレキシカル変数を 作成します: sub counter { state $count = 1; $counter++ } =begin original You can fake a static variable by using a lexical variable which goes out of scope. In this example, you define the subroutine C, and it uses the lexical variable C<$count>. Since you wrap this in a BEGIN block, C<$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 C 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 C<$count> is private to C. =end original スコープ外でレキシカル変数を使うことでスタティック変数を でっち上げることができます。 この例では、サブルーチン C を定義し、そこでレキシカル変数 C<$count> を使います。 これを BEGIN ブロックで囲っているので、C<$count> はコンパイル時に 定義されますが、BEGIN ブロックの終わりでスコープから外れます。 BEGIN ブロックはまた、サブルーチンとそこで使われている値はコンパイル時に 定義されるので、このサブルーチンはその他のどのサブルーチンからも 使える準備が出来ていて、このコードをプログラムテキスト中の他のサブルーチンと 同様に同じ場所(典型的には、コードの最後)にこのコードを置けることを保証します。 サブルーチン C は未だにデータへのリファレンスを持っていて、 これが値にアクセスできる唯一の方法です(そしてそうする度に、値が インクリメントされます)。 C<$count> で定義されたメモリの塊にあるデータは C に プライベートです。 BEGIN { my $count = 1; sub counter { $count++ } } my $start = counter(); .... # code that calls counter(); my $end = counter(); =begin original 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, C and C share the variable. One function adds to the value and the other simply returns the value. They can both access C<$count>, and since it has gone out of scope, there is no other way to access it. =end original 前述の例では、関数でプライベートな変数を作っています; ただ一つの関数だけがこのリファレンスを覚えているからです。 変数がスコープ内にある間に複数の関数を定義でき、各関数は「プライベート」 変数を共有できます。 レキシカル変数がスコープ内ではあるけれども関数の外側から変数にアクセスでき、 それに対するリファレンスすら作成できるため、これは実際には 「静的」変数ではありません。 この例では、C と C は変数を共有しています。 片方の関数が値を加え、もう片方は単に値を返します。 これらは両方とも C<$count> にアクセスでき、スコープ外から離れるため、 これにアクセスするその他の方法はありません。 BEGIN { my $count = 1; sub increment_count { $count++ } sub return_count { $count } } =begin original 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. =end original ファイルプライベートな変数を宣言するには、やはりレキシカル変数が使えます。 ファイルもスコープとなるので、あるファイルで定義されたレキシカル変数は その他のファイルからは見えません。 =begin original See L for more information. The discussion of closures in L may help you even though we did not use anonymous subroutines in this answer. See L for details. =end original さらなる情報については L を 参照してください。 L でのクロージャに関する議論は、この答えには無名サブルーチンは 使っていないですが、助けになるかもしれません。 詳細については L を参照してください。 =head2 What's the difference between dynamic and lexical (static) scoping? Between local() and my()? (動的スコープとレキシカル(または静的)スコープとの間の違いは? local() と my() との違いは?) =begin original C saves away the old value of the global variable C<$x> and assigns a new value for the duration of the subroutine I. This is done at run-time, so is called dynamic scoping. local() always affects global variables, also called package variables or dynamic variables. =end original C は、グローバル変数 C<$x> の古い値を保存して、 I<そのサブルーチンから呼び出された関数から参照できる> サブルーチンの 存在する間の新たな値を代入します。 これはコンパイル時ではなく、実行時に行われるので、動的スコープと呼ばれます。 local() は常にグローバル変数に対して作用し、 パッケージ変数とか動的変数と呼ばれることもあります。 =begin original C 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. =end original C は、現在のサブルーチンにおいてのみ参照できる変数を新たに 生成します。 これはコンパイル時に行われるので、レキシカルスコープだとか 静的スコープと呼ばれます。 my() はプライベート変数に作用し、レキシカル変数とか、(間違って)静的 (スコープを持った)変数と呼ばれることもあります。 =begin original For instance: =end original 例を挙げましょう: 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 =begin original 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 called subroutine. =end original "private"という値を出力させる方法がないということに注目してください。 これは、$var が関数の lexical() なブロックの内側でのみその値を持っていて、 そこから呼び出されたサブルーチンからは隠されてしまうからです。 =begin original 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. =end original まとめると、local() はあなたがプライベートと考えるようなことをローカルな 変数に対して行うようなことはありません。 これはグローバル変数に一時的な値を与えるだけです。 あなたがプライベート変数を必要としている場合、my() があなたが 探し求めているものです。 =begin original See L and L for excruciating details. =end original このことをより詳しく説明している L と L を参照してください。 =head2 How can I access a dynamic variable while a similarly named lexical is in scope? (どうやれば同じ名前のレキシカル変数がスコープにあるときに動的変数にアクセスできますか?) =begin original If you know your package, you can just mention it explicitly, as in $Some_Pack::var. Note that the notation $::var is B the dynamic $var in the current package, but rather the one in the "main" package, as though you had written $main::var. =end original 自分のパッケージを知っているのなら、これを $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"; =begin original Alternatively you can use the compiler directive our() to bring a dynamic variable into the current lexical scope. =end original あるいは、動的変数を現在のレキシカルスコープにもたらすために、コンパイラ 指示子 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"; } =head2 What's the difference between deep and shallow binding? (深い束縛(deep binding)と浅い束縛(shallow binding)との間の違いとは?) =begin original 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 L<"What's a closure?">. =end original 深い束縛では、無名サブルーチンに置かれているレキシカル変数は そのサブルーチンが生成されたときのものと同一のものになります。 浅い束縛では、これはそのサブルーチンが呼び出されたときのスコープに 存在している同じ名前を持った変数のどれか、になります。 Perl はレキシカル変数(つまり、my() によって作られるもの)に対しては 常に深い束縛を使います。 それに対し動的変数(つまりグローバル変数か、ローカル変数か、 パッケージ変数)では、浅い束縛がなされます。 こういったものを使わない理由がもう一つあります。 その答えは L<"What's a closure?"> を参照してください。 =head2 Why doesn't "my($foo) = EFILEE;" work right? (なぜ "my($foo) = EFILEE;" が正しく動作しないのでしょうか?) =begin original C and C give list context to the right hand side of C<=>. The 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()). =end original C と C は C<=> の右辺に対してリストコンテキストを与えます。 読み込み操作 は Perlの関数や演算子の多くと同じくそれが呼び出されたときの コンテキストを見分けることができて、それに応じて適切に振る舞います。 一般的には、scalar() 関数が助けになるでしょう。 その関数は(一般的な神話とは反して)引数となるデータに対して 何も行いませんが、引数がスカラとして振る舞うように指示します。 関数のスカラ時の振る舞いが定義されていないのであれば、 当然ながらこれはあなたの助けにはなりません(sort() がそうです)。 =begin original To enforce scalar context in this particular case, however, you need merely omit the parentheses: =end original しかしながら特定のケースにおいては、スカラコンテキストを強制するために 単に括弧を取り除く必要があります: local($foo) = ; # WRONG local($foo) = scalar(); # ok local $foo = ; # right =begin original You should probably be using lexical variables anyway, although the issue is the same here: =end original これと同じ問題があるものの、なんにしろレキシカル変数を使うべきでしょう。 my($foo) = ; # WRONG my $foo = ; # right =head2 How do I redefine a builtin function, operator, or method? (組み込みの関数や演算子、メソッドを再定義するには?) =begin original Why do you want to do that? :-) =end original なんだってそんなことをしたがるのですか? :-) =begin original 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 L. There's also an example in L. =end original open() のようなあらかじめ定義されている関数をオーバーライドしたいのであれば、 異なるモジュールから新しい定義をインポートする必要があります。 L を参照してください。 L にも例があります。 =begin original If you want to overload a Perl operator, such as C<+> or C<**>, then you'll want to use the C pragma, documented in L. =end original C<+> や C<**> のような Perl の演算子をオーバーロードしたいのであれば L で説明されているような C プラグマを 使いたくなるでしょう。 =begin original If you're talking about obscuring method calls in parent classes, see L. =end original 親クラスにおける不明瞭なメソッド呼び出しについて考えているのなら、 L を参照してください。 =head2 What's the difference between calling a function as &foo and foo()? (関数呼び出しを &foo で行ったときと foo() で行ったときとの違いはなんですか?) =begin original (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original Calling a subroutine as C<&foo> with no trailing parentheses ignores the prototype of C and passes it the current value of the argumet list, C<@_>. Here's an example; the C subroutine calls C<&foo>, which prints what its arguments list: =end original C<&foo> の形で、引き続くかっこなしでサブルーチンを呼び出すと、 C のプロトタイプを無視して、引数リスト C<@_> の現在の値を渡します。 以下は例です: C サブルーチンは、引数リストを表示する C<&foo> を 呼び出します: sub bar { &foo } sub foo { print "Args in foo are: @_\n" } bar( qw( a b c ) ); =begin original When you call C with arguments, you see that C got the same C<@_>: =end original C を引数付きで呼び出した場合、C も同じ C<@_> を得ます: Args in foo are: a b c =begin original Calling the subroutine with trailing parentheses, with or without arguments, does not use the current C<@_> and respects the subroutine prototype. Changing the example to put parentheses after the call to C changes the program: =end original サブルーチンをかっこ付きで呼び出した場合、引数のありなしに関わらず、 現在の C<@_> は使わずに、サブルーチンのプロトタイプに従います。 C を呼び出すときにかっこをつけるように例を変更します: sub bar { &foo() } sub foo { print "Args in foo are: @_\n" } bar( qw( a b c ) ); =begin original Now the output shows that C doesn't get the C<@_> from its caller. =end original 今度は、C が呼び出し元から C<@_> を得ていないことが分かります: Args in foo are: =begin original The main use of the C<@_> pass-through feature is to write subroutines whose main job it is to call other subroutines for you. For further details, see L. =end original C<@_> パススルー機能の主な利用法は、他のサブルーチンを呼び出すのが 主な仕事であるサブルーチンを書くためです。 更なる詳細については、L を参照してください。 =head2 How do I create a switch or case statement? (switch 文や case 文を作るには?) =begin original In Perl 5.10, use the C construct described in L: =end original Perl 5.10 では、L に記述されている C 構造を 使ってください: 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!" } }; =begin original If one wants to use pure Perl and to be compatible with Perl versions prior to 5.10, the general answer is to use C: =end original もしピュア Perl を使って、バージョン 5.10 より前と互換性を持たせたいなら、 構造文を書くための一般的な答えは C を使うことです: for ($variable_to_test) { if (/pat1/) { } # do something elsif (/pat2/) { } # do something else elsif (/pat3/) { } # do something else else { } # default } =begin original 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: =end original 以下の例は、パターンマッチングに基づいた単純な 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"; } =begin original See L for other examples in this style. =end original このスタイルに関するその他の例については L を参照してください。 =begin original 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 C<"SEND"> has precedence over C<"STOP"> here: =end original 定数や変数の位置を変えた方が良いことがあるかもしれません。 たとえば、与えられたたくさんの答についてテストを行いたいとしましょう。 この場合大小文字を無視することもできますし、 略記することもあります。もし全て文字列が異なるキャラクターで始まっていたり、 C<"SEND"> が C<"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" } =begin original A totally different approach is to create a hash of function references. =end original まったく異なるアプローチに、関数のリファレンスのハッシュを作成するという やり方があります。 my %commands = ( "happy" => \&joy, "sad", => \&sullen, "done" => sub { die "See ya!" }, "mad" => \&angry, ); print "How are you? "; chomp($string = ); if ($commands{$string}) { $commands{$string}->(); } else { print "No such command: $string\n"; } =begin original Starting from Perl 5.8, a source filter module, C, 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. =end original Perl 5.8 から、ソースフィルタモジュール C も switch と case を 使うために使えます。 Perl 5.10 には完全互換のネイティブな switch があり、また、これはソース フィルタとして実装されているので、複雑な文法の場合はいつも想定通りに 動くとは限らないからです。 =head2 How can I catch accesses to undefined variables, functions, or methods? (どうすれば未定義な変数, 関数, メソッドに対するアクセスを捕捉できますか?) =begin original The AUTOLOAD method, discussed in L and L, lets you capture calls to undefined functions and methods. =end original L と L で 言及されている AUTOLOAD メソッドは、未定義な関数やメソッドに対する 呼び出しを捕捉させてくれます。 =begin original When it comes to undefined variables that would trigger a warning under C, you can promote the warning to an error. =end original C が有効なときに警告の引き金になるような未定義変数への アクセスがあったとき、警告をエラーに昇格させることができます。 use warnings FATAL => qw(uninitialized); =head2 Why can't a method included in this same file be found? (なぜ同じファイルにあるメソッドが見つけられないのでしょうか?) =begin original Some possible reasons: your inheritance is getting confused, you've misspelled the method name, or the object is of the wrong type. Check out L for details about any of the above cases. You may also use C to find out the class C<$object> was blessed into. =end original 幾つかの理由が考えられます: あなたが継承したものが混乱していているか、 メソッド名を間違えたか、あるいはオブジェクトの型が間違っていたか。 上記の場合に関する詳細は L をチェックしてみてください。 C<$object> が bless されているクラスは C として 見分けることができます。 =begin original Another possible reason for problems is because you've used the indirect object syntax (eg, C) 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 C statement instead of C. If not, make sure to use arrow notation (eg., C<< Guru->find("Samy") >>) instead. Object notation is explained in L. =end original もう一つありうる理由は、Perl がパッケージを見いだす前にクラス名を使った 間接オブジェクト構文(C のようなもの)を使ったためでしょう。 パッケージは、それを使うよりも前に全てが定義されているようにします。 これは C 文ではなく C 文を使えば考慮されます。 あるいは、代わりに矢印記法(arrow notation、 C<< Guru->find("Samy") >> のようなもの)を使うようにしてください。 オブジェクトの記法は L で説明されています。 =begin original Make sure to read about creating modules in L and the perils of indirect objects in L. =end original モジュールの作り方については L を、間接オブジェクトの問題点に ついては L を確認してください。 =head2 How can I find out my current or calling package? (カレントのパッケージや呼び出しパッケージはどうすればわかりますか?) =begin original (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original To find the package you are currently in, use the special literal C<__PACKAGE__>, as documented in L. You can only use the special literals as separate tokens, so you can't interpolate them into strings like you can with variables: =end original 今いるパッケージを知るには、L に記述されている特殊リテラル C<__PACKAGE__> を使ってください。 特殊リテラルは独立したトークンとしてのみ使えるので、変数のように 文字列に展開できません: my $current_package = __PACKAGE__; print "I am in package $current_package\n"; =begin original This is different from finding out the package an object is blessed into, which might not be the current package. For that, use C from C, part of the Standard Library since Perl 5.8: =end original これはオブジェクトが bless されているパッケージを知ることとは違います; これは現在のパッケージではないかもしれません。 この目的のためには、Perl 5.8 から標準ライブラリの一部となっている C の C を使ってください: use Scalar::Util qw(blessed); my $object_package = blessed( $object ); =begin original 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: =end original しかし、ほとんどの場合では、オブジェクトがそのクラスから継承していると 主張している限りは、どのパッケージが bless したかを 気にするべきではありません: my $is_right_class = eval { $object->isa( $package ) }; # true or false =begin original If you want to find the package calling your code, perhaps to give better diagnostics as C does, use the C built-in: =end original あるコードを呼び出したパッケージを知りたい場合 (おそらく C のように よりよい診断メッセージのためでしょう) C 組み込み関数を 使ってください: sub foo { my @args = ...; my( $package, $filename, $line ) = caller; print "I was called from package $package\n"; ); =begin original By default, your program starts in package C
, so you should always be in some package unless someone uses the C built-in with no namespace. See the C entry in L for the details of empty packges. =end original デフォルトでは、プログラムはパッケージ C
で開始されるので、 名前空間を指定せずに C 組み込み文を使わない限り、いつも なんらかのパッケージ内にいるはずです。 空パッケージに関する詳細については L の C を 参照してください。 =head2 How can I comment out a large block of Perl code? (Perl プログラムの大きなブロックをコメントアウトするには?) =begin original (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original 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 C<=cut>, ending the Pod section: =end original Perl の複数行をコメントアウトするための、汚いけれども簡単な方法は、 コメントアウトしたい部分を Pod 指示子で囲むことです。 これらの指示子は、行の先頭、かつ、Perl が新しい文が始まると 想定する場所に置く必要があります(従って、# コメントのように文の途中には 置けません)。 Pod セクションの終了を示す C<=cut> でコメントを終了します: =pod my $object = NotGonnaHappen->new(); ignored_sub(); $wont_be_assigned = 37; =cut =begin original 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. =end original 汚いけれども簡単な方法は、ソースにコメントされたコードを残す予定が ない(つまりいずれ消す)場合にのみうまく働きます。 もし Pod パーサを使うと、複数行コメントは Pod によって表示されます。 よりよい方法は、Pod パーサからも隠すことです。 =begin original The C<=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 C. End the comment using C<=end> with the same label. You still need the C<=cut> to go back to Perl code from the Pod comment: =end original C<=begin> 指示子で、段落を特定の目的のためにマークできます。 Pod パーサがこれを扱えない場合、単に無視されます。 コメントは C でラベル付けします。 コメントの終了は同じラベルで C<=end> を使います。 Pod コメントから Perl コードに戻るにはやはり C<=cut> が必要です: =begin comment my $object = NotGonnaHappen->new(); ignored_sub(); $wont_be_assigned = 37; =end comment =cut =begin original For more information on Pod, check out L and L. =end original Pod に関するさらなる情報については、L と L を 調べてください。 =head2 How do I clear a package? (パッケージをクリアするには?) =begin original Use this code, provided by Mark-Jason Dominus: =end original 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; } } =begin original Or, if you're using a recent release of Perl, you can just use the Symbol::delete_package() function instead. =end original あるいは、あなたが使っている Perl が最近のリリースのものであれば、 単に Symbol::delete_package() という関数を代わりに使うことができます。 =head2 How can I use a variable as a variable name? (変数を変数名として使うには?) =begin original Beginners often think they want to have a variable contain the name of a variable. =end original 初心者はしばしば変数名が入った変数を使いたいと考えます。 $fred = 23; $varname = "fred"; ++$$varname; # $fred now 24 =begin original This works I, but it is a very bad idea for two reasons. =end original これは I<時には> 動作します。 しかしこれは二つの理由により悪いアイデアです。 =begin original The first reason is that this technique I. 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. =end original 一つ目の理由は、このテクニックは I<グローバル変数でのみ動作する> からです。 つまり、もし上記の例において $fred が my() で作成されたレキシカル変数の場合、 このコードは全く動作しません。 プライベートなレキシカル変数を飛ばして、思いがけずグローバル変数に アクセスすることになります。 グローバル変数は、簡単に衝突し、一般に拡張性がなく、混乱するコードを 作ることになるので、よくないものです。 =begin original Symbolic references are forbidden under the C pragma. They are not true references and consequently are not reference counted or garbage collected. =end original シンボリックリファレンスは C プラグマの元では禁止されます。 これは真のリファレンスではないので、リファレンスカウントに含まれず、 ガベージゴレクションもされません。 =begin original 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 C<%main::>) instead of a user-defined hash. The solution is to use your own hash or a real reference instead. =end original 変数に他の変数の名前を記録するというのがよくない考えであるという 別の理由としては、このような疑問はしばしば Perl のデータ構造、 特にハッシュに関する理解の不足から発生するからです。 シンボリックリファレンスを使うことによって、ユーザー定義のハッシュの代わりに パッケージのシンボルテーブルハッシュ(C<%main::> など)を使うことができます。 解決法は、代わりに自分自身のハッシュや真のリファレンスを使うことです。 $USER_VARS{"fred"} = 23; $varname = "fred"; $USER_VARS{$varname}++; # not $$varname++ =begin original 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: =end original ここではシンボリックリファレンスの代わりに %USER_VARS ハッシュを 使っています。 時々これはユーザーから文字列を変数へのリファレンスとして読み込んで、 それを perl プログラムの変数の値として拡張することがあります。 これもよくない考えです。 なぜなら、プログラムが指定する名前空間とユーザーが指定する名前空間を 融合させることになるからです。 以下のように文字列を読み込んであなたのプログラムの変数の実際の内容の ために拡張するのではなく: $str = 'this has a $fred and $barney in it'; $str =~ s/(\$\w+)/$1/eeg; # need double eval =begin original it would be better to keep a hash around like %USER_VARS and have variable references actually refer to entries in that hash: =end original %USER_VARS のようなハッシュを保存し、このハッシュのエントリを参照する 変数リファレンスを持つよりよい方法です: $str =~ s/\$(\w+)/$USER_VARS{$1}/g; # no /e here at all =begin original 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. =end original これは前述の手法よりも、より高速で、より明快で、より安全です。 もちろん、ドル記号を使う必要はありません。 パーセント記号で囲むなどのより混乱しにくい独自のスキームを使えます。 $str = 'this has a %fred% and %barney% in it'; $str =~ s/%(\w+)%/$USER_VARS{$1}/g; # no /e here at all =begin original Another reason that folks sometimes think they want a variable to contain the name of a variable is because 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. =end original 人々が時々変数名が入った変数を欲しがるもう一つの理由は、 ハッシュを使った適切なデータ構造を構築する方法を知らないからです。 例えば、プログラムで %fred と %barney が必要で、 さらにこれらを名前で参照するスカラへ変数が必要だとします。 $name = "fred"; $$name{WIFE} = "wilma"; # set %fred $name = "barney"; $$name{WIFE} = "betty"; # set %barney =begin original This is still a symbolic reference, and is still saddled with the problems enumerated above. It would be far better to write: =end original これはやはりシンボリックリファレンスで、やはり上記の問題を抱えたままです。 以下のように書けば遥かに改善します: $folks{"fred"}{WIFE} = "wilma"; $folks{"barney"}{WIFE} = "betty"; =begin original And just use a multilevel hash to start with. =end original そして始めるのに単に多段ハッシュを使います。 =begin original The only times that you absolutely I use symbolic references are when you really must refer to the symbol table. This may be because it's something that 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. =end original 唯一あなたが完全にシンボリックリファレンスを I<使わなければならない> 場合は、 シンボルテーブルに対するリファレンスが必要なときだけです。 これは、フォーマット名といったものに対する真のリファレンスを得ることが できないからです。 そうすることはメソッド呼び出しのためにも重要です。 なぜなら名前解決のためにシンボルテーブルを使うからです。 =begin original In those cases, you would turn off C temporarily so you can play around with the symbol table. For example: =end original これらの場合、一時的に C にして シンボルテーブルを使うようにできます。 例えば: @colors = qw(red blue green yellow orange purple violet); for my $name (@colors) { no strict 'refs'; # renege for the block *$name = sub { "@_" }; } =begin original All those functions (red(), blue(), green(), etc.) appear to be separate, but the real code in the closure actually was compiled only once. =end original これら(red(), blue(), green() など)の関数全ては別々に現れますが、 クロージャの中の実際のコードは一回だけコンパイルされます。 =begin original So, sometimes you might want to use symbolic references to directly manipulate the symbol table. 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. =end original シンボルテーブルを直接操作するためにシンボリックリファレンスを 使いたくなることがあるかもしれません。 これには、フォーマット、ハンドル、サブルーチンには関係ありません。 これらは常にグローバルだからです--これらに my() を使うことはできません。 おそらく、スカラ、配列、ハッシュのために--そして普通はサブルーチンの ために--だけ、ハードリファレンスが必要でしょう。 =head2 What does "bad interpreter" mean? ("bad interpreter" とはどういう意味ですか?) =begin original (contributed by brian d foy) =end original (brian d foy によって寄贈されました) =begin original The "bad interpreter" message comes from the shell, not perl. The actual message may vary depending on your platform, shell, and locale settings. =end original "bad interpreter" というメッセージは perl ではなく、シェルが出力しています。 実際のメッセージはプラットフォーム、シェル、ロケール設定によって 様々です。 =begin original 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, but can't. =end original "bad interpreter - no such file or directory" と表示されたら、perl スクリプトの最初の行 ("#!" 行) に perl (あるいはスクリプトを実行する 機能のあるその他のプログラム) への正しいパスが含まれていません。 スクリプトをあるマシンから、perl のパスが異なる -- 例えば /usr/bin/perl と /usr/local/bin/perl -- 他のマシンに移動させた場合に時々起こります。 これはまた、元のマシンの行終端が CRLF で、移動先のマシンが LF のみの場合にも 起こります; シェルが /usr/bin/perl を探そうとしますが、失敗します。 =begin original If you see "bad interpreter: Permission denied", you need to make your script executable. =end original "bad interpreter: Permission denied" と表示されたら、スクリプトを 実行可能にする必要があります。 =begin original In either case, you should still be able to run the scripts with perl explicitly: =end original どちらの場合でも、明示的に perl でスクリプトを実行できるようにするべきです: % perl script.pl =begin original 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. =end original "perl: command not found" のようなメッセージが出た場合、perl が PATH に ありません; つまりおそらくは perl の位置があなたの想定している 場所ではないことも意味しているので、#! 行を調整する必要があります。 =head1 REVISION Revision: $Revision$ Date: $Date$ See L for source control details and availability. =head1 AUTHOR AND COPYRIGHT Copyright (c) 1997-2009 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. =begin meta Translate: 吉村 寿人 Update: SHIRAKATA Kentaro (5.6.1-) =end meta