perlsyn > 5.40.0 との差分

perlsyn 5.40.0 と 5.20.1 の差分

11
2=encoding utf8
2=encoding euc-jp
33
44=head1 NAME
55X<syntax>
66
77=begin original
88
9perlsyn - Perl syntax: declarations, statements, comments
9perlsyn - Perl syntax
1010
1111=end original
1212
13perlsyn - Perl の文法: 宣言、文、コメント
13perlsyn - Perl の文法
1414
1515=head1 DESCRIPTION
1616
1717=begin original
1818
1919A Perl program consists of a sequence of declarations and statements
2020which run from the top to the bottom. Loops, subroutines, and other
2121control structures allow you to jump around within the code.
2222
2323=end original
2424
2525Perl プログラムは、宣言と文の並びから構成され、上から下へと実行されます。
2626ループ、サブルーチン、その他の制御機構でコードの色々なところに
2727ジャンプできます。
2828
2929=begin original
3030
3131Perl is a B<free-form> language: you can format and indent it however
3232you like. Whitespace serves mostly to separate tokens, unlike
3333languages like Python where it is an important part of the syntax,
3434or Fortran where it is immaterial.
3535
3636=end original
3737
3838Perl は B<自由書式> 言語です: 好きなように整形したりインデントしたり
3939できます。
4040空白が文法の重要な要素である Python や、意味のない Fortran のような言語と
4141異なり、空白はほとんどトークンの分割の役目です。
4242
4343=begin original
4444
4545Many of Perl's syntactic elements are B<optional>. Rather than
4646requiring you to put parentheses around every function call and
4747declare every variable, you can often leave such explicit elements off
4848and Perl will figure out what you meant. This is known as B<Do What I
4949Mean>, abbreviated B<DWIM>. It allows programmers to be B<lazy> and to
5050code in a style with which they are comfortable.
5151
5252=end original
5353
5454Perl の多くの文法要素は B<省略可能> です。
5555全ての関数をかっこで括ったり、全ての変数を宣言したりすることを
5656要求するのではなく、しばしばそのような明示的な要素を置いておいて、
5757Perl にあなたが意味しているところを見つけ出させることができます。
5858これは B<Do What I Mean> と知られ、頭文字を取って B<DWIM> と呼ばれます。
5959これによって、プログラマを B<怠惰> にでき、彼らが快適だと思うスタイルで
6060コーディングできるようにします。
6161
6262=begin original
6363
6464Perl B<borrows syntax> and concepts from many languages: awk, sed, C,
6565Bourne Shell, Smalltalk, Lisp and even English. Other
6666languages have borrowed syntax from Perl, particularly its regular
6767expression extensions. So if you have programmed in another language
6868you will see familiar pieces in Perl. They often work the same, but
6969see L<perltrap> for information about how they differ.
7070
7171=end original
7272
7373Perl は、awk, sed, C, Bourne Shell, Smalltalk, Lisp, 果ては英語といった、
7474多くの言語からコンセプトと B<文法を借用> しています。
7575他の言語も Perl から文法を借用しています; 特に正規表現拡張をです。
7676従って、他の言語でプログラミングしていたなら、Perl にも見たことがあるような
7777ものがあるでしょう。
7878それらはしばしば同じように動作しますが、違う点についての情報は
7979L<perltrap> を参照してください。
8080
8181=head2 Declarations
8282X<declaration> X<undef> X<undefined> X<uninitialized>
8383
8484(宣言)
8585
8686=begin original
8787
8888The only things you need to declare in Perl are report formats and
8989subroutines (and sometimes not even subroutines). A scalar variable holds
9090the undefined value (C<undef>) until it has been assigned a defined
9191value, which is anything other than C<undef>. When used as a number,
9292C<undef> is treated as C<0>; when used as a string, it is treated as
9393the empty string, C<"">; and when used as a reference that isn't being
9494assigned to, it is treated as an error. If you enable warnings,
9595you'll be notified of an uninitialized value whenever you treat
9696C<undef> as a string or a number. Well, usually. Boolean contexts,
9797such as:
9898
9999=end original
100100
101101Perl で宣言が必要なものはレポートフォーマットとサブルーチンだけです
102102(サブルーチンすら宣言が不要な場合もあります)。
103103スカラ変数は、C<undef> 以外の定義された値を代入されるまでは未定義値
104104(C<undef>)となります。
105105数値として使われる場合、C<undef> は C<0> として扱われます;
106106文字列として使われる場合、これは空文字列 C<""> として扱われます;
107107リファレンスとして使われる場合、これは何も代入されていないので、エラーとして
108108扱われます。
109109警告を有効にしているなら、C<undef> を文字列や数値として扱おうとすると
110110未初期化値を指摘されます。
111111ええ、普通は。
112112次のような真偽値コンテキストなら:
113113
114 if ($x) {}
114 if ($a) {}
115115
116116=begin original
117117
118118are exempt from warnings (because they care about truth rather than
119119definedness). Operators such as C<++>, C<-->, C<+=>,
120120C<-=>, and C<.=>, that operate on undefined variables such as:
121121
122122=end original
123123
124124(定義済みかどうかではなく、真かどうかを考慮するので)警告から免れます。
125125未定義の変数を操作する、C<++>, C<-->, C<+=>, C<-=>, C<.=> のような
126126演算子でも:
127127
128 undef $x;
128 undef $a;
129 $x++;
129 $a++;
130130
131131=begin original
132132
133133are also always exempt from such warnings.
134134
135135=end original
136136
137137とすることでもそのような警告から免れます。
138138
139139=begin original
140140
141141A declaration can be put anywhere a statement can, but has no effect on
142142the execution of the primary sequence of statements: declarations all
143143take effect at compile time. All declarations are typically put at
144144the beginning or the end of the script. However, if you're using
145145lexically-scoped private variables created with C<my()>,
146146C<state()>, or C<our()>, you'll have to make sure
147147your format or subroutine definition is within the same block scope
148148as the my if you expect to be able to access those private variables.
149149
150150=end original
151151
152152宣言は、文が置けるところであればどこにでも置くことができますが、
153153基本的な文の並びは実行時には何の効果も持ちません: 宣言はコンパイル時に
154154すべての効果が表れます。
155155典型的にはすべての宣言は、スクリプトの先頭か終端に置かれます。
156156しかしながら、局所変数を C<my()>,C<state()>, or C<our()> を使って作成して
157157レキシカルなスコープを使っているのであれば、フォーマットやサブルーチンの
158158定義を、同じブロックのスコープの中でその局所変数にアクセスすることが
159159可能であるようにしておく必要があるでしょう。
160160
161161=begin original
162162
163163Declaring a subroutine allows a subroutine name to be used as if it were a
164164list operator from that point forward in the program. You can declare a
165165subroutine without defining it by saying C<sub name>, thus:
166166X<subroutine, declaration>
167167
168168=end original
169169
170170サブルーチンの宣言は、プログラムの後のほうにあるサブルーチン名を
171171リスト演算子のように使うことを許します。
172172定義されていないサブルーチンの宣言を、C<sub name> と記述することで
173173宣言できるので、以下のようにできます:
174174X<subroutine, declaration>
175175
176176 sub myname;
177 $me = myname $0 or die "can't get myname";
177 $me = myname $0 or die "can't get myname";
178178
179179=begin original
180180
181181A bare declaration like that declares the function to be a list operator,
182182not a unary operator, so you have to be careful to use parentheses (or
183183C<or> instead of C<||>.) The C<||> operator binds too tightly to use after
184184list operators; it becomes part of the last element. You can always use
185185parentheses around the list operators arguments to turn the list operator
186186back into something that behaves more like a function call. Alternatively,
187187you can use the prototype C<($)> to turn the subroutine into a unary
188188operator:
189189
190190=end original
191191
192192関数の宣言のような裸の宣言はリスト演算子のように働くのであり、
193193単項演算子としてではありません; ですから、かっこ (または C<||> の代わりに
194194C<or>) を使うことには注意してください。
195195C<||> 演算子はリスト演算子の後ろに使うには束縛が強すぎます; 最後の要素の
196196一部になります。
197197リスト演算子の周りをかっこで囲むことでいつでもリスト演算子を
198198関数呼び出しのように振る舞わせるようにできます。
199199あるいは、サブルーチンを単項演算子に変えるためにプロトタイプ
200200C<($)> も使えます:
201201
202202 sub myname ($);
203203 $me = myname $0 || die "can't get myname";
204204
205205=begin original
206206
207207That now parses as you'd expect, but you still ought to get in the habit of
208208using parentheses in that situation. For more on prototypes, see
209209L<perlsub>.
210210
211211=end original
212212
213213これは予想した通りにパースしますが、それでもこのような場合にはかっこを使う
214214習慣を付けるべきです。
215215プロトタイプに関してさらなる情報は、L<perlsub> を参照してください。
216216
217217=begin original
218218
219219Subroutines declarations can also be loaded up with the C<require> statement
220220or both loaded and imported into your namespace with a C<use> statement.
221221See L<perlmod> for details on this.
222222
223223=end original
224224
225225サブルーチンの宣言は C<require> 文を使って詰め込むこともできますし、
226226C<use> 文を使って自分の名前空間にロードしたりインポートしたりすることが
227227できます。
228228これに関する詳細は L<perlmod> を参照してください。
229229
230230=begin original
231231
232232A statement sequence may contain declarations of lexically-scoped
233233variables, but apart from declaring a variable name, the declaration acts
234234like an ordinary statement, and is elaborated within the sequence of
235235statements as if it were an ordinary statement. That means it actually
236236has both compile-time and run-time effects.
237237
238238=end original
239239
240240文の並びはレキシカルスコープを持った変数の宣言を含むことができますが、
241241変数名の宣言とは切り離され、その宣言は通常の文のように振る舞い、
242242それが通常の文であるかのように文の並びに組みこまれます。
243243これは、そういった宣言がコンパイル時の効果と実行時の効果の両方を
244244持っているということです。
245245
246246=head2 Comments
247247X<comment> X<#>
248248
249249(コメント)
250250
251251=begin original
252252
253253Text from a C<"#"> character until the end of the line is a comment,
254254and is ignored. Exceptions include C<"#"> inside a string or regular
255255expression.
256256
257257=end original
258258
259259コメントは C<"#"> 文字から、行末まで続き、その部分は無視されます。
260260例外は、文字列や正規表現の中にある C<"#"> です。
261261
262262=head2 Simple Statements
263263X<statement> X<semicolon> X<expression> X<;>
264264
265265(単純文)
266266
267267=begin original
268268
269269The only kind of simple statement is an expression evaluated for its
270270side-effects. Every simple statement must be terminated with a
271271semicolon, unless it is the final statement in a block, in which case
272272the semicolon is optional. But put the semicolon in anyway if the
273273block takes up more than one line, because you may eventually add
274274another line. Note that there are operators like C<eval {}>, C<sub {}>, and
275275C<do {}> that I<look> like compound statements, but aren't--they're just
276276TERMs in an expression--and thus need an explicit termination when used
277277as the last item in a statement.
278278
279279=end original
280280
281281単純文となる唯一の種類は、その副作用のために評価される式です。
282282すべての単純文は、それがセミコロンを省略することのできるブロックの
283283最後にない限りは文を終端するためのセミコロンがなければなりません。
284284ブロックが二行以上に渡る場合には、とにかくセミコロンを付けてください;
285285なぜなら、別の行を追加する可能性があるからです。
286286C<eval {}>, C<sub {}>, C<do {}> のように、一見複合文のように I<見える> けれども
287287そうではない--これらは単なる式における TERM です--ものがあって、
288288そういったものを文の最後のアイテムとして使った場合には明示的に終端する
289289必要があるのだということに注意してください。
290290
291=head2 Truth and Falsehood
292X<truth> X<falsehood> X<true> X<false> X<!> X<not> X<negation> X<0>
293
294(真偽値)
295
296=begin original
297
298The number 0, the strings C<'0'> and C<"">, the empty list C<()>, and
299C<undef> are all false in a boolean context. All other values are true.
300Negation of a true value by C<!> or C<not> returns a special false value.
301When evaluated as a string it is treated as C<"">, but as a number, it
302is treated as 0. Most Perl operators
303that return true or false behave this way.
304
305=end original
306
307数値 0, 文字列 C<'0'> と C<"">, 空リスト C<()>, C<undef> は全て真偽値
308コンテキストでは偽となります。
309その他の全ての値は真です。
310真の値を C<!> や C<not> で否定すると、特殊な偽の値を返します。
311これを文字列として評価すると C<""> として扱われますが、数値として評価すると
3120 として扱われます。
313真または偽を返す、ほとんど Perl の演算子はこのように振る舞います。
314
291315=head2 Statement Modifiers
292316X<statement modifier> X<modifier> X<if> X<unless> X<while>
293317X<until> X<when> X<foreach> X<for>
294318
295319(文修飾子)
296320
297321=begin original
298322
299323Any simple statement may optionally be followed by a I<SINGLE> modifier,
300324just before the terminating semicolon (or block ending). The possible
301325modifiers are:
302326
303327=end original
304328
305329任意の単純文には、B<一つ> の修飾子を終端のセミコロンの直前(もしくは
306330ブロックの終端の直前)に付けることができます。
307331使うことのできる修飾子は以下の通りです。
308332
309333 if EXPR
310334 unless EXPR
311335 while EXPR
312336 until EXPR
313337 for LIST
314338 foreach LIST
315339 when EXPR
316340
317341=begin original
318342
319343The C<EXPR> following the modifier is referred to as the "condition".
320344Its truth or falsehood determines how the modifier will behave.
321345
322346=end original
323347
324348修飾子に引き続く C<EXPR> は「条件」として参照されます。
325349その真偽値が修飾子の振る舞いを決定します。
326350
327351=begin original
328352
329353C<if> executes the statement once I<if> and only if the condition is
330354true. C<unless> is the opposite, it executes the statement I<unless>
331the condition is true (that is, if the condition is false). See
355the condition is true (that is, if the condition is false).
332L<perldata/Scalar values> for definitions of true and false.
333356
334357=end original
335358
336359C<if> は I<もし> 条件が真の場合にのみ文を実行します。
337360C<unless> は逆で、条件が真 I<でない限り> (つまり、条件が偽なら) 文を
338361実行します。
339真と偽の定義については L<perldata/Scalar values> を参照してください。
340362
341363 print "Basset hounds got long ears" if length $ear >= 10;
342364 go_outside() and play() unless $is_raining;
343365
344366=begin original
345367
346368The C<for(each)> modifier is an iterator: it executes the statement once
347369for each item in the LIST (with C<$_> aliased to each item in turn).
348There is no syntax to specify a C-style for loop or a lexically scoped
349iteration variable in this form.
350370
351371=end original
352372
353373C<for(each)> 修飾子は反復子です:
354374LIST の値それぞれ毎に文を実行します(実行中は C<$_> がそれぞれの値の
355375エイリアスとなります)。
356この形式で C 風のループやレキシカルスコープの繰り返し変数を
357指定する文法はありません。
358376
359377 print "Hello $_!\n" for qw(world Dolly nurse);
360378
361379=begin original
362380
363381C<while> repeats the statement I<while> the condition is true.
364Postfix C<while> has the same magic treatment of some kinds of condition
365that prefix C<while> has.
366382C<until> does the opposite, it repeats the statement I<until> the
367383condition is true (or while the condition is false):
368384
369385=end original
370386
371387C<while> は条件が真 I<の間> 文を繰り返します。
372後置 C<while> は、ある種の条件において、前置 C<while> と同じ
373マジカルな処理をします。
374388C<until> は逆で、条件が真 I<になるまで> (つまり条件が偽の間) 文を
375389繰り返します:
376390
377391 # Both of these count from 0 to 10.
378392 print $i++ while $i <= 10;
379393 print $j++ until $j > 10;
380394
381395=begin original
382396
383397The C<while> and C<until> modifiers have the usual "C<while> loop"
384398semantics (conditional evaluated first), except when applied to a
385399C<do>-BLOCK (or to the Perl4 C<do>-SUBROUTINE statement), in
386400which case the block executes once before the conditional is
387401evaluated.
388402
389403=end original
390404
391405修飾子 C<while> と C<until> は、一般的な "C<while> loop" の意味を
392406持っています(条件が最初に評価される)が、C<do>-ブロック(もしくは Perl4 の
393407C<do>-サブルーチン文)に適用されるときは例外で、
394408このときは条件が評価されるよりも前に、一度ブロックが実行されます。
395409
396410=begin original
397411
398412This is so that you can write loops like:
399413
400414=end original
401415
402416このため、次のようなループを記述することができます:
403417
404418 do {
405 $line = <STDIN>;
419 $line = <STDIN>;
406 ...
420 ...
407421 } until !defined($line) || $line eq ".\n"
408422
409423=begin original
410424
411425See L<perlfunc/do>. Note also that the loop control statements described
412426later will I<NOT> work in this construct, because modifiers don't take
413427loop labels. Sorry. You can always put another block inside of it
414(for C<next>/C<redo>) or around it (for C<last>) to do that sort of thing.
428(for C<next>) or around it (for C<last>) to do that sort of thing.
429For C<next>, just double the braces:
415430X<next> X<last> X<redo>
416431
417432=end original
418433
419434L<perlfunc/do> を参照してください。
420435後述するループの制御文は、修飾子がループラベルを取らないために
421436この構造文では I<動作しない> ということにも注意してください。
422437申し訳ない。
423438こういった場合に対処するのに別のブロックを内側に入れたり(C<next> の場合)、
424別のブロックで囲む(C<last>/C<redo> の場合)という方法が常に使えます。
439別のブロックで囲む(C<last> の場合)という方法が常に使えます。
440C<next> では単に中かっこを二重にします:
425441X<next> X<last> X<redo>
426442
427=begin original
428
429For C<next> or C<redo>, just double the braces:
430
431=end original
432
433C<next> や C<redo> では単に中かっこを二重にします:
434
435443 do {{
436 next if $x == $y;
444 next if $x == $y;
437 # do something here
445 # do something here
438446 }} until $x++ > $z;
439447
440448=begin original
441449
442For C<last>, you have to be more elaborate and put braces around it:
450For C<last>, you have to be more elaborate:
443451X<last>
444452
445453=end original
446454
447C<last> の場合は、もっと念入りにする必要があり、中かっこで囲みます:
455C<last> の場合は、もっと念入りにする必要があります:
448456
449 {
457 LOOP: {
450 do {
458 do {
451 last if $x == $y**2;
459 last if $x = $y**2;
452 # do something here
460 # do something here
453 } while $x++ <= $z;
461 } while $x++ <= $z;
454462 }
455463
456464=begin original
457465
458If you need both C<next> and C<last>, you have to do both and also use a
459loop label:
460
461=end original
462
463C<next> と C<last> の両方が必要な場合、両方を使ってさらにループラベルを
464使う必要があります:
465
466 LOOP: {
467 do {{
468 next if $x == $y;
469 last LOOP if $x == $y**2;
470 # do something here
471 }} until $x++ > $z;
472 }
473
474=begin original
475
476466B<NOTE:> The behaviour of a C<my>, C<state>, or
477467C<our> modified with a statement modifier conditional
478468or loop construct (for example, C<my $x if ...>) is
479469B<undefined>. The value of the C<my> variable may be C<undef>, any
480470previously assigned value, or possibly anything else. Don't rely on
481471it. Future versions of perl might do something different from the
482472version of perl you try it out on. Here be dragons.
483473X<my>
484474
485475=end original
486476
487477B<注意:> (C<my $x if ...> のような) 条件構造やループ構造で修飾された
488478C<my> C<state>,C<our> 文の振る舞いは B<未定義> です。
489479C<my> 変数の値は C<undef> かも知れませんし、以前に代入された値かも
490480知れませんし、その他の如何なる値の可能性もあります。
491481この値に依存してはいけません。
492482perl の将来のバージョンでは現在のバージョンとは何か違うかも知れません。
493483ここには厄介なものがいます。
494484X<my>
495485
496486=begin original
497487
498488The C<when> modifier is an experimental feature that first appeared in Perl
4994895.14. To use it, you should include a C<use v5.14> declaration.
500490(Technically, it requires only the C<switch> feature, but that aspect of it
501491was not available before 5.14.) Operative only from within a C<foreach>
502492loop or a C<given> block, it executes the statement only if the smartmatch
503493C<< $_ ~~ I<EXPR> >> is true. If the statement executes, it is followed by
504494a C<next> from inside a C<foreach> and C<break> from inside a C<given>.
505495
506496=end original
507497
508498C<when> 修飾子は Perl 5.14 で最初に現れた実験的機能です。
509499使うには、C<use v5.14> 宣言を含めます。
510500(技術的には、C<switch> 機能だけが必要ですが、この観点では 5.14 より前では
511501利用できません。)
512502C<foreach> ループか C<given> ブロックの内側でのみ動作可能で、
513503スマートマッチング C<< $_ ~~ I<EXPR> >> が真の場合にのみ実行されます。
514504文が実行されると、C<foreach> の内側からは C<next> に、C<given> の
515505内側からは C<break> に引き続きます。
516506
517507=begin original
518508
519509Under the current implementation, the C<foreach> loop can be
520510anywhere within the C<when> modifier's dynamic scope, but must be
521within the C<given> block's lexical scope. This restriction may
511within the C<given> block's lexical scope. This restricted may
522be relaxed in a future release. See L</"Switch Statements"> below.
512be relaxed in a future release. See L<"Switch Statements"> below.
523513
524514=end original
525515
526516現在の実装では、C<foreach> ループは C<when> 修飾子の動的スコープの内側の
527517どこでも使えますが、C<given> ブロックのレキシカルスコープの内側で
528518なければなりません。
529519この制限は将来のリリースで緩和されるかもしれません。
530後述する L</"Switch Statements"> を参照してください。
520後述する L<"Switch Statements"> を参照してください。
531521
532522=head2 Compound Statements
533523X<statement, compound> X<block> X<bracket, curly> X<curly bracket> X<brace>
534524X<{> X<}> X<if> X<unless> X<given> X<while> X<until> X<foreach> X<for> X<continue>
535525
536526(複合文)
537527
538528=begin original
539529
540530In Perl, a sequence of statements that defines a scope is called a block.
541531Sometimes a block is delimited by the file containing it (in the case
542532of a required file, or the program as a whole), and sometimes a block
543533is delimited by the extent of a string (in the case of an eval).
544534
545535=end original
546536
547537Perl では、スコープを定義するような文の並びをブロックと呼びます。
548538ブロックはそれを含むファイルによって範囲が定められることがあります
549539(ファイルが require されたときか、プログラム全体としての場合)し、
550540文字列の展開によって範囲が定められる(eval の場合)こともあります。
551541
552542=begin original
553543
554But generally, a block is delimited by curly brackets, also known as
544But generally, a block is delimited by curly brackets, also known as braces.
555braces. We will call this syntactic construct a BLOCK. Because enclosing
545We will call this syntactic construct a BLOCK.
556braces are also the syntax for hash reference constructor expressions
557(see L<perlref>), you may occasionally need to disambiguate by placing a
558C<;> immediately after an opening brace so that Perl realises the brace
559is the start of a block. You will more frequently need to disambiguate
560the other way, by placing a C<+> immediately before an opening brace to
561force it to be interpreted as a hash reference constructor expression.
562It is considered good style to use these disambiguating mechanisms
563liberally, not only when Perl would otherwise guess incorrectly.
564546
565547=end original
566548
567549しかし一般的には、ブロックは中かっこによって範囲が定められます。
568550この構文的な構造をブロックと呼びます。
569中かっこによる囲みはハッシュリファレンス初期化表現 (L<perlref> 参照) の
570文法でもあるので、中かっこがブロックの開始であることを Perl が分かるように、
571時々開き中かっこの直後に C<;> を置くことで曖昧さをなくす
572必要があるかもしれません。
573より頻繁には、ハッシュリファレンス初期化表現として解釈されることを
574強制するために、開き中かっこの直前に C<+> を置くことで逆方向に
575曖昧さをなくす必要があるかも知れません。
576これらのあいまいさをなくす機構は、Perl が間違って推測するときだけではなく、
577より安全に使うのがよいスタイルと考えられています。
578551
579552=begin original
580553
581554The following compound statements may be used to control flow:
582555
583556=end original
584557
585558以下に挙げる複合文を制御フローとして使うことができます:
586559
587560 if (EXPR) BLOCK
588561 if (EXPR) BLOCK else BLOCK
589562 if (EXPR) BLOCK elsif (EXPR) BLOCK ...
590563 if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
591564
592565 unless (EXPR) BLOCK
593566 unless (EXPR) BLOCK else BLOCK
594567 unless (EXPR) BLOCK elsif (EXPR) BLOCK ...
595568 unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
596569
597570 given (EXPR) BLOCK
598571
599572 LABEL while (EXPR) BLOCK
600573 LABEL while (EXPR) BLOCK continue BLOCK
601574
602575 LABEL until (EXPR) BLOCK
603576 LABEL until (EXPR) BLOCK continue BLOCK
604577
605578 LABEL for (EXPR; EXPR; EXPR) BLOCK
606579 LABEL for VAR (LIST) BLOCK
607580 LABEL for VAR (LIST) BLOCK continue BLOCK
608581
609582 LABEL foreach (EXPR; EXPR; EXPR) BLOCK
610583 LABEL foreach VAR (LIST) BLOCK
611584 LABEL foreach VAR (LIST) BLOCK continue BLOCK
612585
613586 LABEL BLOCK
614587 LABEL BLOCK continue BLOCK
615588
616589 PHASE BLOCK
617590
618591=begin original
619592
620As of Perl 5.36, you can iterate over multiple values at a time by specifying
593The experimental C<given> statement is I<not automatically enabled>; see
621a list of lexicals within parentheses:
622
623=end original
624
625Perl 5.36 から、かっこの中にレキシカル変数のリストを指定することで、
626一度に複数の値を反復できます:
627
628 LABEL for my (VAR, VAR) (LIST) BLOCK
629 LABEL for my (VAR, VAR) (LIST) BLOCK continue BLOCK
630 LABEL foreach my (VAR, VAR) (LIST) BLOCK
631 LABEL foreach my (VAR, VAR) (LIST) BLOCK continue BLOCK
632
633=begin original
634
635If enabled by the C<try> feature, the following may also be used
636
637=end original
638
639実験的な C<try> 機能によって有効の場合、次のものも使えます:
640
641 try BLOCK catch (VAR) BLOCK
642 try BLOCK catch (VAR) BLOCK finally BLOCK
643
644=begin original
645
646The experimental C<given> statement is I<not automatically enabled>; see
647594L</"Switch Statements"> below for how to do so, and the attendant caveats.
648595
649596=end original
650597
651実験的な C<given> 文は I<自動的に有効になりません>; その方法と、それに
598実験的な C<given> 文は I<自動的に有効になりません>; そうするため
652伴う注意点については後述する L</"Switch Statements"> を参照してください。
599方法と、付随する問題点については後述する L</"Switch Statements"> を
600参照してください。
653601
654602=begin original
655603
656604Unlike in C and Pascal, in Perl these are all defined in terms of BLOCKs,
657605not statements. This means that the curly brackets are I<required>--no
658606dangling statements allowed. If you want to write conditionals without
659607curly brackets, there are several other ways to do it. The following
660608all do the same thing:
661609
662610=end original
663611
664612C や Pascal とは異なり、Perl ではブロックを取るように
665613定義されていて文を取るのではありません。
666614つまり、中かっこは I<必要なもの> です -- 曖昧な文が許されません。
667615中かっこなしの条件文を使いたいのであれば、いくつかのやり方があります。
668616以下の全ては同じことです:
669617
670618 if (!open(FOO)) { die "Can't open $FOO: $!" }
671619 die "Can't open $FOO: $!" unless open(FOO);
672620 open(FOO) || die "Can't open $FOO: $!";
673621 open(FOO) ? () : die "Can't open $FOO: $!";
674 # a bit exotic, that last one
622 # a bit exotic, that last one
675623
676624=begin original
677625
678626The C<if> statement is straightforward. Because BLOCKs are always
679627bounded by curly brackets, there is never any ambiguity about which
680628C<if> an C<else> goes with. If you use C<unless> in place of C<if>,
681629the sense of the test is reversed. Like C<if>, C<unless> can be followed
682630by C<else>. C<unless> can even be followed by one or more C<elsif>
683631statements, though you may want to think twice before using that particular
684632language construct, as everyone reading your code will have to think at least
685633twice before they can understand what's going on.
686634
687635=end original
688636
689637C<if> 文は明解です。
690638ブロックは常に中かっこで区切られるので、C<if> と C<else> の対応が
691639曖昧になるようなことは決してありません。
692640C<unless> を C<if> の代わりに使うと、検査を反転します。
693641C<if> と同様、C<unless> は C<else> に引き続くことができます。
694642C<unless> は一つまたはそれ以上の C<elsif> に引き続くことすらできますが、
695643この特定の言語構文を使う前に二倍考えたいでしょう; あなたのコードを読む
696644誰もが何が行われているのかを理解する前に少なくとも二倍考える必要が
697645あるからです。
698646
699647=begin original
700648
701649The C<while> statement executes the block as long as the expression is
702true.
650L<true|/"Truth and Falsehood">.
703651The C<until> statement executes the block as long as the expression is
704652false.
705653The LABEL is optional, and if present, consists of an identifier followed
706654by a colon. The LABEL identifies the loop for the loop control
707655statements C<next>, C<last>, and C<redo>.
708656If the LABEL is omitted, the loop control statement
709657refers to the innermost enclosing loop. This may include dynamically
710searching through your call-stack at run time to find the LABEL. Such
658looking back your call-stack at run time to find the LABEL. Such
711659desperate behavior triggers a warning if you use the C<use warnings>
712660pragma or the B<-w> flag.
713661
714662=end original
715663
716C<while> 文は、式が真である間、ブロックを実行します。
664C<while> 文は、式が L<|/"Truth and Falsehood"> である間、ブロックを
665実行します。
717666C<until> 文は、式が偽である間、ブロックを実行します。
718667LABEL は省略可能ですが、ある場合には、コロンを伴った識別子になります。
719668LABEL は C<next>、C<last>、C<redo> といったループ制御文のループを規定します。
720669LABEL が省略された場合、ループ制御文はそれを含むループの中で最も内側の
721670ループを参照します。
722これは、実行時に LABEL を検出するための呼び出しスタック動的検索すること
671これは、実行時に LABEL を検出するための呼び出しスタック動的な後戻り検索を
723672含むことができます。
724673そのような推奨されない振る舞いは、C<use warnings> プラグマや B<-w> フラグを
725674使った場合には警告を引き起こします。
726675
727676=begin original
728677
729If the condition expression of a C<while> statement is based
730on any of a group of iterative expression types then it gets
731some magic treatment. The affected iterative expression types
732are L<C<readline>|perlfunc/readline EXPR>, the L<C<< <FILEHANDLE>
733>>|perlop/"I/O Operators"> input operator, L<C<readdir>|perlfunc/readdir
734DIRHANDLE>, L<C<glob>|perlfunc/glob EXPR>, the L<C<< <PATTERN>
735>>|perlop/"I/O Operators"> globbing operator, and L<C<each>|perlfunc/each
736HASH>. If the condition expression is one of these expression types, then
737the value yielded by the iterative operator will be implicitly assigned
738to C<$_>. If the condition expression is one of these expression types
739or an explicit assignment of one of them to a scalar, then the condition
740actually tests for definedness of the expression's value, not for its
741regular truth value.
742
743=end original
744
745C<while> 文の条件式が反復式型のグループの一つの場合、
746マジカルな扱いを受けます。
747影響を受ける反復式型は、
748L<C<readline>|perlfunc/readline EXPR>、L<C<< <FILEHANDLE>
749>>|perlop/"I/O Operators"> 入力反復子、L<C<readdir>|perlfunc/readdir
750DIRHANDLE>、L<C<glob>|perlfunc/glob EXPR>、L<C<< <PATTERN>
751>>|perlop/"I/O Operators"> グロブ演算子、L<C<each>|perlfunc/each
752HASH> です。
753条件式がこれらの式の型の一つの場合、反復演算子によって
754取り出された値は暗黙に C<$_> に代入されます。
755条件式がこれらの式の型の一つか、これらの一つからスカラへの明示的な代入の
756場合、条件は実際には通常の真の値かどうかではなく、式の値が
757定義値かどうかをテストします。
758
759=begin original
760
761678If there is a C<continue> BLOCK, it is always executed just before the
762679conditional is about to be evaluated again. Thus it can be used to
763680increment a loop variable, even when the loop has been continued via
764681the C<next> statement.
765682
766683=end original
767684
768685C<continue> ブロックが存在する場合、
769686常に条件が再評価される直前に実行されます。
770687したがって、このブロックをループ変数のインクリメントのために
771688使うことができます;
772689これは、ループがC<next>文を通して継続されるときでも実行されます。
773690
774691=begin original
775692
776When a block is preceded by a compilation phase keyword such as C<BEGIN>,
693When a block is preceding by a compilation phase keyword such as C<BEGIN>,
777694C<END>, C<INIT>, C<CHECK>, or C<UNITCHECK>, then the block will run only
778695during the corresponding phase of execution. See L<perlmod> for more details.
779696
780697=end original
781698
782699ブロックの前に C<BEGIN>, C<END>, C<INIT>, C<CHECK>, C<UNITCHECK> のような
783700コンパイルフェーズキーワードが前置されると、ブロックは対応する実行フェーズの
784701間にだけ実行されます。
785702さらなる詳細については L<perlmod> を参照してください。
786703
787704=begin original
788705
789706Extension modules can also hook into the Perl parser to define new
790707kinds of compound statements. These are introduced by a keyword which
791708the extension recognizes, and the syntax following the keyword is
792709defined entirely by the extension. If you are an implementor, see
793710L<perlapi/PL_keyword_plugin> for the mechanism. If you are using such
794711a module, see the module's documentation for details of the syntax that
795712it defines.
796713
797714=end original
798715
799716エクステンションモジュールは新しい種類の複合文を定義するために
800717Perl パーサをフックできます。
801718これらはエクステンションが認識するキーワードで導入され、キーワードに
802719引き続く文法は完全にエクステンションで定義されます。
803720もしあなたが実装車なら、仕組みについては L<perlapi/PL_keyword_plugin> を
804721参照してください。
805722あなたがそのようなモジュールを使うなら、定義されている文法の詳細については
806723そのモジュールの文書を参照してください。
807724
808725=head2 Loop Control
809726X<loop control> X<loop, control> X<next> X<last> X<redo> X<continue>
810727
811728(ループ制御)
812729
813730=begin original
814731
815732The C<next> command starts the next iteration of the loop:
816733
817734=end original
818735
819736C<next> コマンドはループの次の繰り返しを開始します:
820737
821738 LINE: while (<STDIN>) {
822 next LINE if /^#/; # discard comments
739 next LINE if /^#/; # discard comments
823 ...
740 ...
824741 }
825742
826743=begin original
827744
828745The C<last> command immediately exits the loop in question. The
829746C<continue> block, if any, is not executed:
830747
831748=end original
832749
833750C<last> コマンドはループから即座に脱出します。
834751C<continue> ブロックがあっても、それは実行されません:
835752
836753 LINE: while (<STDIN>) {
837 last LINE if /^$/; # exit when done with header
754 last LINE if /^$/; # exit when done with header
838 ...
755 ...
839756 }
840757
841758=begin original
842759
843760The C<redo> command restarts the loop block without evaluating the
844761conditional again. The C<continue> block, if any, is I<not> executed.
845762This command is normally used by programs that want to lie to themselves
846763about what was just input.
847764
848765=end original
849766
850767C<redo> コマンドは、条件の再評価をすることなしにループブロックの
851768再実行を行います。
852769C<continue> ブロックがあっても、それは I<実行されません>。
853770このコマンドは通常、プログラムに対する入力に関してプログラム自身を
854771だましたいといったときに使われます。
855772
856773=begin original
857774
858775For example, when processing a file like F</etc/termcap>.
859776If your input lines might end in backslashes to indicate continuation, you
860777want to skip ahead and get the next record.
861778
862779=end original
863780
864781たとえば、F</etc/termcap> のようなファイルを処理することを
865782考えてみましょう。
866783もし入力された行の行末が継続を示すバックスラッシュであった場合、先へ進んで
867784次のレコードを取り出したいと思うでしょう。
868785
869786 while (<>) {
870 chomp;
787 chomp;
871 if (s/\\$//) {
788 if (s/\\$//) {
872 $_ .= <>;
789 $_ .= <>;
873 redo unless eof();
790 redo unless eof();
874 }
791 }
875 # now process $_
792 # now process $_
876793 }
877794
878795=begin original
879796
880797which is Perl shorthand for the more explicitly written version:
881798
882799=end original
883800
884801これは Perl の省略記法で、もっとはっきりと書くと以下のようになります:
885802
886803 LINE: while (defined($line = <ARGV>)) {
887 chomp($line);
804 chomp($line);
888 if ($line =~ s/\\$//) {
805 if ($line =~ s/\\$//) {
889 $line .= <ARGV>;
806 $line .= <ARGV>;
890 redo LINE unless eof(); # not eof(ARGV)!
807 redo LINE unless eof(); # not eof(ARGV)!
891 }
808 }
892 # now process $line
809 # now process $line
893810 }
894811
895812=begin original
896813
897814Note that if there were a C<continue> block on the above code, it would
898815get executed only on lines discarded by the regex (since redo skips the
899816continue block). A continue block is often used to reset line counters
900817or C<m?pat?> one-time matches:
901818
902819=end original
903820
904821上記の例で C<continue> ブロックがあったとしたら、それは
905822(redo は continue ブロックをスキップするので) 正規表現によって
906823捨てられた行だけが実行されるということに注意してください。
907824continue ブロックは行カウンターをリセットするとか、
908825一度だけマッチする C<m?pat?> をリセットするのに使われます。
909826
910827 # inspired by :1,$g/fred/s//WILMA/
911828 while (<>) {
912 m?(fred)? && s//WILMA $1 WILMA/;
829 m?(fred)? && s//WILMA $1 WILMA/;
913 m?(barney)? && s//BETTY $1 BETTY/;
830 m?(barney)? && s//BETTY $1 BETTY/;
914 m?(homer)? && s//MARGE $1 MARGE/;
831 m?(homer)? && s//MARGE $1 MARGE/;
915832 } continue {
916 print "$ARGV $.: $_";
833 print "$ARGV $.: $_";
917 close ARGV if eof; # reset $.
834 close ARGV if eof; # reset $.
918 reset if eof; # reset ?pat?
835 reset if eof; # reset ?pat?
919836 }
920837
921838=begin original
922839
923840If the word C<while> is replaced by the word C<until>, the sense of the
924841test is reversed, but the conditional is still tested before the first
925842iteration.
926843
927844=end original
928845
929846C<while> を C<until> で置き換えた場合検査の意味は逆転しますが、
930847繰り返しが実行されるより前に条件が検査されることは変わりありません。
931848
932849=begin original
933850
934851Loop control statements don't work in an C<if> or C<unless>, since
935852they aren't loops. You can double the braces to make them such, though.
936853
937854=end original
938855
939856ループ制御文は C<if> や C<unless> 中では動作しません;
940857なぜならそこはループではないからです。
941858しかし中かっこを二重にしてこれに対処することはできます。
942859
943860 if (/pattern/) {{
944 last if /fred/;
861 last if /fred/;
945 next if /barney/; # same effect as "last",
862 next if /barney/; # same effect as "last",
946 # but doesn't document as well
863 # but doesn't document as well
947 # do something here
864 # do something here
948865 }}
949866
950867=begin original
951868
952869This is caused by the fact that a block by itself acts as a loop that
953executes once, see L</"Basic BLOCKs">.
870executes once, see L<"Basic BLOCKs">.
954871
955872=end original
956873
957874これは、ブロック自身は一度だけ実行されるループとして動作するからです;
958L</"Basic BLOCKs"> を参照してください。
875L<"Basic BLOCKs"> を参照してください。
959876
960877=begin original
961878
962879The form C<while/if BLOCK BLOCK>, available in Perl 4, is no longer
963available. Replace any occurrence of C<if BLOCK> by C<if (do BLOCK)>.
880available. Replace any occurrence of C<if BLOCK> by C<if (do BLOCK)>.
964881
965882=end original
966883
967884Perl 4 では使うことのできた C<while/if BLOCK BLOCK> という形式は、
968885もはや使うことができません。
969886C<if BLOCK> の部分を C<if (do BLOCK)> で置き換えてください。
970887
971888=head2 For Loops
972889X<for> X<foreach>
973890
974891(for ループ)
975892
976893=begin original
977894
978895Perl's C-style C<for> loop works like the corresponding C<while> loop;
979896that means that this:
980897
981898=end original
982899
983900Perl の C 形式の C<for> ループは、対応する C<while> ループと同様に
984901動作します; つまり、以下のものは:
985902
986903 for ($i = 1; $i < 10; $i++) {
987 ...
904 ...
988905 }
989906
990907=begin original
991908
992909is the same as this:
993910
994911=end original
995912
996913以下のものと同じです:
997914
998915 $i = 1;
999916 while ($i < 10) {
1000 ...
917 ...
1001918 } continue {
1002 $i++;
919 $i++;
1003920 }
1004921
1005922=begin original
1006923
1007924There is one minor difference: if variables are declared with C<my>
1008925in the initialization section of the C<for>, the lexical scope of
1009926those variables is exactly the C<for> loop (the body of the loop
1010and the control sections). To illustrate:
927and the control sections).
1011928X<my>
1012929
1013930=end original
1014931
1015932小さな違いが一つあります: C<for> の初期化部で C<my> を使って変数が
1016933宣言された場合、この変数のレキシカルスコープは C<for> ループ
1017934(ループ本体と制御部) と完全に同じです。
1018図示すると:
1019935X<my>
1020936
1021 my $i = 'samba';
1022 for (my $i = 1; $i <= 4; $i++) {
1023 print "$i\n";
1024 }
1025 print "$i\n";
1026
1027937=begin original
1028938
1029when executed, gives:
1030
1031=end original
1032
1033実行すると、次のものになります:
1034
1035 1
1036 2
1037 3
1038 4
1039 samba
1040
1041=begin original
1042
1043939As a special case, if the test in the C<for> loop (or the corresponding
1044940C<while> loop) is empty, it is treated as true. That is, both
1045941
1046942=end original
1047943
1048944特別な場合として、もし C<for> ループ (または対応する C<while> ループ) の
1049945テストが空なら、真として扱われます。
1050946つまり、次のもの
1051947
1052948 for (;;) {
1053 ...
949 ...
1054950 }
1055951
1056952=begin original
1057953
1058954and
1059955
1060956=end original
1061957
1062958および
1063959
1064960 while () {
1065 ...
961 ...
1066962 }
1067963
1068964=begin original
1069965
1070966are treated as infinite loops.
1071967
1072968=end original
1073969
1074970は無限ループとして扱われます。
1075971
1076972=begin original
1077973
1078974Besides the normal array index looping, C<for> can lend itself
1079975to many other interesting applications. Here's one that avoids the
1080976problem you get into if you explicitly test for end-of-file on
1081977an interactive file descriptor causing your program to appear to
1082978hang.
1083979X<eof> X<end-of-file> X<end of file>
1084980
1085981=end original
1086982
1087983通常の、配列に対する添え字付けのループのほかにも、C<for> は他の
1088984多くの興味深いアプリケーションのために借用することができます。
1089985以下の例は、対話的なファイル記述子の終端を明示的に検査してしまうと
1090986プログラムをハングアップしたように見えてしまう問題を回避するものです。
1091987X<eof> X<end-of-file> X<end of file>
1092988
1093989 $on_a_tty = -t STDIN && -t STDOUT;
1094990 sub prompt { print "yes? " if $on_a_tty }
1095991 for ( prompt(); <STDIN>; prompt() ) {
1096 # do something
992 # do something
1097993 }
1098994
1099995=begin original
1100996
1101The condition expression of a C<for> loop gets the same magic treatment of
997Using C<readline> (or the operator form, C<< <EXPR> >>) as the
1102C<readline> et al that the condition expression of a C<while> loop gets.
998conditional of a C<for> loop is shorthand for the following. This
999behaviour is the same as a C<while> loop conditional.
1000X<readline> X<< <> >>
11031001
11041002=end original
11051003
1106C<for> ループの条件式は、C<while> ループの条件で行われるもと同様、
1004C<for> ループの条件として C<readline> (または演算子形式の C<< <EXPR> >>) を
1107C<readline> マジカルな扱い行われます。
1005使う場合、以下ように省略形使えます。
1006この振る舞いは C<while> ループ条件と同じです。
1007X<readline> X<< <> >>
11081008
1009 for ( prompt(); defined( $_ = <STDIN> ); prompt() ) {
1010 # do something
1011 }
1012
11091013=head2 Foreach Loops
11101014X<for> X<foreach>
11111015
11121016(foreach ループ)
11131017
11141018=begin original
11151019
1116The C<foreach> loop iterates over a normal list value and sets the scalar
1020The C<foreach> loop iterates over a normal list value and sets the
11171021variable VAR to be each element of the list in turn. If the variable
11181022is preceded with the keyword C<my>, then it is lexically scoped, and
11191023is therefore visible only within the loop. Otherwise, the variable is
11201024implicitly local to the loop and regains its former value upon exiting
11211025the loop. If the variable was previously declared with C<my>, it uses
11221026that variable instead of the global one, but it's still localized to
1123the loop. This implicit localization occurs I<only> for non C-style
1027the loop. This implicit localization occurs I<only> in a C<foreach>
1124loops.
1028loop.
11251029X<my> X<local>
11261030
11271031=end original
11281032
1129C<foreach> ループは 通常のリスト値に対しての繰り返しを行い、スカラ変数 VAR に
1033C<foreach> ループは 通常のリスト値に対しての繰り返しを行い、変数 VAR に
11301034リストの要素を繰り返し一回に一つずつセットします。
11311035変数の前に C<my> というキーワードが置かれていた場合、その変数は
11321036レキシカルスコープを持ち、したがってそれはループの中でのみ可視となります。
11331037このキーワードがなければ、変数はループに対してローカルとなり、ループを
11341038抜けた後で以前の値が再度取得されます。
11351039変数が事前に C<my> を使って宣言されていたならば、グローバルなものの
11361040代わりにその変数を使いますが、それもループにローカルなものとなります。
1137この暗黙のローカル化は C 形式のループの中で I<のみ> 起きます。
1041この暗黙のローカル化は C<foreach> の中で I<のみ> 起きます。
11381042X<my> X<local>
11391043
11401044=begin original
11411045
11421046The C<foreach> keyword is actually a synonym for the C<for> keyword, so
11431047you can use either. If VAR is omitted, C<$_> is set to each value.
11441048X<$_>
11451049
11461050=end original
11471051
11481052
11491053C<foreach> は実際には C<for> の同義語なので、どちらでも使えます。
11501054VAR が省略された場合には、C<$_> に値が設定されます。
11511055X<$_>
11521056
11531057=begin original
11541058
11551059If any element of LIST is an lvalue, you can modify it by modifying
11561060VAR inside the loop. Conversely, if any element of LIST is NOT an
11571061lvalue, any attempt to modify that element will fail. In other words,
11581062the C<foreach> loop index variable is an implicit alias for each item
11591063in the list that you're looping over.
11601064X<alias>
11611065
11621066=end original
11631067
11641068LIST の要素が左辺値であった場合、ループの中で VAR を変更することにより、
11651069対応する値を変更することができます。
11661070逆に、LIST の要素が左辺値でない場合は、この要素を修正しようとしても
11671071失敗します。
11681072言い換えると、C<foreach> ループの帰納変数がループの対象となっている
11691073リスト中の個々のアイテムに対するエイリアスになっているからです。
11701074X<alias>
11711075
11721076=begin original
11731077
11741078If any part of LIST is an array, C<foreach> will get very confused if
11751079you add or remove elements within the loop body, for example with
1176C<splice>. So don't do that.
1080C<splice>. So don't do that.
11771081X<splice>
11781082
11791083=end original
11801084
11811085LIST のいずれかの部分が配列であった場合に、たとえば C<splice> を使って
11821086ループの本体でその要素を削除したりあるいは追加したりすると
11831087C<foreach> は非常に混乱してしまいます。
11841088ですからそういうことをしてはいけません。
11851089X<splice>
11861090
11871091=begin original
11881092
11891093C<foreach> probably won't do what you expect if VAR is a tied or other
1190special variable. Don't do that either.
1094special variable. Don't do that either.
11911095
11921096=end original
11931097
11941098VAR が tie されていたりあるいは他の特殊変数であった場合には
11951099C<foreach> はあなたのもくろみどおりには動かないでしょう。
11961100こういうこともしてはいけません。
11971101
11981102=begin original
11991103
1200As of Perl 5.22, there is an experimental variant of this loop that accepts
1201a variable preceded by a backslash for VAR, in which case the items in the
1202LIST must be references. The backslashed variable will become an alias
1203to each referenced item in the LIST, which must be of the correct type.
1204The variable needn't be a scalar in this case, and the backslash may be
1205followed by C<my>. To use this form, you must enable the C<refaliasing>
1206feature via C<use feature>. (See L<feature>. See also L<perlref/Assigning
1207to References>.)
1208
1209=end original
1210
1211Perl 5.22 から、VAR に逆スラッシュを前置する変数を受け付けるという
1212このループの実験的なバリエーションがあります; この場合 LIST のアイテムは
1213リファレンスでなければなりません。
1214逆スラッシュつき変数は LIST の中のアイテムへのリファレンスとなるエイリアスに
1215なり; 正しい方でなければなりません。
1216この場合変数はスカラである必要はなく、逆スラッシュには C<my> が
1217引き続くことができます。
1218この形式を使うには、C<use feature> で C<refaliasing> 機能を
1219有効にしなければなりません。
1220(L<feature> を参照してください。
1221L<perlref/Assigning to References> も参照してください。)
1222
1223=begin original
1224
1225As of Perl 5.36, you can iterate over multiple values at a time.
1226You can only iterate with lexical scalars as the iterator variables - unlike
1227list assignment, it's not possible to use C<undef> to signify a value that
1228isn't wanted. This is a limitation of the current implementation, and might
1229be changed in the future.
1230
1231=end original
1232
1233Perl 5.36 から、一度に複数の値を反復できます。
1234反復変数としてレキシカルスカラのみ反復できます - リスト代入と異なり、
1235不要な値を示すために C<undef> を使うことは出来ません。
1236これは現在の実装の制限で、将来変更されるかもしれません。
1237
1238=begin original
1239
1240If the size of the LIST is not an exact multiple of the number of iterator
1241variables, then on the last iteration the "excess" iterator variables are
1242aliases to C<undef>, as if the LIST had C<, undef> appended as many times as
1243needed for its length to become an exact multiple. This happens whether
1244LIST is a literal LIST or an array - ie arrays are not extended if their
1245size is not a multiple of the iteration size, consistent with iterating an
1246array one-at-a-time. As these padding elements are not lvalues, attempting
1247to modify them will fail, consistent with the behaviour when iterating a
1248list with literal C<undef>s. If this is not the behaviour you desire, then
1249before the loop starts either explicitly extend your array to be an exact
1250multiple, or explicitly throw an exception.
1251
1252=end original
1253
1254LIST の大きさが反復変数の数の整数倍でない場合、
1255最後の反復では「超過した」反復変数は C<undef> への別名になります;
1256LIST の長さが整数倍になるのに必要なだけ C<, undef> が
1257追加されているかのようになります。
1258これは LIST がリテラルな LIST でも配列でも起こります - つまり、配列が
1259反復の長さの整数倍でない場合も拡張されません; 一度に一つだけ
1260配列を反復する場合と一貫しています。
1261これらの追加された要素は左辺値ではないので、これを変更しようとすると
1262失敗します; リテラルな C<undef> のリストを反復したときの振る舞いと
1263一貫しています。
1264これが望んでいる振る舞いでないなら、ループを開始する前に整数倍になるように
1265明示的に拡張するか、明示的に例外を投げてください。
1266
1267=begin original
1268
12691104Examples:
12701105
12711106=end original
12721107
12731108例:
12741109
12751110 for (@ary) { s/foo/bar/ }
12761111
12771112 for my $elem (@elements) {
1278 $elem *= 2;
1113 $elem *= 2;
12791114 }
12801115
12811116 for $count (reverse(1..10), "BOOM") {
1282 print $count, "\n";
1117 print $count, "\n";
1283 sleep(1);
1118 sleep(1);
12841119 }
12851120
12861121 for (1..15) { print "Merry Christmas\n"; }
12871122
12881123 foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
1289 print "Item: $item\n";
1124 print "Item: $item\n";
12901125 }
12911126
1292 use feature "refaliasing";
1293 no warnings "experimental::refaliasing";
1294 foreach \my %hash (@array_of_hash_references) {
1295 # do something with each %hash
1296 }
1297
1298 foreach my ($foo, $bar, $baz) (@list) {
1299 # do something three-at-a-time
1300 }
1301
1302 foreach my ($key, $value) (%hash) {
1303 # iterate over the hash
1304 # The hash is immediately copied to a flat list before the loop
1305 # starts. The list contains copies of keys but aliases of values.
1306 # This is the same behaviour as for $var (%hash) {...}
1307 }
1308
13091127=begin original
13101128
13111129Here's how a C programmer might code up a particular algorithm in Perl:
13121130
13131131=end original
13141132
13151133以下の例は、C プログラマーが Perl でとあるアルゴリズムを記述するときに
13161134使うであろうやり方です:
13171135
13181136 for (my $i = 0; $i < @ary1; $i++) {
1319 for (my $j = 0; $j < @ary2; $j++) {
1137 for (my $j = 0; $j < @ary2; $j++) {
1320 if ($ary1[$i] > $ary2[$j]) {
1138 if ($ary1[$i] > $ary2[$j]) {
1321 last; # can't go to outer :-(
1139 last; # can't go to outer :-(
1322 }
1140 }
1323 $ary1[$i] += $ary2[$j];
1141 $ary1[$i] += $ary2[$j];
1324 }
1142 }
1325 # this is where that last takes me
1143 # this is where that last takes me
13261144 }
13271145
13281146=begin original
13291147
13301148Whereas here's how a Perl programmer more comfortable with the idiom might
13311149do it:
13321150
13331151=end original
13341152
13351153それに対して、次の例は Perl プログラマーが同じことをよりゆったりとして
13361154行うやり方です:
13371155
13381156 OUTER: for my $wid (@ary1) {
13391157 INNER: for my $jet (@ary2) {
1340 next OUTER if $wid > $jet;
1158 next OUTER if $wid > $jet;
1341 $wid += $jet;
1159 $wid += $jet;
1342 }
1160 }
1343 }
1161 }
13441162
13451163=begin original
13461164
13471165See how much easier this is? It's cleaner, safer, and faster. It's
13481166cleaner because it's less noisy. It's safer because if code gets added
13491167between the inner and outer loops later on, the new code won't be
13501168accidentally executed. The C<next> explicitly iterates the other loop
13511169rather than merely terminating the inner one. And it's faster because
13521170Perl executes a C<foreach> statement more rapidly than it would the
1353equivalent C-style C<for> loop.
1171equivalent C<for> loop.
13541172
13551173=end original
13561174
1357どのくらいこれが簡単になったように見えますか?
1175どのくらいこれが簡単になったように見えますか? これは明確で、安全で、
1358これは明確で、安全で、高速です。
1176高速です。
13591177これは余計なものが少ないので明確なのです。
13601178これは後で内側のループと外側のループとの間にコードを付加えた場合でも、
13611179それを間違って実行することがないので安全なのです。
13621180C<next> は内側のループを終了するのではなく、外側のループの繰り返しを
13631181行います。
1364そしてこれは、Perl は C<foreach> 文をそれと等価な C 形式の C<for> ループよりも
1182そしてこれは、Perl は C<foreach> 文をそれと等価な C<for> ループよりも
13651183すばやく実行するので高速なのです。
13661184
13671185=begin original
13681186
13691187Perceptive Perl hackers may have noticed that a C<for> loop has a return
13701188value, and that this value can be captured by wrapping the loop in a C<do>
13711189block. The reward for this discovery is this cautionary advice: The
13721190return value of a C<for> loop is unspecified and may change without notice.
13731191Do not rely on it.
13741192
13751193=end original
13761194
13771195洞察力のある Perl ハッカーは、C<for> ループに返り値があり、この値は
13781196ループを C<do> ブロックで包むことによって捕捉できることに
13791197気付くかもしれません。
13801198この発見に対する報奨は、この警告的なアドバイスです: C<for> ループの返り値は
13811199未定義で、予告なしに変更されることがあります。
13821200これに依存してはいけません。
13831201
1384=head2 Try Catch Exception Handling
1385X<try> X<catch> X<finally>
1386
1387=begin original
1388
1389The C<try>/C<catch> syntax provides control flow relating to exception
1390handling. The C<try> keyword introduces a block which will be executed when it
1391is encountered, and the C<catch> block provides code to handle any exception
1392that may be thrown by the first.
1393
1394=end original
1395
1396C<try>/C<catch> 構文は、例外処理に関連する制御フローを提供します。
1397C<try> キーワードは、それが検出されたときに実行されるブロックを導入し、
1398C<catch> ブロックは、最初のものによって投げられる可能性のある例外を
1399処理するコードを提供します。
1400
1401=begin original
1402
1403This syntax must first be enabled with C<use feature 'try'>.
1404
1405=end original
1406
1407この文法は、まず C<use feature 'try'> で有効にしなければなりません。
1408
1409 use feature 'try';
1410
1411 try {
1412 my $x = call_a_function();
1413 $x < 100 or die "Too big";
1414 send_output($x);
1415 }
1416 catch ($e) {
1417 warn "Unable to output a value; $e";
1418 }
1419 print "Finished\n";
1420
1421=begin original
1422
1423Here, the body of the C<catch> block (i.e. the C<warn> statement) will be
1424executed if the initial block invokes the conditional C<die>, or if either of
1425the functions it invokes throws an uncaught exception. The C<catch> block can
1426inspect the C<$e> lexical variable in this case to see what the exception was.
1427If no exception was thrown then the C<catch> block does not happen. In either
1428case, execution will then continue from the following statement - in this
1429example the C<print>.
1430
1431=end original
1432
1433ここで、C<catch> ブロックの本体 (つまり、C<warn> 文) は、最初の
1434ブロックが条件付き C<die> を呼び出した場合、または呼び出した関数のいずれかが
1435捕捉されない例外を投げた場合に実行されます。
1436C<catch> ブロックは、この場合の C<$e> レキシカル変数を検査して、例外が何かを
1437調べることができます。
1438例外が投げられなかった場合、C<catch> ブロックは発生しません。
1439いずれの場合も、次の文 (この例では C<print>) から実行が続行されます。
1440
1441=begin original
1442
1443The C<catch> keyword must be immediately followed by a variable declaration in
1444parentheses, which introduces a new variable visible to the body of the
1445subsequent block. Inside the block this variable will contain the exception
1446value that was thrown by the code in the C<try> block. It is not necessary
1447to use the C<my> keyword to declare this variable; this is implied (similar
1448as it is for subroutine signatures).
1449
1450=end original
1451
1452C<catch> キーワードの直後には、かっこで囲まれた変数宣言が
1453続かなければなりません;
1454これにより、後続のブロックの本文から見える新しい変数が導入されます。
1455ブロック内では、この変数には、C<try> ブロック内のコードによって投げられた
1456例外値が含まれます。
1457この変数を宣言するために C<my> キーワードを使用する必要はありません;
1458これは(サブルーチンシグネチャの場合と同様)暗黙的です。
1459
1460=begin original
1461
1462Both the C<try> and the C<catch> blocks are permitted to contain control-flow
1463expressions, such as C<return>, C<goto>, or C<next>/C<last>/C<redo>. In all
1464cases they behave as expected without warnings. In particular, a C<return>
1465expression inside the C<try> block will make its entire containing function
1466return - this is in contrast to its behaviour inside an C<eval> block, where
1467it would only make that block return.
1468
1469=end original
1470
1471C<try> ブロックと C<catch> ブロックの両方に、C<return>, C<goto>,
1472C<next>/C<last>/C<redo> などの制御フロー式を含めることができます。
1473いずれの場合も、警告なしに想定通りに動作します。
1474特に、C<try> ブロック内の C<return> 式は、それを含む関数全体から返ります -
1475これは、そのブロックからのみ返る C<eval> ブロック内での動作とは対照的です。
1476
1477=begin original
1478
1479Like other control-flow syntax, C<try> and C<catch> will yield the last
1480evaluated value when placed as the final statement in a function or a C<do>
1481block. This permits the syntax to be used to create a value. In this case
1482remember not to use the C<return> expression, or that will cause the
1483containing function to return.
1484
1485=end original
1486
1487他の制御フロー構文と同様に、C<try> と C<catch> は、関数または C<do>
1488ブロックの最後のステートメントとして配置された場合に、最後に評価された値を
1489生成します。
1490これにより、この構文を使用して値を作成できます。
1491この場合、C<return> 式を使用しないでください;
1492使用すると、含まれる関数から戻ることになります。
1493
1494 my $value = do {
1495 try {
1496 get_thing(@args);
1497 }
1498 catch ($e) {
1499 warn "Unable to get thing - $e";
1500 $DEFAULT_THING;
1501 }
1502 };
1503
1504=begin original
1505
1506As with other control-flow syntax, C<try> blocks are not visible to
1507C<caller()> (just as for example, C<while> or C<foreach> loops are not).
1508Successive levels of the C<caller> result can see subroutine calls and
1509C<eval> blocks, because those affect the way that C<return> would work. Since
1510C<try> blocks do not intercept C<return>, they are not of interest to
1511C<caller>.
1512
1513=end original
1514
1515他の制御フロー構文と同様に、C<try> ブロックは C<caller()> には見えません
1516(例えば、C<while> または C<foreach> ループが見えないのと同様です)。
1517C<caller> の結果の連続するレベルは、サブルーチン呼び出しと C<eval> ブロックを
1518見ることができます; なぜなら、それらは C<return> の動作方法に
1519影響するからです。
1520C<try> ブロックは C<return> に割り込まないので、それらは
1521C<caller> には関係ありません。
1522
1523=begin original
1524
1525The C<try> and C<catch> blocks may optionally be followed by a third block
1526introduced by the C<finally> keyword. This third block is executed after the
1527rest of the construct has finished.
1528
1529=end original
1530
1531C<try> と C<catch> のブロックは、オプションとして、C<finally> キーワードで
1532導入される第 3 のブロックを引き続かせることができます。
1533この第 3 のブロックは構文の残りの部分が完了した後に実行されます。
1534
1535 try {
1536 call_a_function();
1537 }
1538 catch ($e) {
1539 warn "Unable to call; $e";
1540 }
1541 finally {
1542 print "Finished\n";
1543 }
1544
1545=begin original
1546
1547The C<finally> block is equivalent to using a C<defer> block and will be
1548invoked in the same situations; whether the C<try> block completes
1549successfully, throws an exception, or transfers control elsewhere by using
1550C<return>, a loop control, or C<goto>.
1551
1552=end original
1553
1554C<finally> ブロックは C<defer> ブロックを使うのと等価で、
1555同じ状況で起動されます; C<try> ブロックが正常に完了するか、
1556例外が投げられるか、C<return>、ループ制御、C<goto> を使うことによって
1557別の場所に制御が移るかしたときです。
1558
1559=begin original
1560
1561Unlike the C<try> and C<catch> blocks, a C<finally> block is not permitted to
1562C<return>, C<goto> or use any loop controls. The final expression value is
1563ignored, and does not affect the return value of the containing function even
1564if it is placed last in the function.
1565
1566=end original
1567
1568C<try> と C<catch> ブロックとは異なり、C<finally> ブロックは
1569C<return>, C<goto> あるいはループ制御は許されません。
1570最後の式の値は無視され、たとえこれが関数の最後に置かれていても、
1571これを含んでいる関数の返り値には影響を与えません。
1572
1573=begin original
1574
1575Use of this C<finally> block syntax is currently experimental and will emit a
1576warning in the C<experimental::try> category.
1577
1578=end original
1579
1580この C<finally> ブロック構文の使用は現在実験的であり、
1581C<experimental::try> カテゴリの警告を出力します。
1582
15831202=head2 Basic BLOCKs
15841203X<block>
15851204
1586(基本ブロック (BLOCK))
1205(基本ブロック)
15871206
15881207=begin original
15891208
15901209A BLOCK by itself (labeled or not) is semantically equivalent to a
15911210loop that executes once. Thus you can use any of the loop control
15921211statements in it to leave or restart the block. (Note that this is
15931212I<NOT> true in C<eval{}>, C<sub{}>, or contrary to popular belief
15941213C<do{}> blocks, which do I<NOT> count as loops.) The C<continue>
15951214block is optional.
15961215
15971216=end original
15981217
15991218ブロックそれ自身は(ラベルが付いていようがついてなかろうが)一度だけ
16001219実行されるループと、文法的には等価なものです。
16011220このため、ブロックから脱出するためやブロックの再スタートのために
16021221任意のループ制御文を使うことができます。
16031222(これは C<eval{}>、C<sub{}>、
16041223さらに一般的な認識とは異なり I<ループではない> C<do{}> ブロックに対しては
16051224I<真ではない> ということに注意してください。)
16061225C<continue> ブロックは省略することができます。
16071226
16081227=begin original
16091228
16101229The BLOCK construct can be used to emulate case structures.
16111230
16121231=end original
16131232
16141233BLOCK 構造は case 構造を行うのにも使えます。
16151234
16161235 SWITCH: {
1617 if (/^abc/) { $abc = 1; last SWITCH; }
1236 if (/^abc/) { $abc = 1; last SWITCH; }
1618 if (/^def/) { $def = 1; last SWITCH; }
1237 if (/^def/) { $def = 1; last SWITCH; }
1619 if (/^xyz/) { $xyz = 1; last SWITCH; }
1238 if (/^xyz/) { $xyz = 1; last SWITCH; }
1620 $nothing = 1;
1239 $nothing = 1;
16211240 }
16221241
16231242=begin original
16241243
16251244You'll also find that C<foreach> loop used to create a topicalizer
16261245and a switch:
16271246
16281247=end original
16291248
16301249主題化器とスイッチを作るために使われた C<foreach> ループも見るかもしれません:
16311250
16321251 SWITCH:
16331252 for ($var) {
1634 if (/^abc/) { $abc = 1; last SWITCH; }
1253 if (/^abc/) { $abc = 1; last SWITCH; }
1635 if (/^def/) { $def = 1; last SWITCH; }
1254 if (/^def/) { $def = 1; last SWITCH; }
1636 if (/^xyz/) { $xyz = 1; last SWITCH; }
1255 if (/^xyz/) { $xyz = 1; last SWITCH; }
1637 $nothing = 1;
1256 $nothing = 1;
16381257 }
16391258
16401259=begin original
16411260
16421261Such constructs are quite frequently used, both because older versions of
16431262Perl had no official C<switch> statement, and also because the new version
16441263described immediately below remains experimental and can sometimes be confusing.
16451264
16461265=end original
16471266
16481267古いバージョンの Perl には公式の C<switch> 文がなく、直後に記述する
16491268新しいバージョンはまだ実験的で時々混乱させることがあるので、
16501269このような構文はとてもよく使われています。
16511270
1652=head2 defer blocks
1653X<defer>
1654
1655(defer ブロック)
1656
1657=begin original
1658
1659A block prefixed by the C<defer> modifier provides a section of code which
1660runs at a later time during scope exit.
1661
1662=end original
1663
1664C<defer> 修飾子を前置したブロックは、後でスコープが終了している間に
1665実行されるコードを提供します。
1666
1667=begin original
1668
1669A C<defer> block can appear at any point where a regular block or other
1670statement is permitted. If the flow of execution reaches this statement, the
1671body of the block is stored for later, but not invoked immediately. When the
1672flow of control leaves the containing block for any reason, this stored block
1673is executed on the way past. It provides a means of deferring execution until
1674a later time. This acts similarly to syntax provided by some other languages,
1675often using keywords named C<try / finally>.
1676
1677=end original
1678
1679C<defer> ブロックは、通常のブロックは他の文が許される場所なら
1680どこにでも置くことができます。
1681実行フローがその文に届くと、ブロックの本体は後のために保管されますが、
1682直ちに起動はしません。
1683フロー制御がなんらかの理由で含まれているブロックから離れたとき、
1684この保管されていたブロックが通過する途中で実行されます。
1685これは、後に実行を遅延させる意味を提供します。
1686これは他の言語で、しばしば C<try / finally> という名前のキーワードを
1687使って提供されている文法と似た動作をします。
1688
1689=begin original
1690
1691This syntax is available since Perl 5.36 if enabled by the C<defer> named feature,
1692and is currently experimental. If experimental warnings are enabled it will emit a
1693warning when used.
1694
1695=end original
1696
1697この文法は Perl 5.36 から、C<defer> という名前付き機能が有効の場合に
1698利用可能で、これは現在の所実験的です。
1699実験的警告が有効の場合、使われたときに警告が発生します。
1700
1701 use feature 'defer';
1702
1703 {
1704 say "This happens first";
1705 defer { say "This happens last"; }
1706
1707 say "And this happens inbetween";
1708 }
1709
1710=begin original
1711
1712If multiple C<defer> blocks are contained in a single scope, they are
1713executed in LIFO order; the last one reached is the first one executed.
1714
1715=end original
1716
1717一つのスコープに複数の C<defer> ブロックがある場合、LIFO 順で実行されます;
1718最後に現れたものが最初に実行されます。
1719
1720=begin original
1721
1722The code stored by the C<defer> block will be invoked when control leaves
1723its containing block due to regular fallthrough, explicit C<return>,
1724exceptions thrown by C<die> or propagated by functions called by it, C<goto>,
1725or any of the loop control statements C<next>, C<last> or C<redo>.
1726
1727=end original
1728
1729C<defer> ブロックに保管されているコードは、通常の通過、明示的な C<return>、
1730C<die> あるいは呼び出した関数から伝搬した例外、
1731C<goto>、またはループ制御文 C<next>, C<last>, C<redo> のいずれかによって、
1732制御がブロックから離れたときに実行されます。
1733
1734=begin original
1735
1736If the flow of control does not reach the C<defer> statement itself then its
1737body is not stored for later execution. (This is in direct contrast to the
1738code provided by an C<END> phaser block, which is always enqueued by the
1739compiler, regardless of whether execution ever reached the line it was given
1740on.)
1741
1742=end original
1743
1744フロー制御が C<defer> 文自体に届かない場合、その本体は後の実行のために
1745保管されません。
1746(これは、実行がその行に届くかどうかに関わらず常にコンパイラによって
1747キューに入れられる C<END> フェーズブロックとの直接の違いです。)
1748
1749 use feature 'defer';
1750
1751 {
1752 defer { say "This will run"; }
1753 return;
1754 defer { say "This will not"; }
1755 }
1756
1757=begin original
1758
1759Exceptions thrown by code inside a C<defer> block will propagate to the
1760caller in the same way as any other exception thrown by normal code.
1761
1762=end original
1763
1764C<defer> ブロックの内側で投げられた例外は、通常のコードで
1765投げられたその他の例外と同様に、呼び出し元に伝搬します。
1766
1767=begin original
1768
1769If the C<defer> block is being executed due to a thrown exception and throws
1770another one it is not specified what happens, beyond that the caller will
1771definitely receive an exception.
1772
1773=end original
1774
1775C<defer> ブロックが例外が投げられたために実行され、
1776もう一つの例外が投げられた場合、、呼び出し元が例外を受け取るということ
1777以上に何が起こるかは未規定です。
1778
1779=begin original
1780
1781Besides throwing an exception, a C<defer> block is not permitted to
1782otherwise alter the control flow of its surrounding code. In particular, it
1783may not cause its containing function to C<return>, nor may it C<goto> a
1784label, or control a containing loop using C<next>, C<last> or C<redo>. These
1785constructions are however, permitted entirely within the body of the
1786C<defer>.
1787
1788=end original
1789
1790例外を投げること以外、C<defer> ブロックがその周りのコードの制御フローを
1791変えることは許されていません。
1792特に、含んでいる関数に C<return> を引き起こしたり、ラベルに C<goto> したり、
1793C<next>, C<last>, C<redo> を使って含まれているループを制御してはいけません。
1794しかし、これらの構文は、完全に C<defer> の内部だけの場合は許されます。
1795
1796 use feature 'defer';
1797
1798 {
1799 defer {
1800 foreach ( 1 .. 5 ) {
1801 last if $_ == 3; # this is permitted
1802 }
1803 }
1804 }
1805
1806 {
1807 foreach ( 6 .. 10 ) {
1808 defer {
1809 last if $_ == 8; # this is not
1810 }
1811 }
1812 }
1813
18141271=head2 Switch Statements
18151272
18161273(switch 文)
18171274
18181275X<switch> X<case> X<given> X<when> X<default>
18191276
18201277=begin original
18211278
18221279Starting from Perl 5.10.1 (well, 5.10.0, but it didn't work
18231280right), you can say
18241281
18251282=end original
18261283
18271284Perl 5.10.1 から(えっと、5.10.0 からですが、正しく動いていませんでした)、
18281285以下のように書くと:
18291286
18301287 use feature "switch";
18311288
18321289=begin original
18331290
18341291to enable an experimental switch feature. This is loosely based on an
1835old version of a Raku proposal, but it no longer resembles the Raku
1292old version of a Perl 6 proposal, but it no longer resembles the Perl 6
1836construct. You also get the switch feature whenever you declare that your
1293construct. You also get the switch feature whenever you declare that your
1837code prefers to run under a version of Perl between 5.10 and 5.34. For
1294code prefers to run under a version of Perl that is 5.10 or later. For
18381295example:
18391296
18401297=end original
18411298
18421299実験的な switch 機能を有効にします。
1843これはおおまかに Raku 提案の古い版を基にしていますが、もはや
1300これはおおまかに Perl 6 提案の古い版を基にしていますが、もはや
1844Raku の構文と共通点はありません。
1301Perl 6 の構文と共通点はありません。
1845コードが 5.10 から 5.34 間の Perl バージョンで実行されるように
1302コードが 5.10 以降の Perl バージョンで実行されるように宣言したときもいつでも
1846宣言したときもいつでも switch 機能を得られます。
1303switch 機能を得られます。
18471304例えば:
18481305
18491306 use v5.14;
18501307
18511308=begin original
18521309
18531310Under the "switch" feature, Perl gains the experimental keywords
18541311C<given>, C<when>, C<default>, C<continue>, and C<break>.
18551312Starting from Perl 5.16, one can prefix the switch
18561313keywords with C<CORE::> to access the feature without a C<use feature>
18571314statement. The keywords C<given> and
18581315C<when> are analogous to C<switch> and
1859C<case> in other languages -- though C<continue> is not -- so the code
1316C<case> in other languages, so the code in the previous section could be
1860in the previous section could be rewritten as
1317rewritten as
18611318
18621319=end original
18631320
18641321"switch" 機能の基では、Perl は実験的なキーワード C<given>, C<when>,
18651322C<default>, C<continue>, C<break> を得ます。
18661323Perl 5.16 から、C<use feature> 文なしで機能にアクセスするために、
18671324switch キーワードに C<CORE::> を前置できます。
1868キーワード C<given> と C<when> は
1325キーワード C<given> と C<when> は他の言語での C<switch> および C<case> と
1869-- C<continue> は違いますが --
1870他の言語での C<switch> および C<case> と
18711326同様のものなので、前の節のコードは以下のように書き直せます:
18721327
18731328 use v5.10.1;
18741329 for ($var) {
1875 when (/^abc/) { $abc = 1 }
1330 when (/^abc/) { $abc = 1 }
1876 when (/^def/) { $def = 1 }
1331 when (/^def/) { $def = 1 }
1877 when (/^xyz/) { $xyz = 1 }
1332 when (/^xyz/) { $xyz = 1 }
1878 default { $nothing = 1 }
1333 default { $nothing = 1 }
18791334 }
18801335
18811336=begin original
18821337
18831338The C<foreach> is the non-experimental way to set a topicalizer.
18841339If you wish to use the highly experimental C<given>, that could be
18851340written like this:
18861341
18871342=end original
18881343
18891344C<foreach> は主題化器を設定する実験的でない方法です。
18901345とても実験的な C<given> を使いたいなら、以下のように書けます:
18911346
18921347 use v5.10.1;
18931348 given ($var) {
1894 when (/^abc/) { $abc = 1 }
1349 when (/^abc/) { $abc = 1 }
1895 when (/^def/) { $def = 1 }
1350 when (/^def/) { $def = 1 }
1896 when (/^xyz/) { $xyz = 1 }
1351 when (/^xyz/) { $xyz = 1 }
1897 default { $nothing = 1 }
1352 default { $nothing = 1 }
18981353 }
18991354
19001355=begin original
19011356
19021357As of 5.14, that can also be written this way:
19031358
19041359=end original
19051360
190613615.14 現在、これは以下のようにも書けます:
19071362
19081363 use v5.14;
19091364 for ($var) {
1910 $abc = 1 when /^abc/;
1365 $abc = 1 when /^abc/;
1911 $def = 1 when /^def/;
1366 $def = 1 when /^def/;
1912 $xyz = 1 when /^xyz/;
1367 $xyz = 1 when /^xyz/;
1913 default { $nothing = 1 }
1368 default { $nothing = 1 }
19141369 }
19151370
19161371=begin original
19171372
19181373Or if you don't care to play it safe, like this:
19191374
19201375=end original
19211376
19221377あるいは、安全にすることを気にしないなら、以下のようにします:
19231378
19241379 use v5.14;
19251380 given ($var) {
1926 $abc = 1 when /^abc/;
1381 $abc = 1 when /^abc/;
1927 $def = 1 when /^def/;
1382 $def = 1 when /^def/;
1928 $xyz = 1 when /^xyz/;
1383 $xyz = 1 when /^xyz/;
1929 default { $nothing = 1 }
1384 default { $nothing = 1 }
19301385 }
19311386
19321387=begin original
19331388
19341389The arguments to C<given> and C<when> are in scalar context,
19351390and C<given> assigns the C<$_> variable its topic value.
19361391
19371392=end original
19381393
19391394C<given> と C<when> への引数はスカラコンテキストで、
19401395C<given> は C<$_> 変数に注目している値を代入します。
19411396
19421397=begin original
19431398
19441399Exactly what the I<EXPR> argument to C<when> does is hard to describe
19451400precisely, but in general, it tries to guess what you want done. Sometimes
19461401it is interpreted as C<< $_ ~~ I<EXPR> >>, and sometimes it is not. It
19471402also behaves differently when lexically enclosed by a C<given> block than
19481403it does when dynamically enclosed by a C<foreach> loop. The rules are far
19491404too difficult to understand to be described here. See L</"Experimental Details
19501405on given and when"> later on.
19511406
19521407=end original
19531408
19541409C<when> への I<EXPR> 引数が正確に何をするかを正確に記述するのは
19551410難しいですが、一般的には、あなたのしたいことを推測しようとします。
19561411これは C<< $_ ~~ I<EXPR> >> として解釈される場合もあり、そうでない場合も
19571412あります。
19581413これはまた、C<given> ブロックでレキシカルに囲まれた場合は、C<foreach>
19591414ループによって動的に囲まれた場合とは異なった振る舞いをします。
19601415規則はここで記述されたよりも遥かに理解しにくいものです。
19611416後述する L</"Experimental Details on given and when"> を参照してください。
19621417
19631418=begin original
19641419
19651420Due to an unfortunate bug in how C<given> was implemented between Perl 5.10
19661421and 5.16, under those implementations the version of C<$_> governed by
19671422C<given> is merely a lexically scoped copy of the original, not a
19681423dynamically scoped alias to the original, as it would be if it were a
1969C<foreach> or under both the original and the current Raku language
1424C<foreach> or under both the original and the current Perl 6 language
1970specification. This bug was fixed in Perl 5.18 (and lexicalized C<$_> itself
1425specification. This bug was fixed in Perl
1971was removed in Perl 5.24).
14265.18. If you really want a lexical C<$_>,
1427specify that explicitly, but note that C<my $_>
1428is now deprecated and will warn unless warnings
1429have been disabled:
19721430
19731431=end original
19741432
19751433Perl 5.10 と 5.14 の間での C<given> の実装方法による不幸なバグにより、
19761434現在の実装では、C<given> によって管理される C<$_> は、
1977C<foreach> の場合やオリジナルと現在両方の Raku 言語仕様のように
1435C<foreach> の場合やオリジナルと現在両方の Perl 6 言語仕様のように
19781436元のものの動的スコープな別名ではなく、単なるレキシカルスコープのコピーです。
1979このバグは Perl 5.18 で修正されました
1437このバグは Perl 5.18 で修正されました
1980(そしてレキシカルな C<$_> 自身は Perl 5.24 で削除されました)。
1438本当にレキシカルな C<$_> がほしいなら、明示的に指定しますが、C<my $_>
1439非推奨になって、警告を無効にしない限り警告されるようになったことに
1440注意してください:
19811441
1442 given(my $_ = EXPR) { ... }
1443
19821444=begin original
19831445
19841446If your code still needs to run on older versions,
19851447stick to C<foreach> for your topicalizer and
19861448you will be less unhappy.
19871449
19881450=end original
19891451
19901452あなたのコードがまだ古いバージョンでも動作する必要があるなら、
19911453主題化器には C<foreach> を使うことで不幸を減らせます。
19921454
19931455=head2 Goto
19941456X<goto>
19951457
19961458(goto 文)
19971459
19981460=begin original
19991461
20001462Although not for the faint of heart, Perl does support a C<goto>
20011463statement. There are three forms: C<goto>-LABEL, C<goto>-EXPR, and
20021464C<goto>-&NAME. A loop's LABEL is not actually a valid target for
20031465a C<goto>; it's just the name of the loop.
20041466
20051467=end original
20061468
20071469気弱な人のためでないにも関らず、Perl は C<goto> 文をサポートしています。
20081470C<goto>-LABEL、C<goto>-EXPR、C<goto>-&NAME の三つの形式があります。
20091471ループのラベルは実際には C<goto> の正当なターゲットではなく、
20101472ループの名前にすぎません。
20111473
20121474=begin original
20131475
20141476The C<goto>-LABEL form finds the statement labeled with LABEL and resumes
20151477execution there. It may not be used to go into any construct that
20161478requires initialization, such as a subroutine or a C<foreach> loop. It
20171479also can't be used to go into a construct that is optimized away. It
20181480can be used to go almost anywhere else within the dynamic scope,
20191481including out of subroutines, but it's usually better to use some other
20201482construct such as C<last> or C<die>. The author of Perl has never felt the
20211483need to use this form of C<goto> (in Perl, that is--C is another matter).
20221484
20231485=end original
20241486
20251487C<goto>-LABEL 形式は LABEL でラベル付けされた文を見つけだし、そこから
20261488実行を再開します。
20271489これはサブルーチンであるとか C<foreach> ループのような
20281490初期化を必要とするような構造へ飛び込むために使うことはできません。
20291491また、最適化されて無くなってしまうような構造へ飛び込むこともできません。
20301492動的スコープの中以外のほとんどの場所へは、サブルーチンの外も含めて
20311493移動することができます; しかし、通常は C<last> や C<die> のような
20321494別のやり方を使ったほうが良いでしょう。
20331495Perl の作者は、未だかつてこの形式の C<goto> を使うことが
20341496必要だと感じたことはありません(Perl の場合です--C の場合はまた別の話です)。
20351497
20361498=begin original
20371499
20381500The C<goto>-EXPR form expects a label name, whose scope will be resolved
20391501dynamically. This allows for computed C<goto>s per FORTRAN, but isn't
20401502necessarily recommended if you're optimizing for maintainability:
20411503
20421504=end original
20431505
20441506C<goto>-EXPR 形式は動的に解決されるスコープを持っているラベル名を
20451507期待しています。
20461508これによって FORTRAN の計算型 C<goto> が実現できますが、
20471509これは保守性に重きを置くのであれば使うことは止めた方が良いでしょう。
20481510
20491511 goto(("FOO", "BAR", "GLARCH")[$i]);
20501512
20511513=begin original
20521514
20531515The C<goto>-&NAME form is highly magical, and substitutes a call to the
20541516named subroutine for the currently running subroutine. This is used by
20551517C<AUTOLOAD()> subroutines that wish to load another subroutine and then
20561518pretend that the other subroutine had been called in the first place
20571519(except that any modifications to C<@_> in the current subroutine are
20581520propagated to the other subroutine.) After the C<goto>, not even C<caller()>
20591521will be able to tell that this routine was called first.
20601522
20611523=end original
20621524
20631525C<goto>-&NAME は高度にマジカルで、名前付きサブルーチンの呼び出しを
20641526カレントで実行されているサブルーチンに置き換えます。
20651527これは別のサブルーチンをロードして、最初の場所で呼び出された
20661528別のサブルーチンを要求することをしようとする
20671529C<AUTOLOAD()> サブルーチンで使われていてます
20681530(カレントのサブルーチンにおける C<@_> に対するもの以外の変更は、
20691531別のサブルーチンへ伝播します)。
20701532C<goto> の後で、C<caller()> でなくてもこのサブルーチンが
20711533最初に呼ばれたのだということを伝えることすらできるでしょう。
20721534
20731535=begin original
20741536
20751537In almost all cases like this, it's usually a far, far better idea to use the
20761538structured control flow mechanisms of C<next>, C<last>, or C<redo> instead of
20771539resorting to a C<goto>. For certain applications, the catch and throw pair of
20781540C<eval{}> and die() for exception processing can also be a prudent approach.
20791541
20801542=end original
20811543
20821544このようなケースのほとんどすべての場合、C<goto> に頼るのではなくて
20831545C<next>、C<last>、C<redo> といった制御フロー機構を使うことが、
20841546ずっとずっと良いアイデアでしょう。
20851547一部のアプリケーションに対しては、C<eval{}> と die() を
20861548catch と throw のペアとして例外処理を行うための賢明なアプローチとして
20871549使うことができるでしょう。
20881550
20891551=head2 The Ellipsis Statement
20901552X<...>
20911553X<... statement>
20921554X<ellipsis operator>
20931555X<elliptical statement>
20941556X<unimplemented statement>
20951557X<unimplemented operator>
20961558X<yada-yada>
20971559X<yada-yada operator>
20981560X<... operator>
20991561X<whatever operator>
21001562X<triple-dot operator>
21011563
21021564(省略文)
21031565
21041566=begin original
21051567
21061568Beginning in Perl 5.12, Perl accepts an ellipsis, "C<...>", as a
2107placeholder for code that you haven't implemented yet.
1569placeholder for code that you haven't implemented yet. This form of
1570ellipsis, the unimplemented statement, should not be confused with the
1571binary flip-flop C<...> operator. One is a statement and the other an
1572operator. (Perl doesn't usually confuse them because usually Perl can tell
1573whether it wants an operator or a statement, but see below for exceptions.)
1574
1575=end original
1576
1577Perl 5.12 から、Perl はまだ実装していないコードのプレースホルダとして
1578省略 "C<...>" を受け付けるようになりました。
1579この形式の省略、未実装文は、二項フリップフロップ C<...> 演算子と
1580混乱しないでください。
1581片方は文で、もう片方は演算子です。
1582(Perl は普通混乱しません; なぜなら普通は Perl は演算子を求めているか
1583文を求めているかを伝えるからです; しかし以下の例外を参照してください。)
1584
1585=begin original
1586
21081587When Perl 5.12 or later encounters an ellipsis statement, it parses this
21091588without error, but if and when you should actually try to execute it, Perl
21101589throws an exception with the text C<Unimplemented>:
21111590
21121591=end original
21131592
2114Perl 5.12 から、Perl はまだ実装していないコードのプレースホルダとして
2115省略 "C<...>" を受け付けるようになりました。
21161593Perl 5.12 以降で省略文に遭遇すると、エラーなくパースしますが、実際に
21171594実行しようとすると、C<Unimplemented> というテキストと共に例外を投げます:
21181595
21191596 use v5.12;
21201597 sub unimplemented { ... }
21211598 eval { unimplemented() };
21221599 if ($@ =~ /^Unimplemented at /) {
2123 say "I found an ellipsis!";
1600 say "I found an ellipsis!";
21241601 }
21251602
21261603=begin original
21271604
2128You can only use the elliptical statement to stand in for a complete
1605You can only use the elliptical statement to stand in for a
2129statement. Syntactically, "C<...;>" is a complete statement, but,
1606complete statement. These examples of how the ellipsis works:
2130as with other kinds of semicolon-terminated statement, the semicolon
2131may be omitted if "C<...>" appears immediately before a closing brace.
2132These examples show how the ellipsis works:
21331607
21341608=end original
21351609
21361610完全な文を使える場所でのみ省略文を使えます。
2137文法的には、"C<...;>" は完全な文ですが、その他のセミコロン終端する
2138文と同様、"C<...>" が閉じ中かっこの直前に現れる場合は、
2139セミコロンは省略できます。
21401611次の例は省略がどのように動作するかの例です:
21411612
21421613 use v5.12;
21431614 { ... }
21441615 sub foo { ... }
21451616 ...;
21461617 eval { ... };
21471618 sub somemeth {
2148 my $self = shift;
1619 my $self = shift;
2149 ...;
1620 ...;
21501621 }
21511622 $x = do {
2152 my $n;
1623 my $n;
2153 ...;
1624 ...;
2154 say "Hurrah!";
1625 say "Hurrah!";
2155 $n;
1626 $n;
21561627 };
21571628
21581629=begin original
21591630
21601631The elliptical statement cannot stand in for an expression that
2161is part of a larger statement.
1632is part of a larger statement, since the C<...> is also the three-dot
1633version of the flip-flop operator (see L<perlop/"Range Operators">).
1634
1635=end original
1636
1637C<...> はフリップフロップ演算子(L<Range Operators> 参照)の 3 点版でも
1638あるので、省略文はより大きな文の一部の式としては使えません。
1639
1640=begin original
1641
21621642These examples of attempts to use an ellipsis are syntax errors:
21631643
21641644=end original
21651645
2166省略文はより大きな文の一部の式としては使えません。
21671646省略を使おうとする以下の例は文法エラーになります:
21681647
21691648 use v5.12;
21701649
21711650 print ...;
21721651 open(my $fh, ">", "/dev/passwd") or ...;
21731652 if ($condition && ... ) { say "Howdy" };
2174 ... if $x > $y;
2175 say "Cromulent" if ...;
2176 $flub = 5 + ...;
21771653
21781654=begin original
21791655
21801656There are some cases where Perl can't immediately tell the difference
21811657between an expression and a statement. For instance, the syntax for a
21821658block and an anonymous hash reference constructor look the same unless
21831659there's something in the braces to give Perl a hint. The ellipsis is a
2184syntax error if Perl doesn't guess that the C<{ ... }> is a block.
1660syntax error if Perl doesn't guess that the C<{ ... }> is a block. In that
2185Inside your block, you can use a C<;> before the ellipsis to denote that the
1661case, it doesn't think the C<...> is an ellipsis because it's expecting an
2186C<{ ... }> is a block and not a hash reference constructor.
1662expression instead of a statement:
21871663
21881664=end original
21891665
21901666式と文との違いをすぐに説明できない場合があります。
21911667例えば、ブロックと無名ハッシュリファレンスのコンストラクタは、
21921668Perl にヒントを与える中かっこがなければ同じに見えます。
21931669省略文は Perl が C<{ ... }> をブロックと判断できなかった場合は
21941670文法エラーとなります。
2195ブロックでは、C<{ ... }> がブロックであってハッシュリファレンスの
1671場合、文ではなく式と推測するので、C<...> は省略とは判断されません:
2196コンストラクタでないことを示すために、省略の前に C<;> を使えます。
21971672
21981673=begin original
21991674
1675 @transformed = map { ... } @input; # syntax error
1676
1677=end original
1678
1679 @transformed = map { ... } @input; # 文法エラー
1680
1681=begin original
1682
1683You can use a C<;> inside your block to denote that the C<{ ... }> is a
1684block and not a hash reference constructor. Now the ellipsis works:
1685
1686=end original
1687
1688C<{ ... }> がブロックであって、ハッシュリファレンスのコンストラクタでは
1689ないことを示すためにブロックの中で C<;> を使えます。
1690これで省略は動作します:
1691
1692=begin original
1693
1694 @transformed = map {; ... } @input; # ; disambiguates
1695
1696=end original
1697
1698 @transformed = map {; ... } @input; # ; 曖昧でない
1699
1700=begin original
1701
1702 @transformed = map { ...; } @input; # ; disambiguates
1703
1704=end original
1705
1706 @transformed = map { ...; } @input; # ; 曖昧でない
1707
1708=begin original
1709
22001710Note: Some folks colloquially refer to this bit of punctuation as a
22011711"yada-yada" or "triple-dot", but its true name
2202is actually an ellipsis.
1712is actually an ellipsis. Perl does not yet
1713accept the Unicode version, U+2026 HORIZONTAL ELLIPSIS, as an alias for
1714C<...>, but someday it may.
22031715
22041716=end original
22051717
22061718注意: 一部の人間はこの句読点を口語的に「ヤダヤダ」や「3 点」として
22071719参照しますが、真の名前は実際には省略です。
1720Perl はまだ Unicode 版の U+2026 HORIZONTAL ELLIPSIS を C<...> の別名として
1721認識しませんが、いつかそうなるかもしれません。
22081722
22091723=head2 PODs: Embedded Documentation
22101724X<POD> X<documentation>
22111725
22121726(POD: 組み込みドキュメント)
22131727
22141728=begin original
22151729
22161730Perl has a mechanism for intermixing documentation with source code.
22171731While it's expecting the beginning of a new statement, if the compiler
22181732encounters a line that begins with an equal sign and a word, like this
22191733
22201734=end original
22211735
22221736Perl は、ソースコードとドキュメントとを混ぜ書きするための仕掛けを
22231737持っています。
22241738新しい文の始まりが期待されているときに、コンパイラは
22251739以下の例のような = 記号で始まっている語を見つけると:
22261740
22271741 =head1 Here There Be Pods!
22281742
22291743=begin original
22301744
22311745Then that text and all remaining text up through and including a line
22321746beginning with C<=cut> will be ignored. The format of the intervening
22331747text is described in L<perlpod>.
22341748
22351749=end original
22361750
22371751そのテキストと、C<=cut> で始まる行までの内容を無視します。
22381752間に入るテキストの書式は L<perlpod> で説明されています。
22391753
22401754=begin original
22411755
22421756This allows you to intermix your source code
22431757and your documentation text freely, as in
22441758
22451759=end original
22461760
22471761これによって、ソースコードとドキュメントとを以下に示す例のように
22481762自由に混ぜることができるようになります。
22491763
22501764 =item snazzle($)
22511765
22521766 The snazzle() function will behave in the most spectacular
22531767 form that you can possibly imagine, not even excepting
22541768 cybernetic pyrotechnics.
22551769
22561770 =cut back to the compiler, nuff of this pod stuff!
22571771
22581772 sub snazzle($) {
2259 my $thingie = shift;
1773 my $thingie = shift;
2260 .........
1774 .........
22611775 }
22621776
22631777=begin original
22641778
22651779Note that pod translators should look at only paragraphs beginning
22661780with a pod directive (it makes parsing easier), whereas the compiler
22671781actually knows to look for pod escapes even in the middle of a
22681782paragraph. This means that the following secret stuff will be
22691783ignored by both the compiler and the translators.
22701784
22711785=end original
22721786
22731787コンパイラはパラグラフの途中に pod エスケープがあったとしてもそれを
22741788認識できるのに、pod トランスレータは pod 指示子で始まっている
22751789パラグラフのみに注目すべき(これは構文解析を簡単にするためです)で
22761790あるということに注意して下さい。
22771791つまり、以下の例にある "secret stuff" はコンパイラからも、
22781792トランスレータからも無視されるということです。
22791793
2280 $x=3;
1794 $a=3;
22811795 =secret stuff
22821796 warn "Neither POD nor CODE!?"
22831797 =cut back
2284 print "got $x\n";
1798 print "got $a\n";
22851799
22861800=begin original
22871801
22881802You probably shouldn't rely upon the C<warn()> being podded out forever.
22891803Not all pod translators are well-behaved in this regard, and perhaps
22901804the compiler will become pickier.
22911805
22921806=end original
22931807
22941808この例の C<warn()> のようなものが、将来に渡って無視されるということに
22951809依存すべきではありません。
22961810すべての pod トランスレータがそのように振る舞うわけではありませんし、
22971811コンパイラは将来これを無視しないようになるかもしれません。
22981812
22991813=begin original
23001814
23011815One may also use pod directives to quickly comment out a section
23021816of code.
23031817
23041818=end original
23051819
23061820pod 指示子を、コードの一部を手っ取り早くコメントアウトするために
23071821使うこともできます。
23081822
23091823=head2 Plain Old Comments (Not!)
23101824X<comment> X<line> X<#> X<preprocessor> X<eval>
23111825
23121826=begin original
23131827
23141828Perl can process line directives, much like the C preprocessor. Using
23151829this, one can control Perl's idea of filenames and line numbers in
23161830error or warning messages (especially for strings that are processed
23171831with C<eval()>). The syntax for this mechanism is almost the same as for
23181832most C preprocessors: it matches the regular expression
23191833
23201834=end original
23211835
23221836C のプリプロセッサと同じように、Perl は行指示子を処理できます。
23231837これを使うことによって、エラーメッセージや警告メッセージにある
23241838ファイル名や行番号を制御することができます
23251839(特に、C<eval()> で処理される文字列のために)。
23261840この仕組みの構文はほとんどの C のプリプロセッサとほとんど同じで、正規表現:
23271841
23281842 # example: '# line 42 "new_filename.plx"'
23291843 /^\# \s*
23301844 line \s+ (\d+) \s*
23311845 (?:\s("?)([^"]+)\g2)? \s*
23321846 $/x
23331847
23341848=begin original
23351849
23361850with C<$1> being the line number for the next line, and C<$3> being
23371851the optional filename (specified with or without quotes). Note that
23381852no whitespace may precede the C<< # >>, unlike modern C preprocessors.
23391853
23401854=end original
23411855
23421856にマッチしたものの C<$1> が次の行の行番号となり、省略することもできる
23431857C<$3> は(クォートありかなしで指定された)ファイル名となります。
23441858最近の C プリプロセッサとは違って、C<< # >> の前に空白を置けないことに
23451859注意してください。
23461860
23471861=begin original
23481862
23491863There is a fairly obvious gotcha included with the line directive:
23501864Debuggers and profilers will only show the last source line to appear
23511865at a particular line number in a given file. Care should be taken not
23521866to cause line number collisions in code you'd like to debug later.
23531867
23541868=end original
23551869
23561870行指示子にはかなり明らかな技があります: デバッガとプロファイラは、
23571871与えられたファイルの特定の行番号に対して現れた最新のソース行のみを
23581872表示します。
23591873あとでデバッグしたいコードでは行番号の衝突が起きないように注意するべきです。
23601874
23611875=begin original
23621876
23631877Here are some examples that you should be able to type into your command
23641878shell:
23651879
23661880=end original
23671881
23681882コマンドシェルでタイプすることのできる例をいくつか挙げます:
23691883
23701884 % perl
23711885 # line 200 "bzzzt"
23721886 # the '#' on the previous line must be the first char on line
23731887 die 'foo';
23741888 __END__
23751889 foo at bzzzt line 201.
23761890
23771891 % perl
23781892 # line 200 "bzzzt"
23791893 eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
23801894 __END__
23811895 foo at - line 2001.
23821896
23831897 % perl
23841898 eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
23851899 __END__
23861900 foo at foo bar line 200.
23871901
23881902 % perl
23891903 # line 345 "goop"
23901904 eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";
23911905 print $@;
23921906 __END__
23931907 foo at goop line 345.
23941908
23951909=head2 Experimental Details on given and when
23961910
23971911(given と when の実験的な詳細)
23981912
23991913=begin original
24001914
24011915As previously mentioned, the "switch" feature is considered highly
2402experimental (it is also scheduled to be removed in perl 5.42.0);
1916experimental; it is subject to change with little notice. In particular,
2403it is subject to change with little notice. In particular,
24041917C<when> has tricky behaviours that are expected to change to become less
24051918tricky in the future. Do not rely upon its current (mis)implementation.
24061919Before Perl 5.18, C<given> also had tricky behaviours that you should still
24071920beware of if your code must run on older versions of Perl.
24081921
24091922=end original
24101923
2411既に述べたように、"switch" 機能は非常に実験的であると考えられています
1924既に述べたように、"switch" 機能は非常に実験的であると考えられています;
2412(また perl 5.42.0 で削除されることが予定されています);
24131925ほとんど知らせることなく変更されることがあります。
24141926特に C<when> はトリッキーな振る舞いがあり、将来よりトリッキーで
24151927なくなるように変更される予定です。
24161928現在の(誤)実装に依存しないでください。
24171929Perl 5.18 より前では、C<given> には、コードが古いバージョンの Perl でも
24181930動かなければならない場合に気をつけるべきトリッキーな振る舞いもあります:
24191931
24201932=begin original
24211933
24221934Here is a longer example of C<given>:
24231935
24241936=end original
24251937
24261938これはより長い C<given> の例です:
24271939
24281940 use feature ":5.10";
24291941 given ($foo) {
2430 when (undef) {
1942 when (undef) {
2431 say '$foo is undefined';
1943 say '$foo is undefined';
2432 }
1944 }
2433 when ("foo") {
1945 when ("foo") {
2434 say '$foo is the string "foo"';
1946 say '$foo is the string "foo"';
2435 }
1947 }
2436 when ([1,3,5,7,9]) {
1948 when ([1,3,5,7,9]) {
2437 say '$foo is an odd digit';
1949 say '$foo is an odd digit';
2438 continue; # Fall through
1950 continue; # Fall through
2439 }
1951 }
2440 when ($_ < 100) {
1952 when ($_ < 100) {
2441 say '$foo is numerically less than 100';
1953 say '$foo is numerically less than 100';
2442 }
1954 }
2443 when (\&complicated_check) {
1955 when (\&complicated_check) {
2444 say 'a complicated check for $foo is true';
1956 say 'a complicated check for $foo is true';
2445 }
1957 }
2446 default {
1958 default {
2447 die q(I don't know what to do with $foo);
1959 die q(I don't know what to do with $foo);
2448 }
1960 }
24491961 }
24501962
24511963=begin original
24521964
24531965Before Perl 5.18, C<given(EXPR)> assigned the value of I<EXPR> to
24541966merely a lexically scoped I<B<copy>> (!) of C<$_>, not a dynamically
24551967scoped alias the way C<foreach> does. That made it similar to
24561968
24571969=end original
24581970
24591971Perl 5.18 より前では、C<given(EXPR)> は I<EXPR> の値を単にレキシカルスコープを
24601972持つ C<$_> の I<B<コピー>> (!) に代入します; C<foreach> がするような動的
24611973スコープを持つ別名ではありません。
24621974これは以下と似ています:
24631975
2464 do { my $_ = EXPR; ... }
1976 do { my $_ = EXPR; ... }
24651977
24661978=begin original
24671979
24681980except that the block was automatically broken out of by a successful
24691981C<when> or an explicit C<break>. Because it was only a copy, and because
24701982it was only lexically scoped, not dynamically scoped, you could not do the
24711983things with it that you are used to in a C<foreach> loop. In particular,
24721984it did not work for arbitrary function calls if those functions might try
24731985to access $_. Best stick to C<foreach> for that.
24741986
24751987=end original
24761988
24771989しかし、ブロックは C<when> が成功するか、明示的な C<break> によって
24781990自動的に破壊されるところが違いました。
24791991これはただのコピーで、動的スコープではなくレキシカルなスコープしか
24801992持たないので、C<foreach> ループの中でできるようなことはできませんでした。
24811993特に、$_ にアクセスしようとするかもしれない関数の場合、任意の関数呼び出しに
24821994対しては動作していませんでした。
24831995そのためには C<foreach> にこだわるのが最良です。
24841996
24851997=begin original
24861998
24871999Most of the power comes from the implicit smartmatching that can
24882000sometimes apply. Most of the time, C<when(EXPR)> is treated as an
24892001implicit smartmatch of C<$_>, that is, C<$_ ~~ EXPR>. (See
24902002L<perlop/"Smartmatch Operator"> for more information on smartmatching.)
24912003But when I<EXPR> is one of the 10 exceptional cases (or things like them)
24922004listed below, it is used directly as a boolean.
24932005
24942006=end original
24952007
24962008強力さのほとんどは時々適用される暗黙のスマートマッチングによるものです。
24972009ほとんどの場合、C<when(EXPR)> は暗黙の C<$_> のスマートマッチング、
24982010つまり C<$_ ~~ EXPR> として扱われます。
24992011(スマートマッチングに関するさらなる情報については
25002012L<perlop/"Smartmatch Operator"> を参照してください。)
25012013しかし I<EXPR> が後述する 10 の例外の場合(および似たような場合) の
25022014一つの場合、直接真偽値として使われます。
25032015
25042016=over 4
25052017
25062018=item Z<>1.
25072019
25082020=begin original
25092021
25102022A user-defined subroutine call or a method invocation.
25112023
25122024=end original
25132025
25142026ユーザー定義サブルーチンかメソッド呼び出し。
25152027
25162028=item Z<>2.
25172029
25182030=begin original
25192031
25202032A regular expression match in the form of C</REGEX/>, C<$foo =~ /REGEX/>,
25212033or C<$foo =~ EXPR>. Also, a negated regular expression match in
25222034the form C<!/REGEX/>, C<$foo !~ /REGEX/>, or C<$foo !~ EXPR>.
25232035
25242036=end original
25252037
25262038C</REGEX/>, C<$foo =~ /REGEX/>, C<$foo =~ EXPR> 形式の 正規表現マッチング。
25272039また、C<!/REGEX/>, C<$foo !~ /REGEX/>, C<$foo !~ EXPR> 形式の
25282040正規表現マッチングの否定。
25292041
25302042=item Z<>3.
25312043
25322044=begin original
25332045
25342046A smart match that uses an explicit C<~~> operator, such as C<EXPR ~~ EXPR>.
25352047
25362048=end original
25372049
25382050C<EXPR ~~ EXPR> のように、明示的に C<~~> 演算子を使うスマートマッチング。
25392051
2540=begin original
2541
2542B<NOTE:> You will often have to use C<$c ~~ $_> because the default case
2543uses C<$_ ~~ $c> , which is frequently the opposite of what you want.
2544
2545=end original
2546
2547B<注意:> しばしば C<$c ~~ $_> を使う必要があることに注意してください;
2548なぜならデフォルトの場合は C<$_ ~~ $c> を使い、これはしばしばしたいことの
2549逆だからです。
2550
25512052=item Z<>4.
25522053
25532054=begin original
25542055
25552056A boolean comparison operator such as C<$_ E<lt> 10> or C<$x eq "abc">. The
25562057relational operators that this applies to are the six numeric comparisons
25572058(C<< < >>, C<< > >>, C<< <= >>, C<< >= >>, C<< == >>, and C<< != >>), and
25582059the six string comparisons (C<lt>, C<gt>, C<le>, C<ge>, C<eq>, and C<ne>).
25592060
25602061=end original
25612062
25622063C<$_ E<lt> 10> や C<$x eq "abc"> のような真偽値比較。
25632064これを適用する関係演算子は、六つの数値比較
25642065(C<< < >>, C<< > >>, C<< <= >>, C<< >= >>, C<< == >>, C<< != >>) および
25652066六つの文字列比較 (C<lt>, C<gt>, C<le>, C<ge>, C<eq>, C<ne>) です。
25662067
2068=begin original
2069
2070B<NOTE:> You will often have to use C<$c ~~ $_> because
2071the default case uses C<$_ ~~ $c> , which is frequently
2072the opposite of what you want.
2073
2074=end original
2075
2076B<注意:> しばしば C<$c ~~ $_> を使う必要があることに注意してください;
2077なぜならデフォルトの場合は C<$_ ~~ $c> を使い、これはしばしばしたいことの
2078逆だからです。
2079
25672080=item Z<>5.
25682081
25692082=begin original
25702083
25712084At least the three builtin functions C<defined(...)>, C<exists(...)>, and
25722085C<eof(...)>. We might someday add more of these later if we think of them.
25732086
25742087=end original
25752088
25762089少なくとも三つの組み込み関数 C<defined(...)>, C<exists(...)>, C<eof(...)>。
25772090これらについて考えるとき、いつかもっと追加するかもしれません。
25782091
25792092=item Z<>6.
25802093
25812094=begin original
25822095
25832096A negated expression, whether C<!(EXPR)> or C<not(EXPR)>, or a logical
25842097exclusive-or, C<(EXPR1) xor (EXPR2)>. The bitwise versions (C<~> and C<^>)
25852098are not included.
25862099
25872100=end original
25882101
25892102否定表現 C<!(EXPR)> または C<not(EXPR)>、 排他的論理和
25902103C<(EXPR1) xor (EXPR2)>。
25912104ビット版 (C<~> と C<^>) は含まれません。
25922105
25932106=item Z<>7.
25942107
25952108=begin original
25962109
25972110A filetest operator, with exactly 4 exceptions: C<-s>, C<-M>, C<-A>, and
25982111C<-C>, as these return numerical values, not boolean ones. The C<-z>
25992112filetest operator is not included in the exception list.
26002113
26012114=end original
26022115
26032116真偽値ではなく数値を返す四つの例外: C<-s>, C<-M>, C<-A>, C<-C> を除く
26042117ファイルテスト演算子。
26052118C<-z> ファイルテスト演算子は例外の一覧には含まれません。
26062119
26072120=item Z<>8.
26082121
26092122=begin original
26102123
26112124The C<..> and C<...> flip-flop operators. Note that the C<...> flip-flop
26122125operator is completely different from the C<...> elliptical statement
26132126just described.
26142127
26152128=end original
26162129
26172130フリップフロップ演算子 C<..> と C<...>。
26182131C<...> フリップフロップ演算子は先に記述した C<...> 省略文とは完全に
26192132異なることに注意してください。
26202133
26212134=back
26222135
26232136=begin original
26242137
26252138In those 8 cases above, the value of EXPR is used directly as a boolean, so
26262139no smartmatching is done. You may think of C<when> as a smartsmartmatch.
26272140
26282141=end original
26292142
26302143上述の八つの場合、EXPR の値は直接真偽値として使われるため、
26312144スマートマッチングは行われません。
26322145スマートマッチングとして C<when> を考えるかもしれません。
26332146
26342147=begin original
26352148
26362149Furthermore, Perl inspects the operands of logical operators to
26372150decide whether to use smartmatching for each one by applying the
26382151above test to the operands:
26392152
26402153=end original
26412154
26422155更に、Perl はオペランドに上述のテストを適用することで、それぞれに
26432156スマートマッチングを使うかどうかを決定するために論理演算子の
26442157オペランドを調べます:
26452158
26462159=over 4
26472160
26482161=item Z<>9.
26492162
26502163=begin original
26512164
26522165If EXPR is C<EXPR1 && EXPR2> or C<EXPR1 and EXPR2>, the test is applied
26532166I<recursively> to both EXPR1 and EXPR2.
26542167Only if I<both> operands also pass the
26552168test, I<recursively>, will the expression be treated as boolean. Otherwise,
26562169smartmatching is used.
26572170
26582171=end original
26592172
26602173EXPR が C<EXPR1 && EXPR2> または C<EXPR1 and EXPR2> の場合、テストは
26612174EXPR1 と EXPR2 の両方に I<再帰的> に適用されます。
26622175I<両方の> オペランドがテストに I<再帰的に> 成功した場合にのみ、この式は
26632176真偽値として扱われます。
26642177さもなければ、スマートマッチングが使われます。
26652178
26662179=item Z<>10.
26672180
26682181=begin original
26692182
26702183If EXPR is C<EXPR1 || EXPR2>, C<EXPR1 // EXPR2>, or C<EXPR1 or EXPR2>, the
26712184test is applied I<recursively> to EXPR1 only (which might itself be a
26722185higher-precedence AND operator, for example, and thus subject to the
26732186previous rule), not to EXPR2. If EXPR1 is to use smartmatching, then EXPR2
26742187also does so, no matter what EXPR2 contains. But if EXPR2 does not get to
26752188use smartmatching, then the second argument will not be either. This is
26762189quite different from the C<&&> case just described, so be careful.
26772190
26782191=end original
26792192
26802193EXPR が C<EXPR1 || EXPR2>, C<EXPR1 // EXPR2>, or C<EXPR1 or EXPR2> の場合、
26812194テストは EXPR1 (例えば、より高い優先順位である AND 演算子; 従って
26822195前述の規則に従う)のみに対して I<再帰的に> 適用されます; EXPR2 には
26832196適用されません。
26842197EXPR1 がスマートマッチングを使うなら、EXPR2 も、その内容に関わらず
26852198そうします。
26862199しかし EXPR2 がスマートマッチングを使わないなら、二番目の引数はどちらでも
26872200ありません。
26882201これは既に記述した C<&&> の場合とはかなり異なりますので注意してください。
26892202
26902203=back
26912204
26922205=begin original
26932206
26942207These rules are complicated, but the goal is for them to do what you want
26952208(even if you don't quite understand why they are doing it). For example:
26962209
26972210=end original
26982211
26992212これらの規則は複雑ですが、この目標は (たとえあなたがなぜそうしているかを
27002213完全に理解していなくても) あなたが実行したい通りに実行することです。
27012214例えば:
27022215
27032216 when (/^\d+$/ && $_ < 75) { ... }
27042217
27052218=begin original
27062219
27072220will be treated as a boolean match because the rules say both
27082221a regex match and an explicit test on C<$_> will be treated
27092222as boolean.
27102223
27112224=end original
27122225
27132226これは真偽値マッチングとして扱われます; 規則では正規表現マッチングと
27142227C<$_> への明示的なテストはどちらも真偽値として扱われるからです。
27152228
27162229=begin original
27172230
27182231Also:
27192232
27202233=end original
27212234
27222235また:
27232236
27242237 when ([qw(foo bar)] && /baz/) { ... }
27252238
27262239=begin original
27272240
27282241will use smartmatching because only I<one> of the operands is a boolean:
27292242the other uses smartmatching, and that wins.
27302243
27312244=end original
27322245
27332246これはスマートマッチングを使います; オペランドの I<一つ> だけが
27342247真偽値だからです: もう片方はスマートマッチングを使うので、こちらが
27352248優先されます。
27362249
27372250=begin original
27382251
27392252Further:
27402253
27412254=end original
27422255
27432256さらに:
27442257
27452258 when ([qw(foo bar)] || /^baz/) { ... }
27462259
27472260=begin original
27482261
27492262will use smart matching (only the first operand is considered), whereas
27502263
27512264=end original
27522265
27532266これはスマートマッチングを使います(最初のオペランドのみが考慮されます); 一方
27542267
27552268 when (/^baz/ || [qw(foo bar)]) { ... }
27562269
27572270=begin original
27582271
27592272will test only the regex, which causes both operands to be
27602273treated as boolean. Watch out for this one, then, because an
27612274arrayref is always a true value, which makes it effectively
27622275redundant. Not a good idea.
27632276
27642277=end original
27652278
27662279これは正規表現のみがテストされ、両方のオペランドは真偽値として
27672280扱われることになります。
27682281この場合、配列リファレンスは常に真の値なので、効率的に冗長になることに
27692282注目してください。
27702283良い考えではありません。
27712284
27722285=begin original
27732286
27742287Tautologous boolean operators are still going to be optimized
27752288away. Don't be tempted to write
27762289
27772290=end original
27782291
27792292恒久的な真偽値演算子は最適化されて除去されます。
27802293以下のように書こうとしないでください
27812294
27822295 when ("foo" or "bar") { ... }
27832296
27842297=begin original
27852298
27862299This will optimize down to C<"foo">, so C<"bar"> will never be considered (even
27872300though the rules say to use a smartmatch
27882301on C<"foo">). For an alternation like
27892302this, an array ref will work, because this will instigate smartmatching:
27902303
27912304=end original
27922305
27932306これは C<"foo"> に最適化されるので、C<"bar"> は (たとえ規則では C<"foo"> に
27942307スマートマッチングを使うとなっていたとしても) 考慮されることはありません。
27952308このような代替としては、配列リファレンスは動作します; これは
27962309スマートマッチングを使わせるからです:
27972310
27982311 when ([qw(foo bar)] { ... }
27992312
28002313=begin original
28012314
28022315This is somewhat equivalent to the C-style switch statement's fallthrough
28032316functionality (not to be confused with I<Perl's> fallthrough
28042317functionality--see below), wherein the same block is used for several
28052318C<case> statements.
28062319
28072320=end original
28082321
28092322これはある意味 C スタイルの switch 文の次の条件への移動(fallthrough)機能と
28102323等価です(I<Perl の> 次の条件への移動機能と混同しないでください--
28112324後述します); 複数の C<case> 文に同じブロックが使われます。
28122325
28132326=begin original
28142327
28152328Another useful shortcut is that, if you use a literal array or hash as the
28162329argument to C<given>, it is turned into a reference. So C<given(@foo)> is
28172330the same as C<given(\@foo)>, for example.
28182331
28192332=end original
28202333
28212334その他の便利な省略記法としては、C<given> の引数としてリテラルな配列や
28222335ハッシュを書くと、これはリファレンスに変化します。
28232336それで、例えば C<given(@foo)> は C<given(\@foo)> と同じです。
28242337
28252338=begin original
28262339
28272340C<default> behaves exactly like C<when(1 == 1)>, which is
28282341to say that it always matches.
28292342
28302343=end original
28312344
28322345C<default> は正確に C<when(1 == 1)> のように振る舞い、常に
28332346マッチングします。
28342347
28352348=head3 Breaking out
28362349
28372350(脱出)
28382351
28392352=begin original
28402353
28412354You can use the C<break> keyword to break out of the enclosing
28422355C<given> block. Every C<when> block is implicitly ended with
28432356a C<break>.
28442357
28452358=end original
28462359
28472360囲まれている C<given> ブロックから脱出するために、C<break> キーワードが
28482361使えます。
28492362全ての C<when> ブロックの末尾には暗黙に C<break> があります。
28502363
28512364=head3 Fall-through
28522365
28532366(次の条件への移動(Fall-through))
28542367
28552368=begin original
28562369
28572370You can use the C<continue> keyword to fall through from one
2858case to the next immediate C<when> or C<default>:
2371case to the next:
28592372
28602373=end original
28612374
2862ある case から 直後の C<when> または C<default> に移動るために
2375一つの条件から次へ移動するめにC<continue> キーワードが使えま:
2863C<continue> を使えます:
28642376
28652377 given($foo) {
2866 when (/x/) { say '$foo contains an x'; continue }
2378 when (/x/) { say '$foo contains an x'; continue }
2867 when (/y/) { say '$foo contains a y' }
2379 when (/y/) { say '$foo contains a y' }
2868 default { say '$foo does not contain a y' }
2380 default { say '$foo does not contain a y' }
28692381 }
28702382
28712383=head3 Return value
28722384
28732385(返り値)
28742386
28752387=begin original
28762388
28772389When a C<given> statement is also a valid expression (for example,
28782390when it's the last statement of a block), it evaluates to:
28792391
28802392=end original
28812393
28822394C<given> が有効な式でもある(例えばブロックの最後の文である)場合、
28832395以下のように評価されます:
28842396
28852397=over 4
28862398
28872399=item *
28882400
28892401=begin original
28902402
28912403An empty list as soon as an explicit C<break> is encountered.
28922404
28932405=end original
28942406
28952407明示的な C<break> に遭遇した直後なら空リスト。
28962408
28972409=item *
28982410
28992411=begin original
29002412
29012413The value of the last evaluated expression of the successful
29022414C<when>/C<default> clause, if there happens to be one.
29032415
29042416=end original
29052417
29062418もし成功していれば、成功した C<when>/C<default> 節で最後に評価された式の値。
29072419
29082420=item *
29092421
29102422=begin original
29112423
29122424The value of the last evaluated expression of the C<given> block if no
29132425condition is true.
29142426
29152427=end original
29162428
29172429どの条件も真でなければ C<given> ブロックで最後に評価された式の値。
29182430
29192431=back
29202432
29212433=begin original
29222434
29232435In both last cases, the last expression is evaluated in the context that
29242436was applied to the C<given> block.
29252437
29262438=end original
29272439
29282440最後の二つの場合、最後の式は適用された C<given> ブロックに適用された
29292441コンテキストで評価されます。
29302442
29312443=begin original
29322444
29332445Note that, unlike C<if> and C<unless>, failed C<when> statements always
29342446evaluate to an empty list.
29352447
29362448=end original
29372449
29382450C<if> や C<unless> と異なり、失敗した C<when> 文は常に空リストに
29392451評価されます。
29402452
29412453 my $price = do {
2942 given ($item) {
2454 given ($item) {
2943 when (["pear", "apple"]) { 1 }
2455 when (["pear", "apple"]) { 1 }
2944 break when "vote"; # My vote cannot be bought
2456 break when "vote"; # My vote cannot be bought
2945 1e10 when /Mona Lisa/;
2457 1e10 when /Mona Lisa/;
2946 "unknown";
2458 "unknown";
2947 }
2459 }
29482460 };
29492461
29502462=begin original
29512463
29522464Currently, C<given> blocks can't always
29532465be used as proper expressions. This
29542466may be addressed in a future version of Perl.
29552467
29562468=end original
29572469
29582470現在のところ、C<given> ブロックは常に適切な式として使うことはできません。
29592471これは将来のバージョンの Perl に対処されるでしょう。
29602472
29612473=head3 Switching in a loop
29622474
29632475(ループ内の switch)
29642476
29652477=begin original
29662478
29672479Instead of using C<given()>, you can use a C<foreach()> loop.
29682480For example, here's one way to count how many times a particular
29692481string occurs in an array:
29702482
29712483=end original
29722484
29732485C<given()> を使う代わりに、C<foreach()> ループを使えます。
29742486たとえば、以下は配列内に特定の文字列が何回現れるかを数えるための
29752487ひとつの方法です:
29762488
29772489 use v5.10.1;
29782490 my $count = 0;
29792491 for (@array) {
2980 when ("foo") { ++$count }
2492 when ("foo") { ++$count }
29812493 }
29822494 print "\@array contains $count copies of 'foo'\n";
29832495
29842496=begin original
29852497
29862498Or in a more recent version:
29872499
29882500=end original
29892501
29902502あるいはより最近のバージョンでは:
29912503
29922504 use v5.14;
29932505 my $count = 0;
29942506 for (@array) {
2995 ++$count when "foo";
2507 ++$count when "foo";
29962508 }
29972509 print "\@array contains $count copies of 'foo'\n";
29982510
29992511=begin original
30002512
30012513At the end of all C<when> blocks, there is an implicit C<next>.
30022514You can override that with an explicit C<last> if you're
30032515interested in only the first match alone.
30042516
30052517=end original
30062518
30072519C<when> ブロックの末尾に、暗黙の C<next> があります。
30082520もし最初のマッチングだけに興味があるなら、明示的な C<last> でこれを
30092521上書きできます。
30102522
30112523=begin original
30122524
30132525This doesn't work if you explicitly specify a loop variable, as
30142526in C<for $item (@array)>. You have to use the default variable C<$_>.
30152527
30162528=end original
30172529
30182530これは、C<for $item (@array)> のように明示的にループ変数を指定した場合は
30192531動作しません。
30202532デフォルト変数 C<$_> を使う必要があります。
30212533
3022=head3 Differences from Raku
2534=head3 Differences from Perl 6
30232535
3024(Raku からの違い)
2536(Perl 6 からの違い)
30252537
30262538=begin original
30272539
30282540The Perl 5 smartmatch and C<given>/C<when> constructs are not compatible
3029with their Raku analogues. The most visible difference and least
2541with their Perl 6 analogues. The most visible difference and least
30302542important difference is that, in Perl 5, parentheses are required around
30312543the argument to C<given()> and C<when()> (except when this last one is used
3032as a statement modifier). Parentheses in Raku are always optional in a
2544as a statement modifier). Parentheses in Perl 6 are always optional in a
30332545control construct such as C<if()>, C<while()>, or C<when()>; they can't be
30342546made optional in Perl 5 without a great deal of potential confusion,
30352547because Perl 5 would parse the expression
30362548
30372549=end original
30382550
3039Perl 5 のスマートマッチングと C<given>/C<when> 構文は Raku のものと
2551Perl 5 のスマートマッチングと C<given>/C<when> 構文は Perl 6 のものと
30402552互換性はありません。
30412553もっとも目に見えて、もっとも重要でない違いは、Perl 5 では、C<given()> と
30422554C<when()> の引数は (後者を文修飾子として使う場合を除いて)かっこでくくる
30432555必要があります。
3044Raku では、C<if()>, C<while()>, C<when()> のような制御構造での
2556Perl 6 では、C<if()>, C<while()>, C<when()> のような制御構造での
30452557かっこは常に省略可能です;
30462558Perl 5 では、潜在的な大混乱と引き換えにしなければこれを省略できません;
30472559なぜなら Perl 5 は以下のような表現において:
30482560
30492561 given $foo {
3050 ...
2562 ...
30512563 }
30522564
30532565=begin original
30542566
30552567as though the argument to C<given> were an element of the hash
30562568C<%foo>, interpreting the braces as hash-element syntax.
30572569
30582570=end original
30592571
30602572C<given> の引数はハッシュ C<%foo> の要素であるかのようにパースして、
30612573中かっこをハッシュ要素文法として解釈するからです。
30622574
30632575=begin original
30642576
3065However, there are many, many other differences. For example,
2577However, their are many, many other differences. For example,
30662578this works in Perl 5:
30672579
30682580=end original
30692581
30702582しかし、ここにはとても多くのその他の違いがあります。
30712583例えば、これは Perl 5 で動作します:
30722584
30732585 use v5.12;
30742586 my @primary = ("red", "blue", "green");
30752587
30762588 if (@primary ~~ "red") {
30772589 say "primary smartmatches red";
30782590 }
30792591
30802592 if ("red" ~~ @primary) {
30812593 say "red smartmatches primary";
30822594 }
30832595
30842596 say "that's all, folks!";
30852597
30862598=begin original
30872599
3088But it doesn't work at all in Raku. Instead, you should
2600But it doesn't work at all in Perl 6. Instead, you should
30892601use the (parallelizable) C<any> operator:
30902602
30912603=end original
30922604
3093しかしこれは Raku では全く動作しません。
2605しかしこれは Perl 6 では全く動作しません。
30942606代わりに、(並列化可能な) C<any> 演算子を使います:
30952607
30962608 if any(@primary) eq "red" {
30972609 say "primary smartmatches red";
30982610 }
30992611
31002612 if "red" eq any(@primary) {
31012613 say "red smartmatches primary";
31022614 }
31032615
31042616=begin original
31052617
31062618The table of smartmatches in L<perlop/"Smartmatch Operator"> is not
3107identical to that proposed by the Raku specification, mainly due to
2619identical to that proposed by the Perl 6 specification, mainly due to
3108differences between Raku's and Perl 5's data models, but also because
2620differences between Perl 6's and Perl 5's data models, but also because
3109the Raku spec has changed since Perl 5 rushed into early adoption.
2621the Perl 6 spec has changed since Perl 5 rushed into early adoption.
31102622
31112623=end original
31122624
3113L<perlop/"Smartmatch Operator"> のスマートマッチングの表は Raku 仕様で
2625L<perlop/"Smartmatch Operator"> のスマートマッチングの表は Perl 6 仕様で
3114提案されれているものと同一ではありません; 主に Raku と Perl 5 の
2626提案されれているものと同一ではありません; 主に Perl 6 と Perl 5 の
3115データモデルの違いによりますが、Raku の仕様は Perl 5 が早期に採用した
2627データモデルの違いによりますが、Perl 6 の仕様は Perl 5 が早期に採用した
31162628後に変更されたからです。
31172629
31182630=begin original
31192631
3120In Raku, C<when()> will always do an implicit smartmatch with its
2632In Perl 6, C<when()> will always do an implicit smartmatch with its
31212633argument, while in Perl 5 it is convenient (albeit potentially confusing) to
31222634suppress this implicit smartmatch in various rather loosely-defined
31232635situations, as roughly outlined above. (The difference is largely because
31242636Perl 5 does not have, even internally, a boolean type.)
31252637
31262638=end original
31272639
3128Raku では、C<when()> は常にその引数に対する暗黙のスマートマッチングを
2640Perl 6 では、C<when()> は常にその引数に対する暗黙のスマートマッチングを
31292641行いますが、Perl 5 では既に大まかに示した通り、ゆるく定義された状況によっては
31302642暗黙のスマートマッチングを抑制したほうが便利(たとえ混乱させるかも
31312643知れないにしても)です。
31322644(主な違いは、Perl 5 は内部的にさえ真偽値型を持たないことによります。)
31332645
31342646=cut
31352647
31362648=begin meta
31372649
31382650Translate: KIMURA Koichi (5.005_03)
31392651Update: SHIRAKATA Kentaro <argrath@ub32.org> (5.8.8-)
3140Status: in progress
2652Status: completed
31412653
31422654=end meta