argra****@users*****
argra****@users*****
2008年 3月 10日 (月) 19:52:28 JST
Index: docs/perl/5.10.0/perlsyn.pod diff -u /dev/null docs/perl/5.10.0/perlsyn.pod:1.1 --- /dev/null Mon Mar 10 19:52:28 2008 +++ docs/perl/5.10.0/perlsyn.pod Mon Mar 10 19:52:28 2008 @@ -0,0 +1,1875 @@ +=head1 NAME +X<syntax> + +=begin original + +perlsyn - Perl syntax + +=end original + +perlsyn - Perl の文法 + +=head1 DESCRIPTION + +=begin original + +A Perl program consists of a sequence of declarations and statements +which run from the top to the bottom. Loops, subroutines and other +control structures allow you to jump around within the code. + +=end original + +Perl プログラムは、宣言と文の並びから構成され、上から下へと実行されます。 +ループ、サブルーチン、その他の制御機構でコードの色々なところに +ジャンプできます。 + +=begin original + +Perl is a B<free-form> language, you can format and indent it however +you like. Whitespace mostly serves to separate tokens, unlike +languages like Python where it is an important part of the syntax. + +=end original + +Perl は B<自由書式> 言語ですが、好きなように整形したりインデントしたり +できます。 +空白が文法の重要な要素である Python のような言語と異なり、 +空白はほとんどトークンの分割の役目です。 + +=begin original + +Many of Perl's syntactic elements are B<optional>. Rather than +requiring you to put parentheses around every function call and +declare every variable, you can often leave such explicit elements off +and Perl will figure out what you meant. This is known as B<Do What I +Mean>, abbreviated B<DWIM>. It allows programmers to be B<lazy> and to +code in a style with which they are comfortable. + +=end original + +Perl の多くの文法要素は B<省略可能> です。 +全ての関数をかっこで括ったり、全ての変数を宣言したりすることを +要求するのではなく、しばしばそのような明示的な要素を置いておいて、 +Perl にあなたが意味しているところを見つけ出させることができます。 +これは B<Do What I Mean> と知られ、頭文字を取って B<DWIM> と呼ばれます。 +これによって、プログラマを B<怠惰> にでき、彼らが快適だと思うスタイルで +コーディングできるようにします。 + +=begin original + +Perl B<borrows syntax> and concepts from many languages: awk, sed, C, +Bourne Shell, Smalltalk, Lisp and even English. Other +languages have borrowed syntax from Perl, particularly its regular +expression extensions. So if you have programmed in another language +you will see familiar pieces in Perl. They often work the same, but +see L<perltrap> for information about how they differ. + +=end original + +Perl は、awk, sed, C, Bourne Shell, Smalltalk, Lisp, 果ては英語といった、 +多くの言語からコンセプトと B<文法を借用> しています。 +他の言語も Perl から文法を借用しています; 特に正規表現拡張をです。 +従って、他の言語でプログラミングしていたなら、Perl にも見たことがあるような +ものがあるでしょう。 +それらはしばしば同じように動作しますが、違う点についての情報は +L<perltrap> を参照してください。 + +=head2 Declarations +X<declaration> X<undef> X<undefined> X<uninitialized> + +(宣言) + +=begin original + +The only things you need to declare in Perl are report formats and +subroutines (and sometimes not even subroutines). A variable holds +the undefined value (C<undef>) until it has been assigned a defined +value, which is anything other than C<undef>. When used as a number, +C<undef> is treated as C<0>; when used as a string, it is treated as +the empty string, C<"">; and when used as a reference that isn't being +assigned to, it is treated as an error. If you enable warnings, +you'll be notified of an uninitialized value whenever you treat +C<undef> as a string or a number. Well, usually. Boolean contexts, +such as: + +=end original + +Perl で宣言が必要なものはレポートフォーマットとサブルーチンだけです +(サブルーチンすら宣言が不要な場合もあります)。 +変数は、C<undef> 以外の定義された値を代入されるまでは未定義値(C<undef>)と +なります。 +数値として使われる場合、C<undef> は C<0> として扱われます; +文字列として使われる場合、これは空文字列 C<""> として扱われます; +リファレンストして使われる場合、これは何も代入されていないので、エラーとして +扱われます。 +警告を有効にしているなら、C<undef> を文字列や数値として扱おうとすると +未初期価値を指摘されます。 +ええ、普通は。 +次のような真偽値コンテキストなら: + + my $a; + if ($a) {} + +=begin original + +are exempt from warnings (because they care about truth rather than +definedness). Operators such as C<++>, C<-->, C<+=>, +C<-=>, and C<.=>, that operate on undefined left values such as: + +=end original + +(定義済みかどうかではなく、真かどうかを考慮するので)警告から免れます。 +未定義の左辺値を操作する、C<++>, C<-->, C<+=>, C<-=>, C<.=> のような +演算子でも: + + my $a; + $a++; + +=begin original + +are also always exempt from such warnings. + +=end original + +とすることでもそのような警告から免れます。 + +=begin original + +A declaration can be put anywhere a statement can, but has no effect on +the execution of the primary sequence of statements--declarations all +take effect at compile time. Typically all the declarations are put at +the beginning or the end of the script. However, if you're using +lexically-scoped private variables created with C<my()>, you'll +have to make sure +your format or subroutine definition is within the same block scope +as the my if you expect to be able to access those private variables. + +=end original + +宣言は、文が置けるところであればどこにでも置くことができますが、 +基本的な文の並びは実行時には何の効果も持ちません -- 宣言はコンパイル時に +すべての効果が表れます。 +典型的なすべての宣言は、スクリプトの先頭か終端に置かれます。 +しかしながら、局所変数を C<my()> を使って作成してレキシカルなスコープを +使っているのであれば、フォーマットやサブルーチンの定義を、同じブロックの +スコープの中でその局所変数にアクセスすることが可能であるようにしておく +必要があるでしょう。 + +=begin original + +Declaring a subroutine allows a subroutine name to be used as if it were a +list operator from that point forward in the program. You can declare a +subroutine without defining it by saying C<sub name>, thus: +X<subroutine, declaration> + +=end original + +サブルーチンの宣言は、プログラムの後のほうにあるサブルーチン名を +リスト演算子のように使うことを許します。 +定義されていないサブルーチンの宣言を、C<sub name> と記述することで +宣言できるので、以下のようにできます。 +X<subroutine, declaration> + + sub myname; + $me = myname $0 or die "can't get myname"; + +=begin original + +Note that myname() functions as a list operator, not as a unary operator; +so be careful to use C<or> instead of C<||> in this case. However, if +you were to declare the subroutine as C<sub myname ($)>, then +C<myname> would function as a unary operator, so either C<or> or +C<||> would work. + +=end original + +myname() 関数は、リスト演算子のように働くのであり、単項演算子としてでは +ないということに注意してください。 +ですから、こういった場合に C<||> の代わりに C<or> を使うことには +注意してください。 +しかし、サブルーチンを C<sub myname ($)> のように宣言しているのであれば、 +C<or> でも C<||> でもうまく行きます。 + +=begin original + +Subroutines declarations can also be loaded up with the C<require> statement +or both loaded and imported into your namespace with a C<use> statement. +See L<perlmod> for details on this. + +=end original + +サブルーチンの宣言は C<require> 文を使って詰め込むこともできますし、 +C<use> 文を使って自分の名前空間にロードしたりインポートしたりすることが +できます。 +これに関する詳細は L<perlmod> を参照してください。 + +=begin original + +A statement sequence may contain declarations of lexically-scoped +variables, but apart from declaring a variable name, the declaration acts +like an ordinary statement, and is elaborated within the sequence of +statements as if it were an ordinary statement. That means it actually +has both compile-time and run-time effects. + +=end original + +文の並びはレキシカルスコープを持った変数の宣言を含むことができますが、 +変数名の宣言とは切り離され、その宣言は通常の文のように振る舞い、 +それが通常の文であるかのように文の並びに組みこまれます。 +これは、そういった宣言がコンパイル時の効果と実行時の効果の両方を +持っているということです。 + +=head2 Comments +X<comment> X<#> + +(コメント) + +=begin original + +Text from a C<"#"> character until the end of the line is a comment, +and is ignored. Exceptions include C<"#"> inside a string or regular +expression. + +=end original + +コメントは C<“#”> 文字から、行末まで続き、その部分は無視されます。 +例外は、文字列や正規表現の中にある C<"#"> です。 + +=head2 Simple Statements +X<statement> X<semicolon> X<expression> X<;> + +(単純文) + +=begin original + +The only kind of simple statement is an expression evaluated for its +side effects. Every simple statement must be terminated with a +semicolon, unless it is the final statement in a block, in which case +the semicolon is optional. (A semicolon is still encouraged if the +block takes up more than one line, because you may eventually add +another line.) Note that there are some operators like C<eval {}> and +C<do {}> that look like compound statements, but aren't (they're just +TERMs in an expression), and thus need an explicit termination if used +as the last item in a statement. + +=end original + +単純文となる唯一の種類は、その副作用のために評価される式です。 +すべての単純文は、それがセミコロンを省略することのできるブロックの +最後にない限りは文を終端するためのセミコロンがなければなりません +(ブロックが二行以上に渡る場合には、セミコロンを付けることをお薦めします。 +なぜなら、別の行を追加する可能性があるからです)。 +C<eval {}> や C<do {}> のように、一見複合文のようにみえるけれども +そうではない(これらは単なる式における TERM です)ものがあって、 +そういったものを文の最後のアイテムとして使った場合には明示的に終端する +必要があるのだということに注意してください。 + +=head2 Truth and Falsehood +X<truth> X<falsehood> X<true> X<false> X<!> X<not> X<negation> X<0> + +(真偽値) + +=begin original + +The number 0, the strings C<'0'> and C<''>, the empty list C<()>, and +C<undef> are all false in a boolean context. All other values are true. +Negation of a true value by C<!> or C<not> returns a special false value. +When evaluated as a string it is treated as C<''>, but as a number, it +is treated as 0. + +=end original + +数値 0, 文字列 C<'0'> と C<''>, 空リスト C<()>, C<undef> は全て真偽値 +コンテキストでは偽となります。 +その他の全ての値は真です。 +真の値を C<!> や C<not> で否定すると、特殊な偽の値を返します。 +これを文字列として評価すると C<''> として扱われますが、数値として評価すると +0 として扱われます。 + +=head2 Statement Modifiers +X<statement modifier> X<modifier> X<if> X<unless> X<while> +X<until> X<foreach> X<for> + +(文修飾子) + +=begin original + +Any simple statement may optionally be followed by a I<SINGLE> modifier, +just before the terminating semicolon (or block ending). The possible +modifiers are: + +=end original + +任意の単純文には、B<一つ> の修飾子を終端のセミコロンの直前(もしくは +ブロックの終端の直前)に付けることができます。 +使うことのできる修飾子は以下の通りです。 + + if EXPR + unless EXPR + while EXPR + until EXPR + foreach LIST + +=begin original + +The C<EXPR> following the modifier is referred to as the "condition". +Its truth or falsehood determines how the modifier will behave. + +=end original + +修飾子に引き続く C<EXPR> は「条件」として参照されます。 +その真偽値が修飾子の振る舞いを決定します。 + +=begin original + +C<if> executes the statement once I<if> and only if the condition is +true. C<unless> is the opposite, it executes the statement I<unless> +the condition is true (i.e., if the condition is false). + +=end original + +C<if> は I<もし> 条件が真の場合にのみ文を実行します。 +C<unless> は逆で、条件が真 I<でない限り> (つまり、条件が偽なら) 文を +実行します。 + + print "Basset hounds got long ears" if length $ear >= 10; + go_outside() and play() unless $is_raining; + +=begin original + +The C<foreach> modifier is an iterator: it executes the statement once +for each item in the LIST (with C<$_> aliased to each item in turn). + +=end original + +C<foreach> 修飾子は反復子です: +LIST の値それぞれ毎に文を実行します(実行中は C<$_> がそれぞれの値の +エイリアスとなります)。 + + print "Hello $_!\n" foreach qw(world Dolly nurse); + +=begin original + +C<while> repeats the statement I<while> the condition is true. +C<until> does the opposite, it repeats the statement I<until> the +condition is true (or while the condition is false): + +=end original + +C<while> は条件が真 I<の間> 文を繰り返します。 +C<until> は逆で、条件が真 I<になるまで> (つまり条件が偽の間) 文を +繰り返します: + + # Both of these count from 0 to 10. + print $i++ while $i <= 10; + print $j++ until $j > 10; + +=begin original + +The C<while> and C<until> modifiers have the usual "C<while> loop" +semantics (conditional evaluated first), except when applied to a +C<do>-BLOCK (or to the deprecated C<do>-SUBROUTINE statement), in +which case the block executes once before the conditional is +evaluated. This is so that you can write loops like: + +=end original + +修飾子 C<while> と C<until> は、一般的な "C<while> loop" の意味を +持っています(条件が最初に評価される)が、C<do>-ブロック(もしくは現在では +使用を推奨されていない C<do>-サブルーチン文)に適用されるときは例外で、 +このときは条件が評価されるよりも前に、一度ブロックが実行されます。 +このため、次のようなループを記述することができます。 + + do { + $line = <STDIN>; + ... + } until $line eq ".\n"; + +=begin original + +See L<perlfunc/do>. Note also that the loop control statements described +later will I<NOT> work in this construct, because modifiers don't take +loop labels. Sorry. You can always put another block inside of it +(for C<next>) or around it (for C<last>) to do that sort of thing. +For C<next>, just double the braces: +X<next> X<last> X<redo> + +=end original + +L<perlfunc/do> を参照してください。 +後述するループの制御文は、修飾子がループラベルを取らないために +この構造文では I<動作しない> ということにも注意してください。 +申し訳ない。 +こういった場合に対処するのに別のブロックを内側に入れたり(C<next> の場合)、 +別のブロックで囲む(C<last> の場合)という方法が常に使えます。 +C<next> では単に中かっこを二重にします: +X<next> X<last> X<redo> + + do {{ + next if $x == $y; + # do something here + }} until $x++ > $z; + +=begin original + +For C<last>, you have to be more elaborate: +X<last> + +=end original + +C<last> の場合は、もっと念入りにする必要があります: + + LOOP: { + do { + last if $x = $y**2; + # do something here + } while $x++ <= $z; + } + +=begin original + +B<NOTE:> The behaviour of a C<my> statement modified with a statement +modifier conditional or loop construct (e.g. C<my $x if ...>) is +B<undefined>. The value of the C<my> variable may be C<undef>, any +previously assigned value, or possibly anything else. Don't rely on +it. Future versions of perl might do something different from the +version of perl you try it out on. Here be dragons. +X<my> + +=end original + +B<注意:> (C<my $x if ...> のような) 条件構造やループ構造で修飾された +C<my> 文の振る舞いは B<未定義> です。 +C<my> 変数の値は C<undef> かも知れませんし、以前に代入された値かも +知れませんし、その他の如何なる値の可能性もあります。 +この値に依存してはいけません。 +perl の将来のバージョンでは現在のバージョンとは何か違うかも知れません。 +ここには厄介なものがいます。 +X<my> + +=head2 Compound Statements +X<statement, compound> X<block> X<bracket, curly> X<curly bracket> X<brace> +X<{> X<}> X<if> X<unless> X<while> X<until> X<foreach> X<for> X<continue> + +(複合文) + +=begin original + +In Perl, a sequence of statements that defines a scope is called a block. +Sometimes a block is delimited by the file containing it (in the case +of a required file, or the program as a whole), and sometimes a block +is delimited by the extent of a string (in the case of an eval). + +=end original + +Perl では、スコープを定義するような文の並びをブロックと呼びます。 +ブロックはそれを含むファイルによって範囲が定められることがあります +(ファイルが require されたときか、プログラム全体としての場合)し、 +文字列の展開によって範囲が定められる(eval の場合)こともあります。 + +=begin original + +But generally, a block is delimited by curly brackets, also known as braces. +We will call this syntactic construct a BLOCK. + +=end original + +しかし一般的には、ブロックは中かっこによって範囲が定められます。 +この構文的な構造をブロックと呼びます。 + +=begin original + +The following compound statements may be used to control flow: + +=end original + +以下に挙げる複合文を制御フローとして使うことができます: + + if (EXPR) BLOCK + if (EXPR) BLOCK else BLOCK + if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK + LABEL while (EXPR) BLOCK + LABEL while (EXPR) BLOCK continue BLOCK + LABEL until (EXPR) BLOCK + LABEL until (EXPR) BLOCK continue BLOCK + LABEL for (EXPR; EXPR; EXPR) BLOCK + LABEL foreach VAR (LIST) BLOCK + LABEL foreach VAR (LIST) BLOCK continue BLOCK + LABEL BLOCK continue BLOCK + +=begin original + +Note that, unlike C and Pascal, these are defined in terms of BLOCKs, +not statements. This means that the curly brackets are I<required>--no +dangling statements allowed. If you want to write conditionals without +curly brackets there are several other ways to do it. The following +all do the same thing: + +=end original + +しかし注意して欲しいのは、C や Pascal とは異なり、ブロックを取るように +定義されていて文を取るではないということです。 +つまり、中かっこは I<必要なもの> です -- 曖昧な文が許されません。 +中かっこなしの条件文を使いたいのであれば、いくつかのやり方があります。 +以下の全ては同じことです: + + if (!open(FOO)) { die "Can't open $FOO: $!"; } + die "Can't open $FOO: $!" unless open(FOO); + open(FOO) or die "Can't open $FOO: $!"; # FOO or bust! + open(FOO) ? 'hi mom' : die "Can't open $FOO: $!"; + # a bit exotic, that last one + +=begin original + +The C<if> statement is straightforward. Because BLOCKs are always +bounded by curly brackets, there is never any ambiguity about which +C<if> an C<else> goes with. If you use C<unless> in place of C<if>, +the sense of the test is reversed. + +=end original + +C<if> 文は明解です。 +ブロックは常に中かっこで区切られるので、C<if> と C<else> の対応が +曖昧になるようなことは決してありません。 +C<unless> を C の C<if> のように使いたいのであれば、検査を反転します。 + +=begin original + +The C<while> statement executes the block as long as the expression is +L<true|/"Truth and Falsehood">. +The C<until> statement executes the block as long as the expression is +false. +The LABEL is optional, and if present, consists of an identifier followed +by a colon. The LABEL identifies the loop for the loop control +statements C<next>, C<last>, and C<redo>. +If the LABEL is omitted, the loop control statement +refers to the innermost enclosing loop. This may include dynamically +looking back your call-stack at run time to find the LABEL. Such +desperate behavior triggers a warning if you use the C<use warnings> +pragma or the B<-w> flag. + +=end original + +C<while> 文は、式が L<真|/"Truth and Falsehood"> である間、ブロックを +実行します。 +C<until> 文は、式が偽である間、ブロックを実行します。 +LABEL は省略可能ですが、ある場合には、コロンを伴った識別子になります。 +LABEL は C<next>、C<last>、C<redo> といったループ制御文のループを規定します。 +LABEL が省略された場合、ループ制御文はそれを含むループの中で最も内側の +ループを参照します。 +これは、実行時に LABEL を検出するための呼び出しスタックの動的な後戻り検索を +含むことができます。 +そのような推奨されない振る舞いは、C<use warnings> プラグマや B<-w> フラグを +使った場合には警告を引き起こします。 + +=begin original + +If there is a C<continue> BLOCK, it is always executed just before the +conditional is about to be evaluated again. Thus it can be used to +increment a loop variable, even when the loop has been continued via +the C<next> statement. + +=end original + +C<continue> ブロックが存在する場合、 +常に条件が再評価される直前に実行されます。 +したがって、このブロックをループ変数のインクリメントのために +使うことができます。 +これは、ループがC<next>文を通して継続されるときでも実行されます。 + +=head2 Loop Control +X<loop control> X<loop, control> X<next> X<last> X<redo> X<continue> + +(ループ制御) + +=begin original + +The C<next> command starts the next iteration of the loop: + +=end original + +C<next> コマンドはループの次の繰り返しを開始します: + + LINE: while (<STDIN>) { + next LINE if /^#/; # discard comments + ... + } + +=begin original + +The C<last> command immediately exits the loop in question. The +C<continue> block, if any, is not executed: + +=end original + +C<last> コマンドはループから即座に脱出します。 +C<continue> ブロックがあっても、それは実行されません: + + LINE: while (<STDIN>) { + last LINE if /^$/; # exit when done with header + ... + } + +=begin original + +The C<redo> command restarts the loop block without evaluating the +conditional again. The C<continue> block, if any, is I<not> executed. +This command is normally used by programs that want to lie to themselves +about what was just input. + +=end original + +C<redo> コマンドは、条件の再評価をすることなしにループブロックの +再実行を行います。 +C<continue> ブロックがあっても、それは I<実行されません>。 +このコマンドは通常、プログラムに対する入力に関してプログラム自身を +だましたいといったときに使われます。 + +=begin original + +For example, when processing a file like F</etc/termcap>. +If your input lines might end in backslashes to indicate continuation, you +want to skip ahead and get the next record. + +=end original + +たとえば、F</etc/termcap> のようなファイルを処理することを +考えてみましょう。 +もし入力された行の行末が継続を示すバックスラッシュであった場合、先へ進んで +次のレコードを取り出したいと思うでしょう。 + + while (<>) { + chomp; + if (s/\\$//) { + $_ .= <>; + redo unless eof(); + } + # now process $_ + } + +=begin original + +which is Perl short-hand for the more explicitly written version: + +=end original + +これは Perl の省略記法で、もっとはっきりと書くと以下のようになります: + + LINE: while (defined($line = <ARGV>)) { + chomp($line); + if ($line =~ s/\\$//) { + $line .= <ARGV>; + redo LINE unless eof(); # not eof(ARGV)! + } + # now process $line + } + +=begin original + +Note that if there were a C<continue> block on the above code, it would +get executed only on lines discarded by the regex (since redo skips the +continue block). A continue block is often used to reset line counters +or C<?pat?> one-time matches: + +=end original + +上記の例で C<continue> ブロックがあったとしたら、それは +(redo は continue ブロックをスキップするので) 正規表現によって +捨てられた行だけが実行されるということに注意してください。 +continue ブロックは行カウンターをリセットするとか、 +一度だけマッチする C<?pat?> をリセットするのに使われます。 + + # inspired by :1,$g/fred/s//WILMA/ + while (<>) { + ?(fred)? && s//WILMA $1 WILMA/; + ?(barney)? && s//BETTY $1 BETTY/; + ?(homer)? && s//MARGE $1 MARGE/; + } continue { + print "$ARGV $.: $_"; + close ARGV if eof(); # reset $. + reset if eof(); # reset ?pat? + } + +=begin original + +If the word C<while> is replaced by the word C<until>, the sense of the +test is reversed, but the conditional is still tested before the first +iteration. + +=end original + +C<while> を C<until> で置き換えた場合検査の意味は逆転しますが、 +繰り返しが実行されるより前に条件が検査されることは変わりありません。 + +=begin original + +The loop control statements don't work in an C<if> or C<unless>, since +they aren't loops. You can double the braces to make them such, though. + +=end original + +ループ制御文は C<if> や C<unless> 中では動作しません。 +なぜならそこはループではないからです。 +しかし中かっこを二重にしてこれに対処することはできます。 + + if (/pattern/) {{ + last if /fred/; + next if /barney/; # same effect as "last", but doesn't document as well + # do something here + }} + +=begin original + +This is caused by the fact that a block by itself acts as a loop that +executes once, see L<"Basic BLOCKs">. + +=end original + +これは、ブロック自身は一度だけ実行されるループとして動作するからです; +L<"Basic BLOCKs"> を参照してください。 + +=begin original + +The form C<while/if BLOCK BLOCK>, available in Perl 4, is no longer +available. Replace any occurrence of C<if BLOCK> by C<if (do BLOCK)>. + +=end original + +Perl 4 では使うことのできた C<while/if BLOCK BLOCK> という形式は、 +もはや使うことができません。 +C<if BLOCK> の部分を C<if (do BLOCK)> で置き換えてください。 + +=head2 For Loops +X<for> X<foreach> + +(for ループ) + +=begin original + +Perl's C-style C<for> loop works like the corresponding C<while> loop; +that means that this: + +=end original + +Perl の C 形式の C<for> ループは、対応する C<while> ループと同様に +動作します。 +つまり、以下のものは: + + for ($i = 1; $i < 10; $i++) { + ... + } + +=begin original + +is the same as this: + +=end original + +以下のものと同じです: + + $i = 1; + while ($i < 10) { + ... + } continue { + $i++; + } + +=begin original + +There is one minor difference: if variables are declared with C<my> +in the initialization section of the C<for>, the lexical scope of +those variables is exactly the C<for> loop (the body of the loop +and the control sections). +X<my> + +=end original + +小さな違いが一つあります: C<for> の初期化部で C<my> を使って変数が +宣言された場合、この変数のレキシカルスコープは C<for> ループ +(ループ本体と制御部) と完全に同じです。 +X<my> + +=begin original + +Besides the normal array index looping, C<for> can lend itself +to many other interesting applications. Here's one that avoids the +problem you get into if you explicitly test for end-of-file on +an interactive file descriptor causing your program to appear to +hang. +X<eof> X<end-of-file> X<end of file> + +=end original + +通常の、配列に対する添え字付けのループのほかにも、C<for> は他の +多くの興味深いアプリケーションのために借用することができます。 +以下の例は、対話的なファイル記述子の終端を明示的に検査してしまうと +プログラムをハングアップしたように見えてしまう問題を回避するものです。 +X<eof> X<end-of-file> X<end of file> + + $on_a_tty = -t STDIN && -t STDOUT; + sub prompt { print "yes? " if $on_a_tty } + for ( prompt(); <STDIN>; prompt() ) { + # do something + } + +=begin original + +Using C<readline> (or the operator form, C<< <EXPR> >>) as the +conditional of a C<for> loop is shorthand for the following. This +behaviour is the same as a C<while> loop conditional. +X<readline> X<< <> >> + +=end original + +C<for> ループの条件として C<readline> (または演算子形式の C<< <EXPR> >>) を +使う場合、以下のように省略形が使えます。 +この振る舞いは C<while> ループ条件と同じです。 +X<readline> X<< <> >> + + for ( prompt(); defined( $_ = <STDIN> ); prompt() ) { + # do something + } + +=head2 Foreach Loops +X<for> X<foreach> + +(foreach ループ) + +=begin original + +The C<foreach> loop iterates over a normal list value and sets the +variable VAR to be each element of the list in turn. If the variable +is preceded with the keyword C<my>, then it is lexically scoped, and +is therefore visible only within the loop. Otherwise, the variable is +implicitly local to the loop and regains its former value upon exiting +the loop. If the variable was previously declared with C<my>, it uses +that variable instead of the global one, but it's still localized to +the loop. This implicit localisation occurs I<only> in a C<foreach> +loop. +X<my> X<local> + +=end original + +C<foreach> ループは 通常のリスト値に対しての繰り返しを行い、変数 VAR に +リストの要素を繰り返し一回に一つずつセットします。 +変数の前に C<my> というキーワードが置かれていた場合、その変数は +レキシカルスコープを持ち、したがってそれはループの中でのみ可視となります。 +このキーワードがなければ、変数はループに対してローカルとなり、ループを +抜けた後で以前の値が再度取得されます。 +変数が事前に C<my> を使って宣言されていたならば、グローバルなものの +代わりにその変数を使いますが、それもループにローカルなものとなります。 +この暗黙のローカル化は C<foreach> の中で I<のみ> 起きます。 +X<my> X<local> + +=begin original + +The C<foreach> keyword is actually a synonym for the C<for> keyword, so +you can use C<foreach> for readability or C<for> for brevity. (Or because +the Bourne shell is more familiar to you than I<csh>, so writing C<for> +comes more naturally.) If VAR is omitted, C<$_> is set to each value. +X<$_> + +=end original + +読みやすさのために C<foreach> を、簡潔さのために C<for> を使うことが +できます(あるいは C シェルよりも Bourne シェルに親しんでいるのなら +C<for> の方が自然でしょう)。 +VAR が省略された場合には、C<$_> に値が設定されます。 +X<$_> + +=begin original + +If any element of LIST is an lvalue, you can modify it by modifying +VAR inside the loop. Conversely, if any element of LIST is NOT an +lvalue, any attempt to modify that element will fail. In other words, +the C<foreach> loop index variable is an implicit alias for each item +in the list that you're looping over. +X<alias> + +=end original + +LIST の要素が左辺値であった場合、ループの中で VAR を変更することにより、 +対応する値を変更することができます。 +逆に、LIST の要素が左辺値でない場合は、この要素を修正しようとしても +失敗します。 +言い換えると、C<foreach> ループの帰納変数がループの対象となっている +リスト中の個々のアイテムに対するエイリアスになっているからです。 +X<alias> + +=begin original + +If any part of LIST is an array, C<foreach> will get very confused if +you add or remove elements within the loop body, for example with +C<splice>. So don't do that. +X<splice> + +=end original + +LIST のいずれかの部分が配列であった場合に、たとえば C<splice> を使って +ループの本体でその要素を削除したりあるいは追加したりすると +C<foreach> は非常に混乱してしまいます。 +ですからそういうことをしてはいけません。 +X<splice> + +=begin original + +C<foreach> probably won't do what you expect if VAR is a tied or other +special variable. Don't do that either. + +=end original + +VAR が tie されていたりあるいは他の特殊変数であった場合には +C<foreach> はあなたのもくろみどおりには動かないでしょう。 +こういうこともしてはいけません。 + +=begin original + +Examples: + +=end original + +例: + + for (@ary) { s/foo/bar/ } + + for my $elem (@elements) { + $elem *= 2; + } + + for $count (10,9,8,7,6,5,4,3,2,1,'BOOM') { + print $count, "\n"; sleep(1); + } + + for (1..15) { print "Merry Christmas\n"; } + + foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) { + print "Item: $item\n"; + } + +=begin original + +Here's how a C programmer might code up a particular algorithm in Perl: + +=end original + +以下の例は、C プログラマーが Perl でとあるアルゴリズムを記述するときに +使うであろうやり方です: + + for (my $i = 0; $i < @ary1; $i++) { + for (my $j = 0; $j < @ary2; $j++) { + if ($ary1[$i] > $ary2[$j]) { + last; # can't go to outer :-( + } + $ary1[$i] += $ary2[$j]; + } + # this is where that last takes me + } + +=begin original + +Whereas here's how a Perl programmer more comfortable with the idiom might +do it: + +=end original + +それに対して、次の例は Perl プログラマーが同じことをよりゆったりとして +行うやり方です: + + OUTER: for my $wid (@ary1) { + INNER: for my $jet (@ary2) { + next OUTER if $wid > $jet; + $wid += $jet; + } + } + +=begin original + +See how much easier this is? It's cleaner, safer, and faster. It's +cleaner because it's less noisy. It's safer because if code gets added +between the inner and outer loops later on, the new code won't be +accidentally executed. The C<next> explicitly iterates the other loop +rather than merely terminating the inner one. And it's faster because +Perl executes a C<foreach> statement more rapidly than it would the +equivalent C<for> loop. + +=end original + +どのくらいこれが簡単になったように見えますか? これは明確で、安全で、 +高速です。 +これは余計なものが少ないので明確なのです。 +これは後で内側のループと外側のループとの間にコードを付加えた場合でも、 +それを間違って実行することがないので安全なのです。 +C<next> は内側のループを終了するのではなく、外側のループの繰り返しを +行います。 +そしてこれは、Perl は C<foreach> 文をそれと等価な C<for> ループよりも +すばやく実行するので高速なのです。 + +=head2 Basic BLOCKs +X<block> + +(基本ブロック) + +=begin original + +A BLOCK by itself (labeled or not) is semantically equivalent to a +loop that executes once. Thus you can use any of the loop control +statements in it to leave or restart the block. (Note that this is +I<NOT> true in C<eval{}>, C<sub{}>, or contrary to popular belief +C<do{}> blocks, which do I<NOT> count as loops.) The C<continue> +block is optional. + +=end original + +ブロックそれ自身は(ラベルが付いていようがついてなかろうが)一度だけ +実行されるループと、文法的には等価なものです。 +このため、ブロックから脱出するためやブロックの再スタートのために +任意のループ制御文を使うことができます(これは C<eval{}>、C<sub{}>、 +さらに一般的な認識とは異なり I<ループではない> C<do{}> ブロックに対しては +I<真ではない> ということに注意してください)。 +C<continue> ブロックは省略することができます。 + +=begin original + +The BLOCK construct can be used to emulate case structures. + +=end original + +BLOCK 構造は case 構造を行うのにも使えます。 + + SWITCH: { + if (/^abc/) { $abc = 1; last SWITCH; } + if (/^def/) { $def = 1; last SWITCH; } + if (/^xyz/) { $xyz = 1; last SWITCH; } + $nothing = 1; + } + +=begin original + +Such constructs are quite frequently used, because older versions +of Perl had no official C<switch> statement. + +=end original + +古いバージョンの Perl には公式の C<switch> 文がなかったので、このような +構文はとてもよく使われています。 + +=head2 Switch statements +X<switch> X<case> X<given> X<when> X<default> + +(switch 文) + +=begin original + +Starting from Perl 5.10, you can say + +=end original + +Perl 5.10 から、以下のように書くと: + + use feature "switch"; + +=begin original + +which enables a switch feature that is closely based on the +Perl 6 proposal. + +=end original + +Perl 6 で提案されているものを基礎とした switch 機能が有効になります。 + +=begin original + +The keywords C<given> and C<when> are analogous +to C<switch> and C<case> in other languages, so the code +above could be written as + +=end original + +キーワード C<given> と C<when> は他の言語での C<switch> および C<case> と +同様のものなので、上記のコードは以下のように書けます: + + given($_) { + when (/^abc/) { $abc = 1; } + when (/^def/) { $def = 1; } + when (/^xyz/) { $xyz = 1; } + default { $nothing = 1; } + } + +=begin original + +This construct is very flexible and powerful. For example: + +=end original + +この構造はとても柔軟で、強力です。 +例えば: + + use feature ":5.10"; + given($foo) { + when (undef) { + say '$foo is undefined'; + } + + when ("foo") { + say '$foo is the string "foo"'; + } + + when ([1,3,5,7,9]) { + say '$foo is an odd digit'; + continue; # Fall through + } + + when ($_ < 100) { + say '$foo is numerically less than 100'; + } + + when (\&complicated_check) { + say 'complicated_check($foo) is true'; + } + + default { + die q(I don't know what to do with $foo); + } + } + +=begin original + +C<given(EXPR)> will assign the value of EXPR to C<$_> +within the lexical scope of the block, so it's similar to + +=end original + +C<given(EXPR)> はブロックのレキシカルスコープ内で EXPR を C<$_> に +代入するので、これは以下と似ています: + + do { my $_ = EXPR; ... } + +=begin original + +except that the block is automatically broken out of by a +successful C<when> or an explicit C<break>. + +=end original + +しかし、ブロックは C<when> が成功するか、明示的な C<break> によって +自動的に破壊されるところが違います。 + +=begin original + +Most of the power comes from implicit smart matching: + +=end original + +強力さのほとんどは暗黙のスマートマッチングによるものです: + + when($foo) + +=begin original + +is exactly equivalent to + +=end original + +は正確に以下と等価です: + + when($_ ~~ $foo) + +=begin original + +In fact C<when(EXPR)> is treated as an implicit smart match most of the +time. The exceptions are that when EXPR is: + +=end original + +実際のところ、C<when(EXPR)> はほとんどの場合で暗黙のスマートマッチングとして +扱われます。 +例外は EXPR が以下の場合です: + +=over 4 + +=item o + +=begin original + +a subroutine or method call + +=end original + +サブルーチンかメソッド呼び出し + +=item o + +=begin original + +a regular expression match, i.e. C</REGEX/> or C<$foo =~ /REGEX/>, +or a negated regular expression match C<$foo !~ /REGEX/>. + +=end original + +正規表現マッチング: つまり、C</REGEX/> や C<$foo =~ /REGEX/> や +正規表現マッチングの否定 C<$foo !~ /REGEX/>。 + +=item o + +=begin original + +a comparison such as C<$_ E<lt> 10> or C<$x eq "abc"> +(or of course C<$_ ~~ $c>) + +=end original + +C<$_ E<lt> 10> や C<$x eq "abc"> (や、もちろん C<$_ ~~ $c>) のような比較 + +=item o + +=begin original + +C<defined(...)>, C<exists(...)>, or C<eof(...)> + +=end original + +C<defined(...)>, C<exists(...)>, C<eof(...)> のいずれか + +=item o + +=begin original + +A negated expression C<!(...)> or C<not (...)>, or a logical +exclusive-or C<(...) xor (...)>. + +=end original + +否定表現 C<!(...)>, C<not (...)>, 排他的論理和 C<(...) xor (...)> + +=back + +=begin original + +then the value of EXPR is used directly as a boolean. +Furthermore: + +=end original + +このような場合、EXPR の値は直接真偽値として使われます。 +更に: + +=over 4 + +=item o + +=begin original + +If EXPR is C<... && ...> or C<... and ...>, the test +is applied recursively to both arguments. If I<both> +arguments pass the test, then the argument is treated +as boolean. + +=end original + +EXPR が C<... && ...> または C<... and ...> の場合、テストは両方の +引数に対して再帰的に適用されます。 +I<両方の> 引数がテストに成功した場合、この引数は真偽値として扱われます。 + +=item o + +=begin original + +If EXPR is C<... || ...> or C<... or ...>, the test +is applied recursively to the first argument. + +=end original + +EXPR が C<... || ...> または C<... or ...> の場合、テストは最初の引数に +対して再帰的に適用されます。 + +=back + +=begin original + +These rules look complicated, but usually they will do what +you want. For example you could write: + +=end original + +これらの規則は複雑に見えますが、普通はあなたが実行したい通りに実行します。 +例えば、以下のように書けます: + + when (/^\d+$/ && $_ < 75) { ... } + +=begin original + +Another useful shortcut is that, if you use a literal array +or hash as the argument to C<when>, it is turned into a +reference. So C<given(@foo)> is the same as C<given(\@foo)>, +for example. + +=end original + +その他の便利な省略記法としては、C<when> の引数としてリテラルな配列や +ハッシュを書くと、これはリファレンスに変化します。 +それで、例えば C<given(@foo)> は C<given(\@foo)> と同じです。 + +=begin original + +C<default> behaves exactly like C<when(1 == 1)>, which is +to say that it always matches. + +=end original + +C<default> は正確に C<when(1 == 1)> のように振る舞い、常に +マッチングします。 + +=begin original + +See L</"Smart matching in detail"> for more information +on smart matching. + +=end original + +スマートマッチングに関するさらなる情報については +L</"Smart matching in detail"> を参照してください。 + +=head3 Breaking out + +(脱出) + +=begin original + +You can use the C<break> keyword to break out of the enclosing +C<given> block. Every C<when> block is implicitly ended with +a C<break>. + +=end original + +囲まれている C<given> ブロックから脱出するために、C<break> キーワードが +使えます。 +全ての C<when> ブロックの末尾には暗黙に C<break> があります。 + +=head3 Fall-through + +(次の条件への移動(Fall-through)) + +=begin original + +You can use the C<continue> keyword to fall through from one +case to the next: + +=end original + +一つの条件から次へ移動するためには、C<continue> キーワードが使えます: + + given($foo) { + when (/x/) { say '$foo contains an x'; continue } + when (/y/) { say '$foo contains a y' } + default { say '$foo contains neither an x nor a y' } + } + +=head3 Switching in a loop + +(ループ内の switch) + +=begin original + +Instead of using C<given()>, you can use a C<foreach()> loop. +For example, here's one way to count how many times a particular +string occurs in an array: + +=end original + +C<given()> を使う代わりに、C<foreach()> ループを使えます。 +たとえば、以下は配列内に特定の文字列が何回現れるかを数えるための +ひとつの方法です: + + my $count = 0; + for (@array) { + when ("foo") { ++$count } + } + print "\@array contains $count copies of 'foo'\n"; + +=begin original + +On exit from the C<when> block, there is an implicit C<next>. +You can override that with an explicit C<last> if you're only +interested in the first match. + +=end original + +C<when> ブロックからの終了時に、暗黙の C<next> があります。 +もし最初のマッチングだけに興味があるなら、明示的な C<last> でこれを +上書きできます。 + +=begin original + +This doesn't work if you explicitly specify a loop variable, +as in C<for $item (@array)>. You have to use the default +variable C<$_>. (You can use C<for my $_ (@array)>.) + +=end original + +これは、C<for $item (@array)> のように明示的にループ変数を指定した場合は +動作しません。 +デフォルト変数 C<$_> を使う必要があります。 +(C<for my $_ (@array)> は使えます。) + +=head3 Smart matching in detail + +(スマートマッチングの詳細) + +=begin original + +The behaviour of a smart match depends on what type of thing +its arguments are. It is always commutative, i.e. C<$a ~~ $b> +behaves the same as C<$b ~~ $a>. The behaviour is determined +by the following table: the first row that applies, in either +order, determines the match behaviour. + +=end original + +スマートマッチングの振る舞いは引数にどのような型が使われたかに依存します。 +これは常に可換性があります; つまり、C<$a ~~ $b> は C<$b ~~ $a> と同様に +振る舞います。 +振る舞いは以下の表によって決定されます: +適用される最初の行(どのような順序でも)がマッチングの振る舞いを決定します。 + +=begin original + + $a $b Type of Match Implied Matching Code + ====== ===== ===================== ============= + (overloading trumps everything) + +=end original + + $a $b 暗黙に行われるマッチング マッチングコード + ====== ===== ======================== ============= + (全てはオーバーロード可能です) + + Code[+] Code[+] referential equality $a == $b + Any Code[+] scalar sub truth $b->($a) + + Hash Hash hash keys identical [sort keys %$a]~~[sort keys %$b] + Hash Array hash slice existence grep {exists $a->{$_}} @$b + Hash Regex hash key grep grep /$b/, keys %$a + Hash Any hash entry existence exists $a->{$b} + + Array Array arrays are identical[*] + Array Regex array grep grep /$b/, @$a + Array Num array contains number grep $_ == $b, @$a + Array Any array contains string grep $_ eq $b, @$a + + Any undef undefined !defined $a + Any Regex pattern match $a =~ /$b/ + Code() Code() results are equal $a->() eq $b->() + Any Code() simple closure truth $b->() # ignoring $a + Num numish[!] numeric equality $a == $b + Any Str string equality $a eq $b + Any Num numeric equality $a == $b + +=begin original + + Any Any string equality $a eq $b + +=end original + + Any Any 文字列比較 $a eq $b + +=begin original + + + - this must be a code reference whose prototype (if present) is not "" + (subs with a "" prototype are dealt with by the 'Code()' entry lower down) + * - that is, each element matches the element of same index in the other + array. If a circular reference is found, we fall back to referential + equality. + ! - either a real number, or a string that looks like a number + +=end original + + + - これは、プロトタイプが(あれば) "" でないコードリファレンスでなければ + なりません(プロトタイプが "" のサブルーチンはさらに下に書いている + 'Code()' で扱われます) + * - 各要素をもう一つの配列の同じインデックスの要素とマッチングします。 + 循環リファレンスが発見されると、参照の等価性にフォールバックします。 + ! - 実数か、数値のように見える文字列 + +=begin original + +The "matching code" doesn't represent the I<real> matching code, +of course: it's just there to explain the intended meaning. Unlike +C<grep>, the smart match operator will short-circuit whenever it can. + +=end original + +「マッチングコード」は、もちろん I<実際の> マッチングコードを +表現していません: これは単に意図を説明しているだけです。 +C<grep> と違って、スマートマッチング演算子は何かの省略形です。 + +=head3 Custom matching via overloading + +(オーバーロードを使ったマッチングのカスタマイズ) + +=begin original + +You can change the way that an object is matched by overloading +the C<~~> operator. This trumps the usual smart match semantics. +See L<overload>. + +=end original + +C<~~> 演算子をオーバーロードすることで、オブジェクトのマッチングする方法を +変更できます。 +これは通常のスマートマッチングの意味論に打ち勝ちます。 +L<overload> を参照してください。 + +=head3 Differences from Perl 6 + +(Perl 6 からの違い) + +=begin original + +The Perl 5 smart match and C<given>/C<when> constructs are not +absolutely identical to their Perl 6 analogues. The most visible +difference is that, in Perl 5, parentheses are required around +the argument to C<given()> and C<when()>. Parentheses in Perl 6 +are always optional in a control construct such as C<if()>, +C<while()>, or C<when()>; they can't be made optional in Perl +5 without a great deal of potential confusion, because Perl 5 +would parse the expression + +=end original + +Perl 5 のスマートマッチングと C<given>/C<when> 構文は Perl 6 のものと +完全に同一ではありません。 +もっとも目に見える違いは、Perl 5 では、C<given()> と C<when()> の +引数はかっこでくくる必要があります。 +Perl 6 では、C<if()>, C<while()>, C<when()> のような制御構造での +かっこは常に省略可能です; +Perl 5 では、潜在的な大混乱と引き換えにしなければこれを省略できません; +なぜなら Perl 5 は以下のような表現において: + + given $foo { + ... + } + +=begin original + +as though the argument to C<given> were an element of the hash +C<%foo>, interpreting the braces as hash-element syntax. + +=end original + +C<given> の引数はハッシュ C<%foo> の要素であるかのようにパースして、 +中かっこをハッシュ要素文法として解釈するからです。 + +=begin original + +The table of smart matches is not identical to that proposed by the +Perl 6 specification, mainly due to the differences between Perl 6's +and Perl 5's data models. + +=end original + +スマートマッチングの表は Perl 6 仕様で提案されれているものと +同一ではありません; 主に Perl 6 と Perl 5 のデータモデルの違いによります。 + +=begin original + +In Perl 6, C<when()> will always do an implicit smart match +with its argument, whilst it is convenient in Perl 5 to +suppress this implicit smart match in certain situations, +as documented above. (The difference is largely because Perl 5 +does not, even internally, have a boolean type.) + +=end original + +Perl 6 では、C<when()> は常にその引数に対する暗黙のスマートマッチングを +行いますが、Perl 5 では上述の通り、状況によっては暗黙のスマートマッチングを +抑制したほうが便利です。 +(主な違いは、Perl 5 は内部的にさえ真偽値型を持たないことによります。) + +=head2 Goto +X<goto> + +(goto 文) + +=begin original + +Although not for the faint of heart, Perl does support a C<goto> +statement. There are three forms: C<goto>-LABEL, C<goto>-EXPR, and +C<goto>-&NAME. A loop's LABEL is not actually a valid target for +a C<goto>; it's just the name of the loop. + +=end original + +気弱な人のためでないにも関らず、Perl は C<goto> 文をサポートしています。 +C<goto>-LABEL、C<goto>-EXPR、C<goto>-&NAME の三つの形式があります。 +ループのラベルは実際には C<goto> の正当なターゲットではなく、 +ループの名前にすぎません。 + +=begin original + +The C<goto>-LABEL form finds the statement labeled with LABEL and resumes +execution there. It may not be used to go into any construct that +requires initialization, such as a subroutine or a C<foreach> loop. It +also can't be used to go into a construct that is optimized away. It +can be used to go almost anywhere else within the dynamic scope, +including out of subroutines, but it's usually better to use some other +construct such as C<last> or C<die>. The author of Perl has never felt the +need to use this form of C<goto> (in Perl, that is--C is another matter). + +=end original + +C<goto>-LABEL 形式は LABEL でラベル付けされた文を見つけだし、そこから +実行を再開します。 +これはサブルーチンであるとか C<foreach> ループのような +初期化を必要とするような構造へ飛び込むために使うことはできません。 +また、最適化されて無くなってしまうような構造へ飛び込むこともできません。 +動的スコープの中以外のほとんどの場所へは、サブルーチンの +外も含めて移動することができます。 +しかし、通常は C<last> や C<die> のような別のやり方を使ったほうが +良いでしょう。 +Perl の作者は、未だかつてこの形式の C<goto> を使うことが +必要だと感じたことはありません(Perl の場合です。C の場合はまた別の話です)。 + +=begin original + +The C<goto>-EXPR form expects a label name, whose scope will be resolved +dynamically. This allows for computed C<goto>s per FORTRAN, but isn't +necessarily recommended if you're optimizing for maintainability: + +=end original + +C<goto>-EXPR 形式は動的に解決されるスコープを持っているラベル名を +期待しています。 +これによって FORTRAN の計算型 C<goto> が実現できますが、 +これは保守性に重きを置くのであれば使うことは止めた方が良いでしょう。 + + goto(("FOO", "BAR", "GLARCH")[$i]); + +=begin original + +The C<goto>-&NAME form is highly magical, and substitutes a call to the +named subroutine for the currently running subroutine. This is used by +C<AUTOLOAD()> subroutines that wish to load another subroutine and then +pretend that the other subroutine had been called in the first place +(except that any modifications to C<@_> in the current subroutine are +propagated to the other subroutine.) After the C<goto>, not even C<caller()> +will be able to tell that this routine was called first. + +=end original + +C<goto>-&NAME は高度にマジカルで、名前付きサブルーチンの呼び出しを +カレントで実行されているサブルーチンに置き換えます。 +これは別のサブルーチンをロードして、最初の場所で呼び出された +別のサブルーチンを要求することをしようとする +C<AUTOLOAD()> サブルーチンで使われていてます +(カレントのサブルーチンにおける C<@_> に対するもの以外の変更は、 +別のサブルーチンへ伝播します)。 +C<goto> の後で、C<caller()> でなくてもこのサブルーチンが +最初に呼ばれたのだということを伝えることすらできるでしょう。 + +=begin original + +In almost all cases like this, it's usually a far, far better idea to use the +structured control flow mechanisms of C<next>, C<last>, or C<redo> instead of +resorting to a C<goto>. For certain applications, the catch and throw pair of +C<eval{}> and die() for exception processing can also be a prudent approach. + +=end original + +このようなケースのほとんどすべての場合、C<goto> に頼るのではなくて +C<next>、C<last>、C<redo> といった制御フロー機構を使うことが、 +ずっとずっと良いアイデアでしょう。 +一部のアプリケーションに対しては、C<eval{}> と die() を +catch と throw のペアとして例外処理を行うための賢明なアプローチとして +使うことができるでしょう。 + +=head2 PODs: Embedded Documentation +X<POD> X<documentation> + +(POD: 組み込みドキュメント) + +=begin original + +Perl has a mechanism for intermixing documentation with source code. +While it's expecting the beginning of a new statement, if the compiler +encounters a line that begins with an equal sign and a word, like this + +=end original + +Perl は、ソースコードとドキュメントとを混ぜ書きするための仕掛けを +持っています。 +新しい文の始まりが期待されているときに、コンパイラは +以下の例のような = 記号で始まっている語を見つけると: + + =head1 Here There Be Pods! + +=begin original + +Then that text and all remaining text up through and including a line +beginning with C<=cut> will be ignored. The format of the intervening +text is described in L<perlpod>. + +=end original + +そのテキストと、C<=cut> で始まる行までの内容を無視します。 +間に入るテキストの書式は L<perlpod> で説明されています。 + +=begin original + +This allows you to intermix your source code +and your documentation text freely, as in + +=end original + +これによって、ソースコードとドキュメントとを以下に示す例のように +自由に混ぜることができるようになります。 + + =item snazzle($) + + The snazzle() function will behave in the most spectacular + form that you can possibly imagine, not even excepting + cybernetic pyrotechnics. + + =cut back to the compiler, nuff of this pod stuff! + + sub snazzle($) { + my $thingie = shift; + ......... + } + +=begin original + +Note that pod translators should look at only paragraphs beginning +with a pod directive (it makes parsing easier), whereas the compiler +actually knows to look for pod escapes even in the middle of a +paragraph. This means that the following secret stuff will be +ignored by both the compiler and the translators. + +=end original + +コンパイラはパラグラフの途中に pod エスケープがあったとしてもそれを +認識できるのに、pod トランスレータは pod 指示子で始まっている +パラグラフのみに注目すべき(これは構文解析を簡単にするためです)で +あるということに注意して下さい。 +つまり、以下の例にある "secret stuff" はコンパイラからも、 +トランスレータからも無視されるということです。 + + $a=3; + =secret stuff + warn "Neither POD nor CODE!?" + =cut back + print "got $a\n"; + +=begin original + +You probably shouldn't rely upon the C<warn()> being podded out forever. +Not all pod translators are well-behaved in this regard, and perhaps +the compiler will become pickier. + +=end original + +この例の C<warn()> のようなものが、将来に渡って無視されるということに +依存すべきではありません。 +すべての pod トランスレータがそのように振る舞うわけではありませんし、 +コンパイラは将来これを無視しないようになるかもしれません。 + +=begin original + +One may also use pod directives to quickly comment out a section +of code. + +=end original + +pod 指示子を、コードの一部を手っ取り早くコメントアウトするために +使うこともできます。 + +=head2 Plain Old Comments (Not!) +X<comment> X<line> X<#> X<preprocessor> X<eval> + +=begin original + +Perl can process line directives, much like the C preprocessor. Using +this, one can control Perl's idea of filenames and line numbers in +error or warning messages (especially for strings that are processed +with C<eval()>). The syntax for this mechanism is the same as for most +C preprocessors: it matches the regular expression + +=end original + +C のプリプロセッサと同じように、Perl は行指示子を処理できます。 +これを使うことによって、エラーメッセージや警告メッセージにある +ファイル名や行番号を制御することができます +(特に、C<eval()> で処理される文字列のために)。 +この仕組みの構文は C のプリプロセッサとほとんど同じで、正規表現: + + # example: '# line 42 "new_filename.plx"' + /^\# \s* + line \s+ (\d+) \s* + (?:\s("?)([^"]+)\2)? \s* + $/x + +=begin original + +with C<$1> being the line number for the next line, and C<$3> being +the optional filename (specified with or without quotes). + +=end original + +にマッチしたものの C<$1> が次の行の行番号となり、省略することもできる +C<$3> は(クォートありかなしで指定された)ファイル名となります。 + +=begin original + +There is a fairly obvious gotcha included with the line directive: +Debuggers and profilers will only show the last source line to appear +at a particular line number in a given file. Care should be taken not +to cause line number collisions in code you'd like to debug later. + +=end original + +行指示子にはかなり明らかな技があります。 +デバッガとプロファイラは、与えられたファイルの特定の行番号に対して現れた +最新のソース行のみを表示します。 +あとでデバッグしたいコードでは行番号の衝突が起きないように注意するべきです。 + +=begin original + +Here are some examples that you should be able to type into your command +shell: + +=end original + +コマンドシェルでタイプすることのできる例をいくつか挙げます: + + % perl + # line 200 "bzzzt" + # the `#' on the previous line must be the first char on line + die 'foo'; + __END__ + foo at bzzzt line 201. + + % perl + # line 200 "bzzzt" + eval qq[\n#line 2001 ""\ndie 'foo']; print $@; + __END__ + foo at - line 2001. + + % perl + eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@; + __END__ + foo at foo bar line 200. + + % perl + # line 345 "goop" + eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'"; + print $@; + __END__ + foo at goop line 345. + +=begin meta + +Created: KIMURA Koichi +Updated: Kentaro Shirakata <argra****@ub32*****> + +=end meta + +=cut