5.38.0

NAME

perlsyn - Perl syntax

perlsyn - Perl の文法

説明

A Perl program consists of a sequence of declarations and statements which run from the top to the bottom. Loops, subroutines, and other control structures allow you to jump around within the code.

Perl プログラムは、宣言と文の並びから構成され、上から下へと実行されます。 ループ、サブルーチン、その他の制御機構でコードの色々なところに ジャンプできます。

Perl is a free-form language: you can format and indent it however you like. Whitespace serves mostly to separate tokens, unlike languages like Python where it is an important part of the syntax, or Fortran where it is immaterial.

Perl は 自由書式 言語です: 好きなように整形したりインデントしたり できます。 空白が文法の重要な要素である Python や、意味のない Fortran のような言語と 異なり、空白はほとんどトークンの分割の役目です。

Many of Perl's syntactic elements are optional. Rather than requiring you to put parentheses around every function call and declare every variable, you can often leave such explicit elements off and Perl will figure out what you meant. This is known as Do What I Mean, abbreviated DWIM. It allows programmers to be lazy and to code in a style with which they are comfortable.

Perl の多くの文法要素は 省略可能 です。 全ての関数をかっこで括ったり、全ての変数を宣言したりすることを 要求するのではなく、しばしばそのような明示的な要素を置いておいて、 Perl にあなたが意味しているところを見つけ出させることができます。 これは Do What I Mean と知られ、頭文字を取って DWIM と呼ばれます。 これによって、プログラマを 怠惰 にでき、彼らが快適だと思うスタイルで コーディングできるようにします。

Perl borrows syntax and concepts from many languages: awk, sed, C, Bourne Shell, Smalltalk, Lisp and even English. Other languages have borrowed syntax from Perl, particularly its regular expression extensions. So if you have programmed in another language you will see familiar pieces in Perl. They often work the same, but see perltrap for information about how they differ.

Perl は、awk, sed, C, Bourne Shell, Smalltalk, Lisp, 果ては英語といった、 多くの言語からコンセプトと 文法を借用 しています。 他の言語も Perl から文法を借用しています; 特に正規表現拡張をです。 従って、他の言語でプログラミングしていたなら、Perl にも見たことがあるような ものがあるでしょう。 それらはしばしば同じように動作しますが、違う点についての情報は perltrap を参照してください。

宣言

The only things you need to declare in Perl are report formats and subroutines (and sometimes not even subroutines). A scalar variable holds the undefined value (undef) until it has been assigned a defined value, which is anything other than undef. When used as a number, undef is treated as 0; when used as a string, it is treated as the empty string, ""; and when used as a reference that isn't being assigned to, it is treated as an error. If you enable warnings, you'll be notified of an uninitialized value whenever you treat undef as a string or a number. Well, usually. Boolean contexts, such as:

Perl で宣言が必要なものはレポートフォーマットとサブルーチンだけです (サブルーチンすら宣言が不要な場合もあります)。 スカラ変数は、undef 以外の定義された値を代入されるまでは未定義値 (undef)となります。 数値として使われる場合、undef0 として扱われます; 文字列として使われる場合、これは空文字列 "" として扱われます; リファレンスとして使われる場合、これは何も代入されていないので、エラーとして 扱われます。 警告を有効にしているなら、undef を文字列や数値として扱おうとすると 未初期化値を指摘されます。 ええ、普通は。 次のような真偽値コンテキストなら:

    if ($a) {}

are exempt from warnings (because they care about truth rather than definedness). Operators such as ++, --, +=, -=, and .=, that operate on undefined variables such as:

(定義済みかどうかではなく、真かどうかを考慮するので)警告から免れます。 未定義の変数を操作する、++, --, +=, -=, .= のような 演算子でも:

    undef $a;
    $a++;

are also always exempt from such warnings.

とすることでもそのような警告から免れます。

A declaration can be put anywhere a statement can, but has no effect on the execution of the primary sequence of statements: declarations all take effect at compile time. All declarations are typically put at the beginning or the end of the script. However, if you're using lexically-scoped private variables created with my(), state(), or our(), you'll have to make sure your format or subroutine definition is within the same block scope as the my if you expect to be able to access those private variables.

宣言は、文が置けるところであればどこにでも置くことができますが、 基本的な文の並びは実行時には何の効果も持ちません: 宣言はコンパイル時に すべての効果が表れます。 典型的にはすべての宣言は、スクリプトの先頭か終端に置かれます。 しかしながら、局所変数を my(),state(), or our() を使って作成して レキシカルなスコープを使っているのであれば、フォーマットやサブルーチンの 定義を、同じブロックのスコープの中でその局所変数にアクセスすることが 可能であるようにしておく必要があるでしょう。

Declaring a subroutine allows a subroutine name to be used as if it were a list operator from that point forward in the program. You can declare a subroutine without defining it by saying sub name, thus:

サブルーチンの宣言は、プログラムの後のほうにあるサブルーチン名を リスト演算子のように使うことを許します。 定義されていないサブルーチンの宣言を、sub name と記述することで 宣言できるので、以下のようにできます:

    sub myname;
    $me = myname $0             or die "can't get myname";

A bare declaration like that declares the function to be a list operator, not a unary operator, so you have to be careful to use parentheses (or or instead of ||.) The || operator binds too tightly to use after list operators; it becomes part of the last element. You can always use parentheses around the list operators arguments to turn the list operator back into something that behaves more like a function call. Alternatively, you can use the prototype ($) to turn the subroutine into a unary operator:

関数の宣言のような裸の宣言はリスト演算子のように働くのであり、 単項演算子としてではありません; ですから、かっこ (または || の代わりに or) を使うことには注意してください。 || 演算子はリスト演算子の後ろに使うには束縛が強すぎます; 最後の要素の 一部になります。 リスト演算子の周りをかっこで囲むことでいつでもリスト演算子を 関数呼び出しのように振る舞わせるようにできます。 あるいは、サブルーチンを単項演算子に変えるためにプロトタイプ ($) も使えます:

  sub myname ($);
  $me = myname $0             || die "can't get myname";

That now parses as you'd expect, but you still ought to get in the habit of using parentheses in that situation. For more on prototypes, see perlsub.

これは予想した通りにパースしますが、それでもこのような場合にはかっこを使う 習慣を付けるべきです。 プロトタイプに関してさらなる情報は、perlsub を参照してください。

Subroutines declarations can also be loaded up with the require statement or both loaded and imported into your namespace with a use statement. See perlmod for details on this.

サブルーチンの宣言は require 文を使って詰め込むこともできますし、 use 文を使って自分の名前空間にロードしたりインポートしたりすることが できます。 これに関する詳細は perlmod を参照してください。

A statement sequence may contain declarations of lexically-scoped variables, but apart from declaring a variable name, the declaration acts like an ordinary statement, and is elaborated within the sequence of statements as if it were an ordinary statement. That means it actually has both compile-time and run-time effects.

文の並びはレキシカルスコープを持った変数の宣言を含むことができますが、 変数名の宣言とは切り離され、その宣言は通常の文のように振る舞い、 それが通常の文であるかのように文の並びに組みこまれます。 これは、そういった宣言がコンパイル時の効果と実行時の効果の両方を 持っているということです。

コメント

Text from a "#" character until the end of the line is a comment, and is ignored. Exceptions include "#" inside a string or regular expression.

コメントは "#" 文字から、行末まで続き、その部分は無視されます。 例外は、文字列や正規表現の中にある "#" です。

単純文

The only kind of simple statement is an expression evaluated for its side-effects. Every simple statement must be terminated with a semicolon, unless it is the final statement in a block, in which case the semicolon is optional. But put the semicolon in anyway if the block takes up more than one line, because you may eventually add another line. Note that there are operators like eval {}, sub {}, and do {} that look like compound statements, but aren't--they're just TERMs in an expression--and thus need an explicit termination when used as the last item in a statement.

単純文となる唯一の種類は、その副作用のために評価される式です。 すべての単純文は、それがセミコロンを省略することのできるブロックの 最後にない限りは文を終端するためのセミコロンがなければなりません。 ブロックが二行以上に渡る場合には、とにかくセミコロンを付けてください; なぜなら、別の行を追加する可能性があるからです。 eval {}, sub {}, do {} のように、一見複合文のように 見える けれども そうではない--これらは単なる式における TERM です--ものがあって、 そういったものを文の最後のアイテムとして使った場合には明示的に終端する 必要があるのだということに注意してください。

文修飾子

Any simple statement may optionally be followed by a SINGLE modifier, just before the terminating semicolon (or block ending). The possible modifiers are:

任意の単純文には、一つ の修飾子を終端のセミコロンの直前(もしくは ブロックの終端の直前)に付けることができます。 使うことのできる修飾子は以下の通りです。

    if EXPR
    unless EXPR
    while EXPR
    until EXPR
    for LIST
    foreach LIST
    when EXPR

The EXPR following the modifier is referred to as the "condition". Its truth or falsehood determines how the modifier will behave.

修飾子に引き続く EXPR は「条件」として参照されます。 その真偽値が修飾子の振る舞いを決定します。

if executes the statement once if and only if the condition is true. unless is the opposite, it executes the statement unless the condition is true (that is, if the condition is false). See "Scalar values" in perldata for definitions of true and false.

ifもし 条件が真の場合にのみ文を実行します。 unless は逆で、条件が真 でない限り (つまり、条件が偽なら) 文を 実行します。 真と偽の定義については "Scalar values" in perldata を参照してください。

    print "Basset hounds got long ears" if length $ear >= 10;
    go_outside() and play() unless $is_raining;

The for(each) modifier is an iterator: it executes the statement once for each item in the LIST (with $_ aliased to each item in turn). There is no syntax to specify a C-style for loop or a lexically scoped iteration variable in this form.

for(each) 修飾子は反復子です: LIST の値それぞれ毎に文を実行します(実行中は $_ がそれぞれの値の エイリアスとなります)。 この形式で C 風のループやレキシカルスコープの繰り返し変数を 指定する文法はありません。

    print "Hello $_!\n" for qw(world Dolly nurse);

while repeats the statement while the condition is true. Postfix while has the same magic treatment of some kinds of condition that prefix while has. until does the opposite, it repeats the statement until the condition is true (or while the condition is false):

while は条件が真 の間 文を繰り返します。 後置 while は、ある種の条件において、前置 while と同じ マジカルな処理をします。 until は逆で、条件が真 になるまで (つまり条件が偽の間) 文を 繰り返します:

    # Both of these count from 0 to 10.
    print $i++ while $i <= 10;
    print $j++ until $j >  10;

The while and until modifiers have the usual "while loop" semantics (conditional evaluated first), except when applied to a do-BLOCK (or to the Perl4 do-SUBROUTINE statement), in which case the block executes once before the conditional is evaluated.

修飾子 whileuntil は、一般的な "while loop" の意味を 持っています(条件が最初に評価される)が、do-ブロック(もしくは Perl4 の do-サブルーチン文)に適用されるときは例外で、 このときは条件が評価されるよりも前に、一度ブロックが実行されます。

This is so that you can write loops like:

このため、次のようなループを記述することができます:

    do {
        $line = <STDIN>;
        ...
    } until !defined($line) || $line eq ".\n"

See "do" in perlfunc. Note also that the loop control statements described later will NOT work in this construct, because modifiers don't take loop labels. Sorry. You can always put another block inside of it (for next/redo) or around it (for last) to do that sort of thing.

"do" in perlfunc を参照してください。 後述するループの制御文は、修飾子がループラベルを取らないために この構造文では 動作しない ということにも注意してください。 申し訳ない。 こういった場合に対処するのに別のブロックを内側に入れたり(next の場合)、 別のブロックで囲む(last/redo の場合)という方法が常に使えます。

For next or redo, just double the braces:

nextredo では単に中かっこを二重にします:

    do {{
        next if $x == $y;
        # do something here
    }} until $x++ > $z;

For last, you have to be more elaborate and put braces around it:

last の場合は、もっと念入りにする必要があり、中かっこで囲みます:

    {
        do {
            last if $x == $y**2;
            # do something here
        } while $x++ <= $z;
    }

If you need both next and last, you have to do both and also use a loop label:

nextlast の両方が必要な場合、両方を使ってさらにループラベルを 使う必要があります:

    LOOP: {
        do {{
            next if $x == $y;
            last LOOP if $x == $y**2;
            # do something here
        }} until $x++ > $z;
    }

NOTE: The behaviour of a my, state, or our modified with a statement modifier conditional or loop construct (for example, my $x if ...) is undefined. The value of the my variable may be undef, any previously assigned value, or possibly anything else. Don't rely on it. Future versions of perl might do something different from the version of perl you try it out on. Here be dragons.

注意: (my $x if ... のような) 条件構造やループ構造で修飾された my state,our 文の振る舞いは 未定義 です。 my 変数の値は undef かも知れませんし、以前に代入された値かも 知れませんし、その他の如何なる値の可能性もあります。 この値に依存してはいけません。 perl の将来のバージョンでは現在のバージョンとは何か違うかも知れません。 ここには厄介なものがいます。

The when modifier is an experimental feature that first appeared in Perl 5.14. To use it, you should include a use v5.14 declaration. (Technically, it requires only the switch feature, but that aspect of it was not available before 5.14.) Operative only from within a foreach loop or a given block, it executes the statement only if the smartmatch $_ ~~ EXPR is true. If the statement executes, it is followed by a next from inside a foreach and break from inside a given.

when 修飾子は Perl 5.14 で最初に現れた実験的機能です。 使うには、use v5.14 宣言を含めます。 (技術的には、switch 機能だけが必要ですが、この観点では 5.14 より前では 利用できません。) foreach ループか given ブロックの内側でのみ動作可能で、 スマートマッチング $_ ~~ EXPR が真の場合にのみ実行されます。 文が実行されると、foreach の内側からは next に、given の 内側からは break に引き続きます。

Under the current implementation, the foreach loop can be anywhere within the when modifier's dynamic scope, but must be within the given block's lexical scope. This restriction may be relaxed in a future release. See "Switch Statements" below.

現在の実装では、foreach ループは when 修飾子の動的スコープの内側の どこでも使えますが、given ブロックのレキシカルスコープの内側で なければなりません。 この制限は将来のリリースで緩和されるかもしれません。 後述する "Switch Statements" を参照してください。

複合文

In Perl, a sequence of statements that defines a scope is called a block. Sometimes a block is delimited by the file containing it (in the case of a required file, or the program as a whole), and sometimes a block is delimited by the extent of a string (in the case of an eval).

Perl では、スコープを定義するような文の並びをブロックと呼びます。 ブロックはそれを含むファイルによって範囲が定められることがあります (ファイルが require されたときか、プログラム全体としての場合)し、 文字列の展開によって範囲が定められる(eval の場合)こともあります。

But generally, a block is delimited by curly brackets, also known as braces. We will call this syntactic construct a BLOCK. Because enclosing braces are also the syntax for hash reference constructor expressions (see perlref), you may occasionally need to disambiguate by placing a ; immediately after an opening brace so that Perl realises the brace is the start of a block. You will more frequently need to disambiguate the other way, by placing a + immediately before an opening brace to force it to be interpreted as a hash reference constructor expression. It is considered good style to use these disambiguating mechanisms liberally, not only when Perl would otherwise guess incorrectly.

しかし一般的には、ブロックは中かっこによって範囲が定められます。 この構文的な構造をブロックと呼びます。 中かっこによる囲みはハッシュリファレンス初期化表現 (perlref 参照) の 文法でもあるので、中かっこがブロックの開始であることを Perl が分かるように、 時々開き中かっこの直後に ; を置くことで曖昧さをなくす 必要があるかもしれません。 より頻繁には、ハッシュリファレンス初期化表現として解釈されることを 強制するために、開き中かっこの直前に + を置くことで逆方向に 曖昧さをなくす必要があるかも知れません。 これらのあいまいさをなくす機構は、Perl が間違って推測するときだけではなく、 より安全に使うのがよいスタイルと考えられています。

The following compound statements may be used to control flow:

以下に挙げる複合文を制御フローとして使うことができます:

    if (EXPR) BLOCK
    if (EXPR) BLOCK else BLOCK
    if (EXPR) BLOCK elsif (EXPR) BLOCK ...
    if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK

    unless (EXPR) BLOCK
    unless (EXPR) BLOCK else BLOCK
    unless (EXPR) BLOCK elsif (EXPR) BLOCK ...
    unless (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK

    given (EXPR) BLOCK

    LABEL while (EXPR) BLOCK
    LABEL while (EXPR) BLOCK continue BLOCK

    LABEL until (EXPR) BLOCK
    LABEL until (EXPR) BLOCK continue BLOCK

    LABEL for (EXPR; EXPR; EXPR) BLOCK
    LABEL for VAR (LIST) BLOCK
    LABEL for VAR (LIST) BLOCK continue BLOCK

    LABEL foreach (EXPR; EXPR; EXPR) BLOCK
    LABEL foreach VAR (LIST) BLOCK
    LABEL foreach VAR (LIST) BLOCK continue BLOCK

    LABEL BLOCK
    LABEL BLOCK continue BLOCK

    PHASE BLOCK

As of Perl 5.36, you can iterate over multiple values at a time by specifying a list of lexicals within parentheses:

Perl 5.36 から、かっこの中にレキシカル変数のリストを指定することで、 一度に複数の値を反復できます:

    no warnings "experimental::for_list";
    LABEL for my (VAR, VAR) (LIST) BLOCK
    LABEL for my (VAR, VAR) (LIST) BLOCK continue BLOCK
    LABEL foreach my (VAR, VAR) (LIST) BLOCK
    LABEL foreach my (VAR, VAR) (LIST) BLOCK continue BLOCK

If enabled by the experimental try feature, the following may also be used

実験的な try 機能によって有効の場合、次のものも使えます:

    try BLOCK catch (VAR) BLOCK
    try BLOCK catch (VAR) BLOCK finally BLOCK

The experimental given statement is not automatically enabled; see "Switch Statements" below for how to do so, and the attendant caveats.

実験的な given 文は 自動的に有効にはなりません; その方法と、それに 伴う注意点については後述する "Switch Statements" を参照してください。

Unlike in C and Pascal, in Perl these are all defined in terms of BLOCKs, not statements. This means that the curly brackets are required--no dangling statements allowed. If you want to write conditionals without curly brackets, there are several other ways to do it. The following all do the same thing:

C や Pascal とは異なり、Perl ではブロックを取るように 定義されていて文を取るのではありません。 つまり、中かっこは 必要なもの です -- 曖昧な文が許されません。 中かっこなしの条件文を使いたいのであれば、いくつかのやり方があります。 以下の全ては同じことです:

    if (!open(FOO)) { die "Can't open $FOO: $!" }
    die "Can't open $FOO: $!" unless open(FOO);
    open(FOO)  || die "Can't open $FOO: $!";
    open(FOO) ? () : die "Can't open $FOO: $!";
        # a bit exotic, that last one

The if statement is straightforward. Because BLOCKs are always bounded by curly brackets, there is never any ambiguity about which if an else goes with. If you use unless in place of if, the sense of the test is reversed. Like if, unless can be followed by else. unless can even be followed by one or more elsif statements, though you may want to think twice before using that particular language construct, as everyone reading your code will have to think at least twice before they can understand what's going on.

if 文は明解です。 ブロックは常に中かっこで区切られるので、ifelse の対応が 曖昧になるようなことは決してありません。 unlessif の代わりに使うと、検査を反転します。 if と同様、unlesselse に引き続くことができます。 unless は一つまたはそれ以上の elsif に引き続くことすらできますが、 この特定の言語構文を使う前に二倍考えたいでしょう; あなたのコードを読む 誰もが何が行われているのかを理解する前に少なくとも二倍考える必要が あるからです。

The while statement executes the block as long as the expression is true. The until statement executes the block as long as the expression is false. The LABEL is optional, and if present, consists of an identifier followed by a colon. The LABEL identifies the loop for the loop control statements next, last, and redo. If the LABEL is omitted, the loop control statement refers to the innermost enclosing loop. This may include dynamically searching through your call-stack at run time to find the LABEL. Such desperate behavior triggers a warning if you use the use warnings pragma or the -w flag.

while 文は、式が真である間、ブロックを実行します。 until 文は、式が偽である間、ブロックを実行します。 LABEL は省略可能ですが、ある場合には、コロンを伴った識別子になります。 LABEL は nextlastredo といったループ制御文のループを規定します。 LABEL が省略された場合、ループ制御文はそれを含むループの中で最も内側の ループを参照します。 これは、実行時に LABEL を検出するための呼び出しスタックを動的に検索することを 含むことができます。 そのような推奨されない振る舞いは、use warnings プラグマや -w フラグを 使った場合には警告を引き起こします。

If the condition expression of a while statement is based on any of a group of iterative expression types then it gets some magic treatment. The affected iterative expression types are readline, the <FILEHANDLE> input operator, readdir, glob, the <PATTERN> globbing operator, and each. If the condition expression is one of these expression types, then the value yielded by the iterative operator will be implicitly assigned to $_. If the condition expression is one of these expression types or an explicit assignment of one of them to a scalar, then the condition actually tests for definedness of the expression's value, not for its regular truth value.

while 文の条件式が反復式型のグループの一つの場合、 マジカルな扱いを受けます。 影響を受ける反復式型は、 readline<FILEHANDLE> 入力反復子、readdirglob<PATTERN> グロブ演算子、each です。 条件式がこれらの式の型の一つの場合、反復演算子によって 取り出された値は暗黙に $_ に代入されます。 条件式がこれらの式の型の一つか、これらの一つからスカラへの明示的な代入の 場合、条件は実際には通常の真の値かどうかではなく、式の値が 定義値かどうかをテストします。

If there is a continue BLOCK, it is always executed just before the conditional is about to be evaluated again. Thus it can be used to increment a loop variable, even when the loop has been continued via the next statement.

continue ブロックが存在する場合、 常に条件が再評価される直前に実行されます。 したがって、このブロックをループ変数のインクリメントのために 使うことができます; これは、ループがnext文を通して継続されるときでも実行されます。

When a block is preceded by a compilation phase keyword such as BEGIN, END, INIT, CHECK, or UNITCHECK, then the block will run only during the corresponding phase of execution. See perlmod for more details.

ブロックの前に BEGIN, END, INIT, CHECK, UNITCHECK のような コンパイルフェーズキーワードが前置されると、ブロックは対応する実行フェーズの 間にだけ実行されます。 さらなる詳細については perlmod を参照してください。

Extension modules can also hook into the Perl parser to define new kinds of compound statements. These are introduced by a keyword which the extension recognizes, and the syntax following the keyword is defined entirely by the extension. If you are an implementor, see "PL_keyword_plugin" in perlapi for the mechanism. If you are using such a module, see the module's documentation for details of the syntax that it defines.

エクステンションモジュールは新しい種類の複合文を定義するために Perl パーサをフックできます。 これらはエクステンションが認識するキーワードで導入され、キーワードに 引き続く文法は完全にエクステンションで定義されます。 もしあなたが実装車なら、仕組みについては "PL_keyword_plugin" in perlapi を 参照してください。 あなたがそのようなモジュールを使うなら、定義されている文法の詳細については そのモジュールの文書を参照してください。

ループ制御

The next command starts the next iteration of the loop:

next コマンドはループの次の繰り返しを開始します:

    LINE: while (<STDIN>) {
        next LINE if /^#/;      # discard comments
        ...
    }

The last command immediately exits the loop in question. The continue block, if any, is not executed:

last コマンドはループから即座に脱出します。 continue ブロックがあっても、それは実行されません:

    LINE: while (<STDIN>) {
        last LINE if /^$/;      # exit when done with header
        ...
    }

The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed. This command is normally used by programs that want to lie to themselves about what was just input.

redo コマンドは、条件の再評価をすることなしにループブロックの 再実行を行います。 continue ブロックがあっても、それは 実行されません。 このコマンドは通常、プログラムに対する入力に関してプログラム自身を だましたいといったときに使われます。

For example, when processing a file like /etc/termcap. If your input lines might end in backslashes to indicate continuation, you want to skip ahead and get the next record.

たとえば、/etc/termcap のようなファイルを処理することを 考えてみましょう。 もし入力された行の行末が継続を示すバックスラッシュであった場合、先へ進んで 次のレコードを取り出したいと思うでしょう。

    while (<>) {
        chomp;
        if (s/\\$//) {
            $_ .= <>;
            redo unless eof();
        }
        # now process $_
    }

which is Perl shorthand for the more explicitly written version:

これは Perl の省略記法で、もっとはっきりと書くと以下のようになります:

    LINE: while (defined($line = <ARGV>)) {
        chomp($line);
        if ($line =~ s/\\$//) {
            $line .= <ARGV>;
            redo LINE unless eof(); # not eof(ARGV)!
        }
        # now process $line
    }

Note that if there were a continue block on the above code, it would get executed only on lines discarded by the regex (since redo skips the continue block). A continue block is often used to reset line counters or m?pat? one-time matches:

上記の例で continue ブロックがあったとしたら、それは (redo は continue ブロックをスキップするので) 正規表現によって 捨てられた行だけが実行されるということに注意してください。 continue ブロックは行カウンターをリセットするとか、 一度だけマッチする m?pat? をリセットするのに使われます。

    # inspired by :1,$g/fred/s//WILMA/
    while (<>) {
        m?(fred)?    && s//WILMA $1 WILMA/;
        m?(barney)?  && s//BETTY $1 BETTY/;
        m?(homer)?   && s//MARGE $1 MARGE/;
    } continue {
        print "$ARGV $.: $_";
        close ARGV  if eof;             # reset $.
        reset       if eof;             # reset ?pat?
    }

If the word while is replaced by the word until, the sense of the test is reversed, but the conditional is still tested before the first iteration.

whileuntil で置き換えた場合検査の意味は逆転しますが、 繰り返しが実行されるより前に条件が検査されることは変わりありません。

Loop control statements don't work in an if or unless, since they aren't loops. You can double the braces to make them such, though.

ループ制御文は ifunless 中では動作しません; なぜならそこはループではないからです。 しかし中かっこを二重にしてこれに対処することはできます。

    if (/pattern/) {{
        last if /fred/;
        next if /barney/; # same effect as "last",
                          # but doesn't document as well
        # do something here
    }}

This is caused by the fact that a block by itself acts as a loop that executes once, see "Basic BLOCKs".

これは、ブロック自身は一度だけ実行されるループとして動作するからです; "Basic BLOCKs" を参照してください。

The form while/if BLOCK BLOCK, available in Perl 4, is no longer available. Replace any occurrence of if BLOCK by if (do BLOCK).

Perl 4 では使うことのできた while/if BLOCK BLOCK という形式は、 もはや使うことができません。 if BLOCK の部分を if (do BLOCK) で置き換えてください。

for ループ

Perl's C-style for loop works like the corresponding while loop; that means that this:

Perl の C 形式の for ループは、対応する while ループと同様に 動作します; つまり、以下のものは:

    for ($i = 1; $i < 10; $i++) {
        ...
    }

is the same as this:

以下のものと同じです:

    $i = 1;
    while ($i < 10) {
        ...
    } continue {
        $i++;
    }

There is one minor difference: if variables are declared with my in the initialization section of the for, the lexical scope of those variables is exactly the for loop (the body of the loop and the control sections). To illustrate:

小さな違いが一つあります: for の初期化部で my を使って変数が 宣言された場合、この変数のレキシカルスコープは for ループ (ループ本体と制御部) と完全に同じです。 図示すると:

    my $i = 'samba';
    for (my $i = 1; $i <= 4; $i++) {
        print "$i\n";
    }
    print "$i\n";

when executed, gives:

実行すると、次のものになります:

    1
    2
    3
    4
    samba

As a special case, if the test in the for loop (or the corresponding while loop) is empty, it is treated as true. That is, both

特別な場合として、もし for ループ (または対応する while ループ) の テストが空なら、真として扱われます。 つまり、次のもの

    for (;;) {
        ...
    }

and

および

    while () {
        ...
    }

are treated as infinite loops.

は無限ループとして扱われます。

Besides the normal array index looping, for can lend itself to many other interesting applications. Here's one that avoids the problem you get into if you explicitly test for end-of-file on an interactive file descriptor causing your program to appear to hang.

通常の、配列に対する添え字付けのループのほかにも、for は他の 多くの興味深いアプリケーションのために借用することができます。 以下の例は、対話的なファイル記述子の終端を明示的に検査してしまうと プログラムをハングアップしたように見えてしまう問題を回避するものです。

    $on_a_tty = -t STDIN && -t STDOUT;
    sub prompt { print "yes? " if $on_a_tty }
    for ( prompt(); <STDIN>; prompt() ) {
        # do something
    }

The condition expression of a for loop gets the same magic treatment of readline et al that the condition expression of a while loop gets.

for ループの条件式は、while ループの条件式で行われるものと同様、 readline のマジカルな扱いが行われます。

foreach ループ

The foreach loop iterates over a normal list value and sets the scalar variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs only for non C-style loops.

foreach ループは 通常のリスト値に対しての繰り返しを行い、スカラ変数 VAR に リストの要素を繰り返し一回に一つずつセットします。 変数の前に my というキーワードが置かれていた場合、その変数は レキシカルスコープを持ち、したがってそれはループの中でのみ可視となります。 このキーワードがなければ、変数はループに対してローカルとなり、ループを 抜けた後で以前の値が再度取得されます。 変数が事前に my を使って宣言されていたならば、グローバルなものの 代わりにその変数を使いますが、それもループにローカルなものとなります。 この暗黙のローカル化は非 C 形式のループの中で のみ 起きます。

The foreach keyword is actually a synonym for the for keyword, so you can use either. If VAR is omitted, $_ is set to each value.

foreach は実際には for の同義語なので、どちらでも使えます。 VAR が省略された場合には、$_ に値が設定されます。

If any element of LIST is an lvalue, you can modify it by modifying VAR inside the loop. Conversely, if any element of LIST is NOT an lvalue, any attempt to modify that element will fail. In other words, the foreach loop index variable is an implicit alias for each item in the list that you're looping over.

LIST の要素が左辺値であった場合、ループの中で VAR を変更することにより、 対応する値を変更することができます。 逆に、LIST の要素が左辺値でない場合は、この要素を修正しようとしても 失敗します。 言い換えると、foreach ループの帰納変数がループの対象となっている リスト中の個々のアイテムに対するエイリアスになっているからです。

If any part of LIST is an array, foreach will get very confused if you add or remove elements within the loop body, for example with splice. So don't do that.

LIST のいずれかの部分が配列であった場合に、たとえば splice を使って ループの本体でその要素を削除したりあるいは追加したりすると foreach は非常に混乱してしまいます。 ですからそういうことをしてはいけません。

foreach probably won't do what you expect if VAR is a tied or other special variable. Don't do that either.

VAR が tie されていたりあるいは他の特殊変数であった場合には foreach はあなたのもくろみどおりには動かないでしょう。 こういうこともしてはいけません。

As of Perl 5.22, there is an experimental variant of this loop that accepts a variable preceded by a backslash for VAR, in which case the items in the LIST must be references. The backslashed variable will become an alias to each referenced item in the LIST, which must be of the correct type. The variable needn't be a scalar in this case, and the backslash may be followed by my. To use this form, you must enable the refaliasing feature via use feature. (See feature. See also "Assigning to References" in perlref.)

Perl 5.22 から、VAR に逆スラッシュを前置する変数を受け付けるという このループの実験的なバリエーションがあります; この場合 LIST のアイテムは リファレンスでなければなりません。 逆スラッシュつき変数は LIST の中のアイテムへのリファレンスとなるエイリアスに なり; 正しい方でなければなりません。 この場合変数はスカラである必要はなく、逆スラッシュには my が 引き続くことができます。 この形式を使うには、use featurerefaliasing 機能を 有効にしなければなりません。 (feature を参照してください。 "Assigning to References" in perlref も参照してください。)

As of Perl 5.36, you can iterate over multiple values at a time. You can only iterate with lexical scalars as the iterator variables - unlike list assignment, it's not possible to use undef to signify a value that isn't wanted. This is a limitation of the current implementation, and might be changed in the future.

Perl 5.36 から、一度に複数の値を反復できます。 反復変数としてレキシカルスカラのみ反復できます - リスト代入と異なり、 不要な値を示すために undef を使うことは出来ません。 これは現在の実装の制限で、将来変更されるかもしれません。

If the size of the LIST is not an exact multiple of the number of iterator variables, then on the last iteration the "excess" iterator variables are aliases to undef, as if the LIST had , undef appended as many times as needed for its length to become an exact multiple. This happens whether LIST is a literal LIST or an array - ie arrays are not extended if their size is not a multiple of the iteration size, consistent with iterating an array one-at-a-time. As these padding elements are not lvalues, attempting to modify them will fail, consistent with the behaviour when iterating a list with literal undefs. If this is not the behaviour you desire, then before the loop starts either explicitly extend your array to be an exact multiple, or explicitly throw an exception.

LIST の大きさが反復変数の数の整数倍でない場合、 最後の反復では「超過した」反復変数は undef への別名になります; LIST の長さが整数倍になるのに必要なだけ , undef が 追加されているかのようになります。 これは LIST がリテラルな LIST でも配列でも起こります - つまり、配列が 反復の長さの整数倍でない場合も拡張されません; 一度に一つだけ 配列を反復する場合と一貫しています。 これらの追加された要素は左辺値ではないので、これを変更しようとすると 失敗します; リテラルな undef のリストを反復したときの振る舞いと 一貫しています。 これが望んでいる振る舞いでないなら、ループを開始する前に整数倍になるように 明示的に拡張するか、明示的に例外を投げてください。

Examples:

例:

    for (@ary) { s/foo/bar/ }

    for my $elem (@elements) {
        $elem *= 2;
    }

    for $count (reverse(1..10), "BOOM") {
        print $count, "\n";
        sleep(1);
    }

    for (1..15) { print "Merry Christmas\n"; }

    foreach $item (split(/:[\\\n:]*/, $ENV{TERMCAP})) {
        print "Item: $item\n";
    }

    use feature "refaliasing";
    no warnings "experimental::refaliasing";
    foreach \my %hash (@array_of_hash_references) {
        # do something with each %hash
    }

    foreach my ($foo, $bar, $baz) (@list) {
        # do something three-at-a-time
    }

    foreach my ($key, $value) (%hash) {
        # iterate over the hash
        # The hash is immediately copied to a flat list before the loop
        # starts. The list contains copies of keys but aliases of values.
        # This is the same behaviour as for $var (%hash) {...}
    }

Here's how a C programmer might code up a particular algorithm in Perl:

以下の例は、C プログラマーが Perl でとあるアルゴリズムを記述するときに 使うであろうやり方です:

    for (my $i = 0; $i < @ary1; $i++) {
        for (my $j = 0; $j < @ary2; $j++) {
            if ($ary1[$i] > $ary2[$j]) {
                last; # can't go to outer :-(
            }
            $ary1[$i] += $ary2[$j];
        }
        # this is where that last takes me
    }

Whereas here's how a Perl programmer more comfortable with the idiom might do it:

それに対して、次の例は Perl プログラマーが同じことをよりゆったりとして 行うやり方です:

    OUTER: for my $wid (@ary1) {
    INNER:   for my $jet (@ary2) {
                next OUTER if $wid > $jet;
                $wid += $jet;
             }
          }

See how much easier this is? It's cleaner, safer, and faster. It's cleaner because it's less noisy. It's safer because if code gets added between the inner and outer loops later on, the new code won't be accidentally executed. The next explicitly iterates the other loop rather than merely terminating the inner one. And it's faster because Perl executes a foreach statement more rapidly than it would the equivalent C-style for loop.

どのくらいこれが簡単になったように見えますか? これは明確で、安全で、高速です。 これは余計なものが少ないので明確なのです。 これは後で内側のループと外側のループとの間にコードを付加えた場合でも、 それを間違って実行することがないので安全なのです。 next は内側のループを終了するのではなく、外側のループの繰り返しを 行います。 そしてこれは、Perl は foreach 文をそれと等価な C 形式の for ループよりも すばやく実行するので高速なのです。

Perceptive Perl hackers may have noticed that a for loop has a return value, and that this value can be captured by wrapping the loop in a do block. The reward for this discovery is this cautionary advice: The return value of a for loop is unspecified and may change without notice. Do not rely on it.

洞察力のある Perl ハッカーは、for ループに返り値があり、この値は ループを do ブロックで包むことによって捕捉できることに 気付くかもしれません。 この発見に対する報奨は、この警告的なアドバイスです: for ループの返り値は 未定義で、予告なしに変更されることがあります。 これに依存してはいけません。

Try Catch Exception Handling

The try/catch syntax provides control flow relating to exception handling. The try keyword introduces a block which will be executed when it is encountered, and the catch block provides code to handle any exception that may be thrown by the first.

try/catch 構文は、例外処理に関連する制御フローを提供します。 try キーワードは、それが検出されたときに実行されるブロックを導入し、 catch ブロックは、最初のものによって投げられる可能性のある例外を 処理するコードを提供します。

    try {
        my $x = call_a_function();
        $x < 100 or die "Too big";
        send_output($x);
    }
    catch ($e) {
        warn "Unable to output a value; $e";
    }
    print "Finished\n";

Here, the body of the catch block (i.e. the warn statement) will be executed if the initial block invokes the conditional die, or if either of the functions it invokes throws an uncaught exception. The catch block can inspect the $e lexical variable in this case to see what the exception was. If no exception was thrown then the catch block does not happen. In either case, execution will then continue from the following statement - in this example the print.

ここで、catch ブロックの本体 (つまり、warn 文) は、最初の ブロックが条件付き die を呼び出した場合、または呼び出した関数のいずれかが 捕捉されない例外を投げた場合に実行されます。 catch ブロックは、この場合の $e レキシカル変数を検査して、例外が何かを 調べることができます。 例外が投げられなかった場合、catch ブロックは発生しません。 いずれの場合も、次の文 (この例では print) から実行が続行されます。

The catch keyword must be immediately followed by a variable declaration in parentheses, which introduces a new variable visible to the body of the subsequent block. Inside the block this variable will contain the exception value that was thrown by the code in the try block. It is not necessary to use the my keyword to declare this variable; this is implied (similar as it is for subroutine signatures).

catch キーワードの直後には、かっこで囲まれた変数宣言が 続かなければなりません; これにより、後続のブロックの本文から見える新しい変数が導入されます。 ブロック内では、この変数には、try ブロック内のコードによって投げられた 例外値が含まれます。 この変数を宣言するために my キーワードを使用する必要はありません; これは(サブルーチンシグネチャの場合と同様)暗黙的です。

Both the try and the catch blocks are permitted to contain control-flow expressions, such as return, goto, or next/last/redo. In all cases they behave as expected without warnings. In particular, a return expression inside the try block will make its entire containing function return - this is in contrast to its behaviour inside an eval block, where it would only make that block return.

try ブロックと catch ブロックの両方に、return, goto, next/last/redo などの制御フロー式を含めることができます。 いずれの場合も、警告なしに想定通りに動作します。 特に、try ブロック内の return 式は、それを含む関数全体から返ります - これは、そのブロックからのみ返る eval ブロック内での動作とは対照的です。

Like other control-flow syntax, try and catch will yield the last evaluated value when placed as the final statement in a function or a do block. This permits the syntax to be used to create a value. In this case remember not to use the return expression, or that will cause the containing function to return.

他の制御フロー構文と同様に、trycatch は、関数または do ブロックの最後のステートメントとして配置された場合に、最後に評価された値を 生成します。 これにより、この構文を使用して値を作成できます。 この場合、return 式を使用しないでください; 使用すると、含まれる関数から戻ることになります。

    my $value = do {
        try {
            get_thing(@args);
        }
        catch ($e) {
            warn "Unable to get thing - $e";
            $DEFAULT_THING;
        }
    };

As with other control-flow syntax, try blocks are not visible to caller() (just as for example, while or foreach loops are not). Successive levels of the caller result can see subroutine calls and eval blocks, because those affect the way that return would work. Since try blocks do not intercept return, they are not of interest to caller.

他の制御フロー構文と同様に、try ブロックは caller() には見えません (例えば、while または foreach ループが見えないのと同様です)。 caller の結果の連続するレベルは、サブルーチン呼び出しと eval ブロックを 見ることができます; なぜなら、それらは return の動作方法に 影響するからです。 try ブロックは return に割り込まないので、それらは caller には関係ありません。

The try and catch blocks may optionally be followed by a third block introduced by the finally keyword. This third block is executed after the rest of the construct has finished.

trycatch のブロックは、オプションとして、finally キーワードで 導入される第 3 のブロックを引き続かせることができます。 この第 3 のブロックは構文の残りの部分が完了した後に実行されます。

    try {
        call_a_function();
    }
    catch ($e) {
        warn "Unable to call; $e";
    }
    finally {
        print "Finished\n";
    }

The finally block is equivalent to using a defer block and will be invoked in the same situations; whether the try block completes successfully, throws an exception, or transfers control elsewhere by using return, a loop control, or goto.

finally ブロックは defer ブロックを使うのと等価で、 同じ状況で起動されます; try ブロックが正常に完了するか、 例外が投げられるか、return、ループ制御、goto を使うことによって 別の場所に制御が移るかしたときです。

Unlike the try and catch blocks, a finally block is not permitted to return, goto or use any loop controls. The final expression value is ignored, and does not affect the return value of the containing function even if it is placed last in the function.

trycatch ブロックとは異なり、finally ブロックは return, goto あるいはループ制御は許されません。 最後の式の値は無視され、たとえこれが関数の最後に置かれていても、 これを含んでいる関数の返り値には影響を与えません。

This syntax is currently experimental and must be enabled with use feature 'try'. It emits a warning in the experimental::try category.

この構文は現在実験的であり、use feature 'try' を使用して有効にする 必要があります。 experimental::try カテゴリの警告を出力します。

基本ブロック (BLOCK)

A BLOCK by itself (labeled or not) is semantically equivalent to a loop that executes once. Thus you can use any of the loop control statements in it to leave or restart the block. (Note that this is NOT true in eval{}, sub{}, or contrary to popular belief do{} blocks, which do NOT count as loops.) The continue block is optional.

ブロックそれ自身は(ラベルが付いていようがついてなかろうが)一度だけ 実行されるループと、文法的には等価なものです。 このため、ブロックから脱出するためやブロックの再スタートのために 任意のループ制御文を使うことができます。 (これは eval{}sub{}、 さらに一般的な認識とは異なり ループではない do{} ブロックに対しては 真ではない ということに注意してください。) continue ブロックは省略することができます。

The BLOCK construct can be used to emulate case structures.

BLOCK 構造は case 構造を行うのにも使えます。

    SWITCH: {
        if (/^abc/) { $abc = 1; last SWITCH; }
        if (/^def/) { $def = 1; last SWITCH; }
        if (/^xyz/) { $xyz = 1; last SWITCH; }
        $nothing = 1;
    }

You'll also find that foreach loop used to create a topicalizer and a switch:

主題化器とスイッチを作るために使われた foreach ループも見るかもしれません:

    SWITCH:
    for ($var) {
        if (/^abc/) { $abc = 1; last SWITCH; }
        if (/^def/) { $def = 1; last SWITCH; }
        if (/^xyz/) { $xyz = 1; last SWITCH; }
        $nothing = 1;
    }

Such constructs are quite frequently used, both because older versions of Perl had no official switch statement, and also because the new version described immediately below remains experimental and can sometimes be confusing.

古いバージョンの Perl には公式の switch 文がなく、直後に記述する 新しいバージョンはまだ実験的で時々混乱させることがあるので、 このような構文はとてもよく使われています。

defer ブロック

A block prefixed by the defer modifier provides a section of code which runs at a later time during scope exit.

defer 修飾子を前置したブロックは、後でスコープが終了している間に 実行されるコードを提供します。

A defer block can appear at any point where a regular block or other statement is permitted. If the flow of execution reaches this statement, the body of the block is stored for later, but not invoked immediately. When the flow of control leaves the containing block for any reason, this stored block is executed on the way past. It provides a means of deferring execution until a later time. This acts similarly to syntax provided by some other languages, often using keywords named try / finally.

defer ブロックは、通常のブロックは他の文が許される場所なら どこにでも置くことができます。 実行フローがその文に届くと、ブロックの本体は後のために保管されますが、 直ちに起動はしません。 フロー制御がなんらかの理由で含まれているブロックから離れたとき、 この保管されていたブロックが通過する途中で実行されます。 これは、後に実行を遅延させる意味を提供します。 これは他の言語で、しばしば try / finally という名前のキーワードを 使って提供されている文法と似た動作をします。

This syntax is available if enabled by the defer named feature, and is currently experimental. If experimental warnings are enabled it will emit a warning when used.

この文法は defer という名前付き機能が有効の場合に利用可能で、 これは現在の所実験的です。 実験的警告が有効の場合、使われたときに警告が発生します。

    use feature 'defer';

    {
        say "This happens first";
        defer { say "This happens last"; }

        say "And this happens inbetween";
    }

If multiple defer blocks are contained in a single scope, they are executed in LIFO order; the last one reached is the first one executed.

一つのスコープに複数の defer ブロックがある場合、LIFO 順で実行されます; 最後に現れたものが最初に実行されます。

The code stored by the defer block will be invoked when control leaves its containing block due to regular fallthrough, explicit return, exceptions thrown by die or propagated by functions called by it, goto, or any of the loop control statements next, last or redo.

defer ブロックに保管されているコードは、通常の通過、明示的な returndie あるいは呼び出した関数から伝搬した例外、 goto、またはループ制御文 next, last, redo のいずれかによって、 制御がブロックから離れたときに実行されます。

If the flow of control does not reach the defer statement itself then its body is not stored for later execution. (This is in direct contrast to the code provided by an END phaser block, which is always enqueued by the compiler, regardless of whether execution ever reached the line it was given on.)

フロー制御が defer 文自体に届かない場合、その本体は後の実行のために 保管されません。 (これは、実行がその行に届くかどうかに関わらず常にコンパイラによって キューに入れられる END フェーズブロックとの直接の違いです。)

    use feature 'defer';

    {
        defer { say "This will run"; }
        return;
        defer { say "This will not"; }
    }

Exceptions thrown by code inside a defer block will propagate to the caller in the same way as any other exception thrown by normal code.

defer ブロックの内側で投げられた例外は、通常のコードで 投げられたその他の例外と同様に、呼び出し元に伝搬します。

If the defer block is being executed due to a thrown exception and throws another one it is not specified what happens, beyond that the caller will definitely receive an exception.

defer ブロックが例外が投げられたために実行され、 もう一つの例外が投げられた場合、、呼び出し元が例外を受け取るということ 以上に何が起こるかは未規定です。

Besides throwing an exception, a defer block is not permitted to otherwise alter the control flow of its surrounding code. In particular, it may not cause its containing function to return, nor may it goto a label, or control a containing loop using next, last or redo. These constructions are however, permitted entirely within the body of the defer.

例外を投げること以外、defer ブロックがその周りのコードの制御フローを 変えることは許されていません。 特に、含んでいる関数に return を引き起こしたり、ラベルに goto したり、 next, last, redo を使って含まれているループを制御してはいけません。 しかし、これらの構文は、完全に defer の内部だけの場合は許されます。

    use feature 'defer';

    {
        defer {
            foreach ( 1 .. 5 ) {
                last if $_ == 3;     # this is permitted
            }
        }
    }

    {
        foreach ( 6 .. 10 ) {
            defer {
                last if $_ == 8;     # this is not
            }
        }
    }

switch 文

Starting from Perl 5.10.1 (well, 5.10.0, but it didn't work right), you can say

Perl 5.10.1 から(えっと、5.10.0 からですが、正しく動いていませんでした)、 以下のように書くと:

    use feature "switch";

to enable an experimental switch feature. This is loosely based on an old version of a Raku proposal, but it no longer resembles the Raku construct. You also get the switch feature whenever you declare that your code prefers to run under a version of Perl between 5.10 and 5.34. For example:

実験的な switch 機能を有効にします。 これはおおまかに Raku 提案の古い版を基にしていますが、もはや Raku の構文と共通点はありません。 コードが 5.10 から 5.34 の間の Perl バージョンで実行されるように 宣言したときもいつでも switch 機能を得られます。 例えば:

    use v5.14;

Under the "switch" feature, Perl gains the experimental keywords given, when, default, continue, and break. Starting from Perl 5.16, one can prefix the switch keywords with CORE:: to access the feature without a use feature statement. The keywords given and when are analogous to switch and case in other languages -- though continue is not -- so the code in the previous section could be rewritten as

"switch" 機能の基では、Perl は実験的なキーワード given, when, default, continue, break を得ます。 Perl 5.16 から、use feature 文なしで機能にアクセスするために、 switch キーワードに CORE:: を前置できます。 キーワード givenwhen は -- continue は違いますが -- 他の言語での switch および case と 同様のものなので、前の節のコードは以下のように書き直せます:

    use v5.10.1;
    for ($var) {
        when (/^abc/) { $abc = 1 }
        when (/^def/) { $def = 1 }
        when (/^xyz/) { $xyz = 1 }
        default       { $nothing = 1 }
    }

The foreach is the non-experimental way to set a topicalizer. If you wish to use the highly experimental given, that could be written like this:

foreach は主題化器を設定する実験的でない方法です。 とても実験的な given を使いたいなら、以下のように書けます:

    use v5.10.1;
    given ($var) {
        when (/^abc/) { $abc = 1 }
        when (/^def/) { $def = 1 }
        when (/^xyz/) { $xyz = 1 }
        default       { $nothing = 1 }
    }

As of 5.14, that can also be written this way:

5.14 現在、これは以下のようにも書けます:

    use v5.14;
    for ($var) {
        $abc = 1 when /^abc/;
        $def = 1 when /^def/;
        $xyz = 1 when /^xyz/;
        default { $nothing = 1 }
    }

Or if you don't care to play it safe, like this:

あるいは、安全にすることを気にしないなら、以下のようにします:

    use v5.14;
    given ($var) {
        $abc = 1 when /^abc/;
        $def = 1 when /^def/;
        $xyz = 1 when /^xyz/;
        default { $nothing = 1 }
    }

The arguments to given and when are in scalar context, and given assigns the $_ variable its topic value.

givenwhen への引数はスカラコンテキストで、 given$_ 変数に注目している値を代入します。

Exactly what the EXPR argument to when does is hard to describe precisely, but in general, it tries to guess what you want done. Sometimes it is interpreted as $_ ~~ EXPR, and sometimes it is not. It also behaves differently when lexically enclosed by a given block than it does when dynamically enclosed by a foreach loop. The rules are far too difficult to understand to be described here. See "Experimental Details on given and when" later on.

when への EXPR 引数が正確に何をするかを正確に記述するのは 難しいですが、一般的には、あなたのしたいことを推測しようとします。 これは $_ ~~ EXPR として解釈される場合もあり、そうでない場合も あります。 これはまた、given ブロックでレキシカルに囲まれた場合は、foreach ループによって動的に囲まれた場合とは異なった振る舞いをします。 規則はここで記述されたよりも遥かに理解しにくいものです。 後述する "Experimental Details on given and when" を参照してください。

Due to an unfortunate bug in how given was implemented between Perl 5.10 and 5.16, under those implementations the version of $_ governed by given is merely a lexically scoped copy of the original, not a dynamically scoped alias to the original, as it would be if it were a foreach or under both the original and the current Raku language specification. This bug was fixed in Perl 5.18 (and lexicalized $_ itself was removed in Perl 5.24).

Perl 5.10 と 5.14 の間での given の実装方法による不幸なバグにより、 現在の実装では、given によって管理される $_ は、 foreach の場合やオリジナルと現在両方の Raku 言語仕様のように 元のものの動的スコープな別名ではなく、単なるレキシカルスコープのコピーです。 このバグは Perl 5.18 で修正されました (そしてレキシカルな $_ 自身は Perl 5.24 で削除されました)。

If your code still needs to run on older versions, stick to foreach for your topicalizer and you will be less unhappy.

あなたのコードがまだ古いバージョンでも動作する必要があるなら、 主題化器には foreach を使うことで不幸を減らせます。

goto 文

Although not for the faint of heart, Perl does support a goto statement. There are three forms: goto-LABEL, goto-EXPR, and goto-&NAME. A loop's LABEL is not actually a valid target for a goto; it's just the name of the loop.

気弱な人のためでないにも関らず、Perl は goto 文をサポートしています。 goto-LABEL、goto-EXPR、goto-&NAME の三つの形式があります。 ループのラベルは実際には goto の正当なターゲットではなく、 ループの名前にすぎません。

The goto-LABEL form finds the statement labeled with LABEL and resumes execution there. It may not be used to go into any construct that requires initialization, such as a subroutine or a foreach loop. It also can't be used to go into a construct that is optimized away. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but it's usually better to use some other construct such as last or die. The author of Perl has never felt the need to use this form of goto (in Perl, that is--C is another matter).

goto-LABEL 形式は LABEL でラベル付けされた文を見つけだし、そこから 実行を再開します。 これはサブルーチンであるとか foreach ループのような 初期化を必要とするような構造へ飛び込むために使うことはできません。 また、最適化されて無くなってしまうような構造へ飛び込むこともできません。 動的スコープの中以外のほとんどの場所へは、サブルーチンの外も含めて 移動することができます; しかし、通常は lastdie のような 別のやり方を使ったほうが良いでしょう。 Perl の作者は、未だかつてこの形式の goto を使うことが 必要だと感じたことはありません(Perl の場合です--C の場合はまた別の話です)。

The goto-EXPR form expects a label name, whose scope will be resolved dynamically. This allows for computed gotos per FORTRAN, but isn't necessarily recommended if you're optimizing for maintainability:

goto-EXPR 形式は動的に解決されるスコープを持っているラベル名を 期待しています。 これによって FORTRAN の計算型 goto が実現できますが、 これは保守性に重きを置くのであれば使うことは止めた方が良いでしょう。

    goto(("FOO", "BAR", "GLARCH")[$i]);

The goto-&NAME form is highly magical, and substitutes a call to the named subroutine for the currently running subroutine. This is used by AUTOLOAD() subroutines that wish to load another subroutine and then pretend that the other subroutine had been called in the first place (except that any modifications to @_ in the current subroutine are propagated to the other subroutine.) After the goto, not even caller() will be able to tell that this routine was called first.

goto-&NAME は高度にマジカルで、名前付きサブルーチンの呼び出しを カレントで実行されているサブルーチンに置き換えます。 これは別のサブルーチンをロードして、最初の場所で呼び出された 別のサブルーチンを要求することをしようとする AUTOLOAD() サブルーチンで使われていてます (カレントのサブルーチンにおける @_ に対するもの以外の変更は、 別のサブルーチンへ伝播します)。 goto の後で、caller() でなくてもこのサブルーチンが 最初に呼ばれたのだということを伝えることすらできるでしょう。

In almost all cases like this, it's usually a far, far better idea to use the structured control flow mechanisms of next, last, or redo instead of resorting to a goto. For certain applications, the catch and throw pair of eval{} and die() for exception processing can also be a prudent approach.

このようなケースのほとんどすべての場合、goto に頼るのではなくて nextlastredo といった制御フロー機構を使うことが、 ずっとずっと良いアイデアでしょう。 一部のアプリケーションに対しては、eval{} と die() を catch と throw のペアとして例外処理を行うための賢明なアプローチとして 使うことができるでしょう。

省略文

Beginning in Perl 5.12, Perl accepts an ellipsis, "...", as a placeholder for code that you haven't implemented yet. When Perl 5.12 or later encounters an ellipsis statement, it parses this without error, but if and when you should actually try to execute it, Perl throws an exception with the text Unimplemented:

Perl 5.12 から、Perl はまだ実装していないコードのプレースホルダとして 省略 "..." を受け付けるようになりました。 Perl 5.12 以降で省略文に遭遇すると、エラーなくパースしますが、実際に 実行しようとすると、Unimplemented というテキストと共に例外を投げます:

    use v5.12;
    sub unimplemented { ... }
    eval { unimplemented() };
    if ($@ =~ /^Unimplemented at /) {
        say "I found an ellipsis!";
    }

You can only use the elliptical statement to stand in for a complete statement. Syntactically, "...;" is a complete statement, but, as with other kinds of semicolon-terminated statement, the semicolon may be omitted if "..." appears immediately before a closing brace. These examples show how the ellipsis works:

完全な文を使える場所でのみ省略文を使えます。 文法的には、"...;" は完全な文ですが、その他のセミコロン終端する 文と同様、"..." が閉じ中かっこの直前に現れる場合は、 セミコロンは省略できます。 次の例は省略がどのように動作するかの例です:

    use v5.12;
    { ... }
    sub foo { ... }
    ...;
    eval { ... };
    sub somemeth {
        my $self = shift;
        ...;
    }
    $x = do {
        my $n;
        ...;
        say "Hurrah!";
        $n;
    };

The elliptical statement cannot stand in for an expression that is part of a larger statement. These examples of attempts to use an ellipsis are syntax errors:

省略文はより大きな文の一部の式としては使えません。 省略を使おうとする以下の例は文法エラーになります:

    use v5.12;

    print ...;
    open(my $fh, ">", "/dev/passwd") or ...;
    if ($condition && ... ) { say "Howdy" };
    ... if $a > $b;
    say "Cromulent" if ...;
    $flub = 5 + ...;

There are some cases where Perl can't immediately tell the difference between an expression and a statement. For instance, the syntax for a block and an anonymous hash reference constructor look the same unless there's something in the braces to give Perl a hint. The ellipsis is a syntax error if Perl doesn't guess that the { ... } is a block. Inside your block, you can use a ; before the ellipsis to denote that the { ... } is a block and not a hash reference constructor.

式と文との違いをすぐに説明できない場合があります。 例えば、ブロックと無名ハッシュリファレンスのコンストラクタは、 Perl にヒントを与える中かっこがなければ同じに見えます。 省略文は Perl が { ... } をブロックと判断できなかった場合は 文法エラーとなります。 ブロックの中では、{ ... } がブロックであってハッシュリファレンスの コンストラクタでないことを示すために、省略の前に ; を使えます。

Note: Some folks colloquially refer to this bit of punctuation as a "yada-yada" or "triple-dot", but its true name is actually an ellipsis.

注意: 一部の人間はこの句読点を口語的に「ヤダヤダ」や「3 点」として 参照しますが、真の名前は実際には省略です。

POD: 組み込みドキュメント

Perl has a mechanism for intermixing documentation with source code. While it's expecting the beginning of a new statement, if the compiler encounters a line that begins with an equal sign and a word, like this

Perl は、ソースコードとドキュメントとを混ぜ書きするための仕掛けを 持っています。 新しい文の始まりが期待されているときに、コンパイラは 以下の例のような = 記号で始まっている語を見つけると:

    =head1 Here There Be Pods!

Then that text and all remaining text up through and including a line beginning with =cut will be ignored. The format of the intervening text is described in perlpod.

そのテキストと、=cut で始まる行までの内容を無視します。 間に入るテキストの書式は perlpod で説明されています。

This allows you to intermix your source code and your documentation text freely, as in

これによって、ソースコードとドキュメントとを以下に示す例のように 自由に混ぜることができるようになります。

    =item snazzle($)

    The snazzle() function will behave in the most spectacular
    form that you can possibly imagine, not even excepting
    cybernetic pyrotechnics.

    =cut back to the compiler, nuff of this pod stuff!

    sub snazzle($) {
        my $thingie = shift;
        .........
    }

Note that pod translators should look at only paragraphs beginning with a pod directive (it makes parsing easier), whereas the compiler actually knows to look for pod escapes even in the middle of a paragraph. This means that the following secret stuff will be ignored by both the compiler and the translators.

コンパイラはパラグラフの途中に pod エスケープがあったとしてもそれを 認識できるのに、pod トランスレータは pod 指示子で始まっている パラグラフのみに注目すべき(これは構文解析を簡単にするためです)で あるということに注意して下さい。 つまり、以下の例にある "secret stuff" はコンパイラからも、 トランスレータからも無視されるということです。

    $a=3;
    =secret stuff
     warn "Neither POD nor CODE!?"
    =cut back
    print "got $a\n";

You probably shouldn't rely upon the warn() being podded out forever. Not all pod translators are well-behaved in this regard, and perhaps the compiler will become pickier.

この例の warn() のようなものが、将来に渡って無視されるということに 依存すべきではありません。 すべての pod トランスレータがそのように振る舞うわけではありませんし、 コンパイラは将来これを無視しないようになるかもしれません。

One may also use pod directives to quickly comment out a section of code.

pod 指示子を、コードの一部を手っ取り早くコメントアウトするために 使うこともできます。

Plain Old Comments (Not!)

Perl can process line directives, much like the C preprocessor. Using this, one can control Perl's idea of filenames and line numbers in error or warning messages (especially for strings that are processed with eval()). The syntax for this mechanism is almost the same as for most C preprocessors: it matches the regular expression

C のプリプロセッサと同じように、Perl は行指示子を処理できます。 これを使うことによって、エラーメッセージや警告メッセージにある ファイル名や行番号を制御することができます (特に、eval() で処理される文字列のために)。 この仕組みの構文はほとんどの C のプリプロセッサとほとんど同じで、正規表現:

    # example: '# line 42 "new_filename.plx"'
    /^\#   \s*
      line \s+ (\d+)   \s*
      (?:\s("?)([^"]+)\g2)? \s*
     $/x

with $1 being the line number for the next line, and $3 being the optional filename (specified with or without quotes). Note that no whitespace may precede the #, unlike modern C preprocessors.

にマッチしたものの $1 が次の行の行番号となり、省略することもできる $3 は(クォートありかなしで指定された)ファイル名となります。 最近の C プリプロセッサとは違って、# の前に空白を置けないことに 注意してください。

There is a fairly obvious gotcha included with the line directive: Debuggers and profilers will only show the last source line to appear at a particular line number in a given file. Care should be taken not to cause line number collisions in code you'd like to debug later.

行指示子にはかなり明らかな技があります: デバッガとプロファイラは、 与えられたファイルの特定の行番号に対して現れた最新のソース行のみを 表示します。 あとでデバッグしたいコードでは行番号の衝突が起きないように注意するべきです。

Here are some examples that you should be able to type into your command shell:

コマンドシェルでタイプすることのできる例をいくつか挙げます:

    % perl
    # line 200 "bzzzt"
    # the '#' on the previous line must be the first char on line
    die 'foo';
    __END__
    foo at bzzzt line 201.

    % perl
    # line 200 "bzzzt"
    eval qq[\n#line 2001 ""\ndie 'foo']; print $@;
    __END__
    foo at - line 2001.

    % perl
    eval qq[\n#line 200 "foo bar"\ndie 'foo']; print $@;
    __END__
    foo at foo bar line 200.

    % perl
    # line 345 "goop"
    eval "\n#line " . __LINE__ . ' "' . __FILE__ ."\"\ndie 'foo'";
    print $@;
    __END__
    foo at goop line 345.

given と when の実験的な詳細

As previously mentioned, the "switch" feature is considered highly experimental (it is also scheduled to be removed in perl 5.42.0); it is subject to change with little notice. In particular, when has tricky behaviours that are expected to change to become less tricky in the future. Do not rely upon its current (mis)implementation. Before Perl 5.18, given also had tricky behaviours that you should still beware of if your code must run on older versions of Perl.

既に述べたように、"switch" 機能は非常に実験的であると考えられています (また perl 5.42.0 で削除されることが予定されています); ほとんど知らせることなく変更されることがあります。 特に when はトリッキーな振る舞いがあり、将来よりトリッキーで なくなるように変更される予定です。 現在の(誤)実装に依存しないでください。 Perl 5.18 より前では、given には、コードが古いバージョンの Perl でも 動かなければならない場合に気をつけるべきトリッキーな振る舞いもあります:

Here is a longer example of given:

これはより長い given の例です:

    use feature ":5.10";
    given ($foo) {
        when (undef) {
            say '$foo is undefined';
        }
        when ("foo") {
            say '$foo is the string "foo"';
        }
        when ([1,3,5,7,9]) {
            say '$foo is an odd digit';
            continue; # Fall through
        }
        when ($_ < 100) {
            say '$foo is numerically less than 100';
        }
        when (\&complicated_check) {
            say 'a complicated check for $foo is true';
        }
        default {
            die q(I don't know what to do with $foo);
        }
    }

Before Perl 5.18, given(EXPR) assigned the value of EXPR to merely a lexically scoped copy (!) of $_, not a dynamically scoped alias the way foreach does. That made it similar to

Perl 5.18 より前では、given(EXPR)EXPR の値を単にレキシカルスコープを 持つ $_コピー (!) に代入します; foreach がするような動的 スコープを持つ別名ではありません。 これは以下と似ています:

        do { my $_ = EXPR; ... }

except that the block was automatically broken out of by a successful when or an explicit break. Because it was only a copy, and because it was only lexically scoped, not dynamically scoped, you could not do the things with it that you are used to in a foreach loop. In particular, it did not work for arbitrary function calls if those functions might try to access $_. Best stick to foreach for that.

しかし、ブロックは when が成功するか、明示的な break によって 自動的に破壊されるところが違いました。 これはただのコピーで、動的スコープではなくレキシカルなスコープしか 持たないので、foreach ループの中でできるようなことはできませんでした。 特に、$_ にアクセスしようとするかもしれない関数の場合、任意の関数呼び出しに 対しては動作していませんでした。 そのためには foreach にこだわるのが最良です。

Most of the power comes from the implicit smartmatching that can sometimes apply. Most of the time, when(EXPR) is treated as an implicit smartmatch of $_, that is, $_ ~~ EXPR. (See "Smartmatch Operator" in perlop for more information on smartmatching.) But when EXPR is one of the 10 exceptional cases (or things like them) listed below, it is used directly as a boolean.

強力さのほとんどは時々適用される暗黙のスマートマッチングによるものです。 ほとんどの場合、when(EXPR) は暗黙の $_ のスマートマッチング、 つまり $_ ~~ EXPR として扱われます。 (スマートマッチングに関するさらなる情報については "Smartmatch Operator" in perlop を参照してください。) しかし EXPR が後述する 10 の例外の場合(および似たような場合) の 一つの場合、直接真偽値として使われます。

1.

A user-defined subroutine call or a method invocation.

ユーザー定義サブルーチンかメソッド呼び出し。

2.

A regular expression match in the form of /REGEX/, $foo =~ /REGEX/, or $foo =~ EXPR. Also, a negated regular expression match in the form !/REGEX/, $foo !~ /REGEX/, or $foo !~ EXPR.

/REGEX/, $foo =~ /REGEX/, $foo =~ EXPR 形式の 正規表現マッチング。 また、!/REGEX/, $foo !~ /REGEX/, $foo !~ EXPR 形式の 正規表現マッチングの否定。

3.

A smart match that uses an explicit ~~ operator, such as EXPR ~~ EXPR.

EXPR ~~ EXPR のように、明示的に ~~ 演算子を使うスマートマッチング。

NOTE: You will often have to use $c ~~ $_ because the default case uses $_ ~~ $c , which is frequently the opposite of what you want.

注意: しばしば $c ~~ $_ を使う必要があることに注意してください; なぜならデフォルトの場合は $_ ~~ $c を使い、これはしばしばしたいことの 逆だからです。

4.

A boolean comparison operator such as $_ < 10 or $x eq "abc". The relational operators that this applies to are the six numeric comparisons (<, >, <=, >=, ==, and !=), and the six string comparisons (lt, gt, le, ge, eq, and ne).

$_ < 10$x eq "abc" のような真偽値比較。 これを適用する関係演算子は、六つの数値比較 (<, >, <=, >=, ==, !=) および 六つの文字列比較 (lt, gt, le, ge, eq, ne) です。

5.

At least the three builtin functions defined(...), exists(...), and eof(...). We might someday add more of these later if we think of them.

少なくとも三つの組み込み関数 defined(...), exists(...), eof(...)。 これらについて考えるとき、いつかもっと追加するかもしれません。

6.

A negated expression, whether !(EXPR) or not(EXPR), or a logical exclusive-or, (EXPR1) xor (EXPR2). The bitwise versions (~ and ^) are not included.

否定表現 !(EXPR) または not(EXPR)、 排他的論理和 (EXPR1) xor (EXPR2)。 ビット版 (~^) は含まれません。

7.

A filetest operator, with exactly 4 exceptions: -s, -M, -A, and -C, as these return numerical values, not boolean ones. The -z filetest operator is not included in the exception list.

真偽値ではなく数値を返す四つの例外: -s, -M, -A, -C を除く ファイルテスト演算子。 -z ファイルテスト演算子は例外の一覧には含まれません。

8.

The .. and ... flip-flop operators. Note that the ... flip-flop operator is completely different from the ... elliptical statement just described.

フリップフロップ演算子 ........ フリップフロップ演算子は先に記述した ... 省略文とは完全に 異なることに注意してください。

In those 8 cases above, the value of EXPR is used directly as a boolean, so no smartmatching is done. You may think of when as a smartsmartmatch.

上述の八つの場合、EXPR の値は直接真偽値として使われるため、 スマートマッチングは行われません。 スマートマッチングとして when を考えるかもしれません。

Furthermore, Perl inspects the operands of logical operators to decide whether to use smartmatching for each one by applying the above test to the operands:

更に、Perl はオペランドに上述のテストを適用することで、それぞれに スマートマッチングを使うかどうかを決定するために論理演算子の オペランドを調べます:

9.

If EXPR is EXPR1 && EXPR2 or EXPR1 and EXPR2, the test is applied recursively to both EXPR1 and EXPR2. Only if both operands also pass the test, recursively, will the expression be treated as boolean. Otherwise, smartmatching is used.

EXPR が EXPR1 && EXPR2 または EXPR1 and EXPR2 の場合、テストは EXPR1 と EXPR2 の両方に 再帰的 に適用されます。 両方の オペランドがテストに 再帰的に 成功した場合にのみ、この式は 真偽値として扱われます。 さもなければ、スマートマッチングが使われます。

10.

If EXPR is EXPR1 || EXPR2, EXPR1 // EXPR2, or EXPR1 or EXPR2, the test is applied recursively to EXPR1 only (which might itself be a higher-precedence AND operator, for example, and thus subject to the previous rule), not to EXPR2. If EXPR1 is to use smartmatching, then EXPR2 also does so, no matter what EXPR2 contains. But if EXPR2 does not get to use smartmatching, then the second argument will not be either. This is quite different from the && case just described, so be careful.

EXPR が EXPR1 || EXPR2, EXPR1 // EXPR2, or EXPR1 or EXPR2 の場合、 テストは EXPR1 (例えば、より高い優先順位である AND 演算子; 従って 前述の規則に従う)のみに対して 再帰的に 適用されます; EXPR2 には 適用されません。 EXPR1 がスマートマッチングを使うなら、EXPR2 も、その内容に関わらず そうします。 しかし EXPR2 がスマートマッチングを使わないなら、二番目の引数はどちらでも ありません。 これは既に記述した && の場合とはかなり異なりますので注意してください。

These rules are complicated, but the goal is for them to do what you want (even if you don't quite understand why they are doing it). For example:

これらの規則は複雑ですが、この目標は (たとえあなたがなぜそうしているかを 完全に理解していなくても) あなたが実行したい通りに実行することです。 例えば:

    when (/^\d+$/ && $_ < 75) { ... }

will be treated as a boolean match because the rules say both a regex match and an explicit test on $_ will be treated as boolean.

これは真偽値マッチングとして扱われます; 規則では正規表現マッチングと $_ への明示的なテストはどちらも真偽値として扱われるからです。

Also:

また:

    when ([qw(foo bar)] && /baz/) { ... }

will use smartmatching because only one of the operands is a boolean: the other uses smartmatching, and that wins.

これはスマートマッチングを使います; オペランドの 一つ だけが 真偽値だからです: もう片方はスマートマッチングを使うので、こちらが 優先されます。

Further:

さらに:

    when ([qw(foo bar)] || /^baz/) { ... }

will use smart matching (only the first operand is considered), whereas

これはスマートマッチングを使います(最初のオペランドのみが考慮されます); 一方

    when (/^baz/ || [qw(foo bar)]) { ... }

will test only the regex, which causes both operands to be treated as boolean. Watch out for this one, then, because an arrayref is always a true value, which makes it effectively redundant. Not a good idea.

これは正規表現のみがテストされ、両方のオペランドは真偽値として 扱われることになります。 この場合、配列リファレンスは常に真の値なので、効率的に冗長になることに 注目してください。 良い考えではありません。

Tautologous boolean operators are still going to be optimized away. Don't be tempted to write

恒久的な真偽値演算子は最適化されて除去されます。 以下のように書こうとしないでください

    when ("foo" or "bar") { ... }

This will optimize down to "foo", so "bar" will never be considered (even though the rules say to use a smartmatch on "foo"). For an alternation like this, an array ref will work, because this will instigate smartmatching:

これは "foo" に最適化されるので、"bar" は (たとえ規則では "foo" に スマートマッチングを使うとなっていたとしても) 考慮されることはありません。 このような代替としては、配列リファレンスは動作します; これは スマートマッチングを使わせるからです:

    when ([qw(foo bar)] { ... }

This is somewhat equivalent to the C-style switch statement's fallthrough functionality (not to be confused with Perl's fallthrough functionality--see below), wherein the same block is used for several case statements.

これはある意味 C スタイルの switch 文の次の条件への移動(fallthrough)機能と 等価です(Perl の 次の条件への移動機能と混同しないでください-- 後述します); 複数の case 文に同じブロックが使われます。

Another useful shortcut is that, if you use a literal array or hash as the argument to given, it is turned into a reference. So given(@foo) is the same as given(\@foo), for example.

その他の便利な省略記法としては、given の引数としてリテラルな配列や ハッシュを書くと、これはリファレンスに変化します。 それで、例えば given(@foo)given(\@foo) と同じです。

default behaves exactly like when(1 == 1), which is to say that it always matches.

default は正確に when(1 == 1) のように振る舞い、常に マッチングします。

脱出

You can use the break keyword to break out of the enclosing given block. Every when block is implicitly ended with a break.

囲まれている given ブロックから脱出するために、break キーワードが 使えます。 全ての when ブロックの末尾には暗黙に break があります。

次の条件への移動(Fall-through)

You can use the continue keyword to fall through from one case to the next immediate when or default:

ある case から 直後の when または default に移動するために continue を使えます:

    given($foo) {
        when (/x/) { say '$foo contains an x'; continue }
        when (/y/) { say '$foo contains a y'            }
        default    { say '$foo does not contain a y'    }
    }

返り値

When a given statement is also a valid expression (for example, when it's the last statement of a block), it evaluates to:

given が有効な式でもある(例えばブロックの最後の文である)場合、 以下のように評価されます:

  • An empty list as soon as an explicit break is encountered.

    明示的な break に遭遇した直後なら空リスト。

  • The value of the last evaluated expression of the successful when/default clause, if there happens to be one.

    もし成功していれば、成功した when/default 節で最後に評価された式の値。

  • The value of the last evaluated expression of the given block if no condition is true.

    どの条件も真でなければ given ブロックで最後に評価された式の値。

In both last cases, the last expression is evaluated in the context that was applied to the given block.

最後の二つの場合、最後の式は適用された given ブロックに適用された コンテキストで評価されます。

Note that, unlike if and unless, failed when statements always evaluate to an empty list.

ifunless と異なり、失敗した when 文は常に空リストに 評価されます。

    my $price = do {
        given ($item) {
            when (["pear", "apple"]) { 1 }
            break when "vote";      # My vote cannot be bought
            1e10  when /Mona Lisa/;
            "unknown";
        }
    };

Currently, given blocks can't always be used as proper expressions. This may be addressed in a future version of Perl.

現在のところ、given ブロックは常に適切な式として使うことはできません。 これは将来のバージョンの Perl に対処されるでしょう。

ループ内の switch

Instead of using given(), you can use a foreach() loop. For example, here's one way to count how many times a particular string occurs in an array:

given() を使う代わりに、foreach() ループを使えます。 たとえば、以下は配列内に特定の文字列が何回現れるかを数えるための ひとつの方法です:

    use v5.10.1;
    my $count = 0;
    for (@array) {
        when ("foo") { ++$count }
    }
    print "\@array contains $count copies of 'foo'\n";

Or in a more recent version:

あるいはより最近のバージョンでは:

    use v5.14;
    my $count = 0;
    for (@array) {
        ++$count when "foo";
    }
    print "\@array contains $count copies of 'foo'\n";

At the end of all when blocks, there is an implicit next. You can override that with an explicit last if you're interested in only the first match alone.

when ブロックの末尾に、暗黙の next があります。 もし最初のマッチングだけに興味があるなら、明示的な last でこれを 上書きできます。

This doesn't work if you explicitly specify a loop variable, as in for $item (@array). You have to use the default variable $_.

これは、for $item (@array) のように明示的にループ変数を指定した場合は 動作しません。 デフォルト変数 $_ を使う必要があります。

Raku からの違い

The Perl 5 smartmatch and given/when constructs are not compatible with their Raku analogues. The most visible difference and least important difference is that, in Perl 5, parentheses are required around the argument to given() and when() (except when this last one is used as a statement modifier). Parentheses in Raku are always optional in a control construct such as if(), while(), or when(); they can't be made optional in Perl 5 without a great deal of potential confusion, because Perl 5 would parse the expression

Perl 5 のスマートマッチングと given/when 構文は Raku のものと 互換性はありません。 もっとも目に見えて、もっとも重要でない違いは、Perl 5 では、given()when() の引数は (後者を文修飾子として使う場合を除いて)かっこでくくる 必要があります。 Raku では、if(), while(), when() のような制御構造での かっこは常に省略可能です; Perl 5 では、潜在的な大混乱と引き換えにしなければこれを省略できません; なぜなら Perl 5 は以下のような表現において:

    given $foo {
        ...
    }

as though the argument to given were an element of the hash %foo, interpreting the braces as hash-element syntax.

given の引数はハッシュ %foo の要素であるかのようにパースして、 中かっこをハッシュ要素文法として解釈するからです。

However, their are many, many other differences. For example, this works in Perl 5:

しかし、ここにはとても多くのその他の違いがあります。 例えば、これは Perl 5 で動作します:

    use v5.12;
    my @primary = ("red", "blue", "green");

    if (@primary ~~ "red") {
        say "primary smartmatches red";
    }

    if ("red" ~~ @primary) {
        say "red smartmatches primary";
    }

    say "that's all, folks!";

But it doesn't work at all in Raku. Instead, you should use the (parallelizable) any operator:

しかしこれは Raku では全く動作しません。 代わりに、(並列化可能な) any 演算子を使います:

   if any(@primary) eq "red" {
       say "primary smartmatches red";
   }

   if "red" eq any(@primary) {
       say "red smartmatches primary";
   }

The table of smartmatches in "Smartmatch Operator" in perlop is not identical to that proposed by the Raku specification, mainly due to differences between Raku's and Perl 5's data models, but also because the Raku spec has changed since Perl 5 rushed into early adoption.

"Smartmatch Operator" in perlop のスマートマッチングの表は Raku 仕様で 提案されれているものと同一ではありません; 主に Raku と Perl 5 の データモデルの違いによりますが、Raku の仕様は Perl 5 が早期に採用した 後に変更されたからです。

In Raku, when() will always do an implicit smartmatch with its argument, while in Perl 5 it is convenient (albeit potentially confusing) to suppress this implicit smartmatch in various rather loosely-defined situations, as roughly outlined above. (The difference is largely because Perl 5 does not have, even internally, a boolean type.)

Raku では、when() は常にその引数に対する暗黙のスマートマッチングを 行いますが、Perl 5 では既に大まかに示した通り、ゆるく定義された状況によっては 暗黙のスマートマッチングを抑制したほうが便利(たとえ混乱させるかも 知れないにしても)です。 (主な違いは、Perl 5 は内部的にさえ真偽値型を持たないことによります。)