5.6.1 > Perl

名前

perlop - Perl operators and precedence

Perl の演算子と優先順位

概要

Perl operators have the following associativity and precedence, listed from highest precedence to lowest. Operators borrowed from C keep the same precedence relationship with each other, even where C's precedence is slightly screwy. (This makes learning Perl easier for C folks.) With very few exceptions, these all operate on scalar values only, not array values.

Perl の演算子には、以下のような結合性と優先順位 (高い優先順位から 低いものへ並べている) があります。 C から持ってきた演算子の優先順位は、C での優先順位が多少おかしくても、 そのままにしてあります。 (これによって、C を使っている方が Perl に移りやすくなっています。) ごく僅かな例外を別として、全ての演算子はスカラ値のみを持ち、 配列値を持ちません。

    left        terms and list operators (leftward)
    left        ->
    nonassoc    ++ --
    right       **
    right       ! ~ \ and unary + and -
    left        =~ !~
    left        * / % x
    left        + - .
    left        << >>
    nonassoc    named unary operators
    nonassoc    < > <= >= lt gt le ge
    nonassoc    == != <=> eq ne cmp
    left        &
    left        | ^
    left        &&
    left        ||
    nonassoc    ..  ...
    right       ?:
    right       = += -= *= etc.
    left        , =>
    nonassoc    list operators (rightward)
    right       not
    left        and
    left        or xor
    左結合      項  リスト演算子 (左方向に対して)
    左結合      ->
    非結合      ++ --
    右結合      **
    右結合      ! ~ \ 単項の+ 単項の-
    左結合      =~ !~
    左結合      * / % x
    左結合      + - .
    左結合      << >>
    非結合      名前付き単項演算子
    非結合      < > <= >= lt gt le ge
    非結合      == != <=> eq ne cmp
    左結合      &
    左結合      | ^
    左結合      &&
    左結合      ||
    非結合      .. ...
    右結合      ?:
    右結合      = += -= *= などの代入演算子
    左結合      , =>
    非結合      リスト演算子 (右方向に対して)
    右結合      not
    左結合      and
    左結合      or xor

In the following sections, these operators are covered in precedence order.

以下の節では、これらの演算子を優先順位に従って紹介します。

Many operators can be overloaded for objects. See overload.

多くの演算子はオブジェクトでオーバーロードできます。 overload を参照して下さい。

説明

項とリスト演算子 (左方向)

A TERM has the highest precedence in Perl. They include variables, quote and quote-like operators, any expression in parentheses, and any function whose arguments are parenthesized. Actually, there aren't really functions in this sense, just list operators and unary operators behaving as functions because you put parentheses around the arguments. These are all documented in perlfunc.

「項」は Perl でもっとも優先順位が高いものです。 これには、変数、クォートとクォート的な演算子、括弧で括った任意の式、 引数を括弧で括った任意の関数が含まれます。 実際には、この意味では本当の関数はなく、リスト演算子と関数のように働く 単項演算子が、引数を括弧で括るためそのように見えます。 これらはすべて perlfunc に記述しています。

If any list operator (print(), etc.) or any unary operator (chdir(), etc.) is followed by a left parenthesis as the next token, the operator and arguments within parentheses are taken to be of highest precedence, just like a normal function call.

もし、リスト演算子 (print() など) や単項演算子 (chdir() など)の 名前の後に開き括弧が続く場合には、その演算子と括弧内の引数は、 通常の関数呼び出しのように、もっとも高い優先順位で処理されます。

In the absence of parentheses, the precedence of list operators such as print, sort, or chmod is either very high or very low depending on whether you are looking at the left side or the right side of the operator. For example, in

括弧が無い場合には、printsortchmod のようなリスト演算子の 優先順位は、演算子の左側をからすると非常に高く、右側からすると 非常に低く見えます。たとえば、

    @ary = (1, 3, sort 4, 2);
    print @ary;         # prints 1324

the commas on the right of the sort are evaluated before the sort, but the commas on the left are evaluated after. In other words, list operators tend to gobble up all arguments that follow, and then act like a simple TERM with regard to the preceding expression. Be careful with parentheses:

では、sort の右のコンマは sort よりも前に評価されます (右側から 見ると sort の優先順位が低い) が、左側のコンマは sort のあとに 評価されます (左側から見ると sort の方が優先順位が高く なっている)。 言い方を変えると、リスト演算子は自分の後にある引数をすべて使って処理を行ない、 その結果を自分の前の式に対する「項」であるかのように見せるということです。 ただし、括弧には気を付けないといけません:

    # These evaluate exit before doing the print:
    print($foo, exit);  # Obviously not what you want.
    print $foo, exit;   # Nor is this.

    # These do the print before evaluating exit:
    (print $foo), exit; # This is what you want.
    print($foo), exit;  # Or this.
    print ($foo), exit; # Or even this.
    # 以下は print を行なう前に exit を評価します:
    print($foo, exit);  # 明らかにやりたいことではないでしょう。
    print $foo, exit;   # これでもない。

    # 以下は exit を評価する前に print を行ないます:
    (print $foo), exit; # これがしたかった。
    print($foo), exit;  # これでもいい。
    print ($foo), exit; # これも OK。

Also note that

    print ($foo & 255) + 1, "\n";

probably doesn't do what you expect at first glance. See "Named Unary Operators" for more discussion of this.

また、

    print ($foo & 255) + 1, "\n";

の動作を一目見ただけで判断するのは、難しいでしょう。 詳しくは、"Named Unary Operators" を参照してください。

Also parsed as terms are the do {} and eval {} constructs, as well as subroutine and method calls, and the anonymous constructors [] and {}.

この他に「項」として解析されるものには、do {}eval {} の 構成、サブルーティンやメソッドの呼び出し、無名のコンストラクタ []{} があります。

See also "Quote and Quote-like Operators" toward the end of this section, as well as "O Operators"" in "I.

後の方の"Quote and Quote-like Operators""O Operators"" in "Iも参照してください。

矢印演算子

"->" is an infix dereference operator, just as it is in C and C++. If the right side is either a [...], {...}, or a (...) subscript, then the left side must be either a hard or symbolic reference to an array, a hash, or a subroutine respectively. (Or technically speaking, a location capable of holding a hard reference, if it's an array or hash reference being used for assignment.) See perlreftut and perlref.

C や C++ と同じように "->" は中置の被参照演算子です。 右側が [...], {...}, (...) のいずれかの形の添字であれば、左側は配列、ハッシュ、 サブルーチンへのハードリファレンスかシンボリックリファレンス (あるいは 技術的には、配列またはハードリファレンスが代入可能であれば ハードリファレンスを保持できる場所) でなければなりません。perlreftutperlref を参照してください。

Otherwise, the right side is a method name or a simple scalar variable containing either the method name or a subroutine reference, and the left side must be either an object (a blessed reference) or a class name (that is, a package name). See perlobj.

そうでなければ、右側はメソッド名かサブルーチンのリファレンスを持った 単純スカラ変数で、左側はオブジェクト (bless されたリファレンス) か クラス名でなければなりません。 perlobj を参照してください。

インクリメントとデクリメント

"++" and "--" work as in C. That is, if placed before a variable, they increment or decrement the variable before returning the value, and if placed after, increment or decrement the variable after returning the value.

"++" と "--" は、C の場合と同じように動作します。 つまり、変数の前に置かれれば、値を返す前に変数をインクリメントまたは デクリメントし、後に置かれれば、値を返した後で変数を インクリメントまたはデクリメントします。

The auto-increment operator has a little extra builtin magic to it. If you increment a variable that is numeric, or that has ever been used in a numeric context, you get a normal increment. If, however, the variable has been used in only string contexts since it was set, and has a value that is not the empty string and matches the pattern /^[a-zA-Z]*[0-9]*\z/, the increment is done as a string, preserving each character within its range, with carry:

インクリメント演算子には、ちょっと風変わりな機能が組み込まれています。 数値が入った変数や、数値の文脈で使われてきた変数を インクリメントする場合には、通常のインクリメントとして動作します。 しかし、その変数が設定されてからずっと文字列の文脈で しか使われていなくて、空文字列でなく、 /^[a-zA-Z]*[0-9]*\z/ にマッチする 値を持っているときには、個々の文字の範囲を保ちながら桁あげを行なって、 文字列としてインクリメントが行なわれます (マジカルインクリメントと呼ばれます):

    print ++($foo = '99');      # prints '100'
    print ++($foo = 'a0');      # prints 'a1'
    print ++($foo = 'Az');      # prints 'Ba'
    print ++($foo = 'zz');      # prints 'aaa'

The auto-decrement operator is not magical.

デクリメント演算子には、マジカルなものはありません。

指数演算子

Binary "**" is the exponentiation operator. It binds even more tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is implemented using C's pow(3) function, which actually works on doubles internally.)

二項演算子の "**" は指数演算子です。 この演算子は、単項のマイナスよりも結合が強い演算子で、 -2**4 は (-2)**4 ではなく、-(2**4) と解釈されます。 (これは C の pow(3) を使って実装されていますので、 内部的には double で動作します。)

単項演算子

Unary "!" performs logical negation, i.e., "not". See also not for a lower precedence version of this.

単項演算子の "!" は論理否定を行ないます。 つまり 「not」 ということです。 この演算子の優先順位を低くしたものとして、not が用意されています。

Unary "-" performs arithmetic negation if the operand is numeric. If the operand is an identifier, a string consisting of a minus sign concatenated with the identifier is returned. Otherwise, if the string starts with a plus or minus, a string starting with the opposite sign is returned. One effect of these rules is that -bareword is equivalent to "-bareword".

単項演算子の "-" は被演算子が数値であれば、算術否定を行ないます。 被演算子が識別子ならば、マイナス記号にその識別子をつなげた 文字列が返されます。 これ以外で被演算子の最初の文字がプラスかマイナスのときには、 その記号を逆のものに置き換えた文字列を返します。 この規則の結果、-bareword"-bareword" に等価となります。

Unary "~" performs bitwise negation, i.e., 1's complement. For example, 0666 & ~027 is 0640. (See also "Integer Arithmetic" and "Bitwise String Operators".) Note that the width of the result is platform-dependent: ~0 is 32 bits wide on a 32-bit platform, but 64 bits wide on a 64-bit platform, so if you are expecting a certain bit width, remember use the & operator to mask off the excess bits.

単項演算子の "~" はビットごとの否定を行ないます。 つまり、1 の補数を返します。 例えば、0666 & ~027 は 0640 です。 ("Integer Arithmetic""Bitwise String Operators" も参照して下さい。) 結果の幅はプラットホーム依存であることに注意してください。 ~0 は 32-bit プラットホームでは 32 ビット幅ですが、 64-bit プラットホームでは 64 ビット幅ですので、 特定のビット幅を仮定する場合は、 余分なビットをマスクするために & 演算子を使うことを忘れないでください。

Unary "+" has no effect whatsoever, even on strings. It is useful syntactically for separating a function name from a parenthesized expression that would otherwise be interpreted as the complete list of function arguments. (See examples above under Terms and List Operators (Leftward).)

単項演算子の "+" は、たとえ文字列に対して用いられた場合にも、何もしません。 関数名に続けて括弧付きの式を書く場合に、関数の引数リストと 解釈されないようにするために用いることができます。 (下記 Terms and List Operators (Leftward) の例を参照してください。)

Unary "\" creates a reference to whatever follows it. See perlreftut and perlref. Do not confuse this behavior with the behavior of backslash within a string, although both forms do convey the notion of protecting the next thing from interpolation.

単項演算子の "\" はその後に続くものへのリファレンスを生成します。 perlreftutperlref を参照してください。 この用法も文字列中のバックスラッシュも、後に続くものが展開されるのを 防ぐことになりますが、動作を混同しないでください。

拘束演算子

Binary "=~" binds a scalar expression to a pattern match. Certain operations search or modify the string $_ by default. This operator makes that kind of operation work on some other string. The right argument is a search pattern, substitution, or transliteration. The left argument is what is supposed to be searched, substituted, or transliterated instead of the default $_. When used in scalar context, the return value generally indicates the success of the operation. Behavior in list context depends on the particular operator. See "Regexp Quote-Like Operators" for details.

二項演算子の "=~" は、スカラ式をパターンマッチに拘束します。 デフォルトで $_ の文字列を検索したり、変更したりする演算があります。 この演算子は、そのような演算を他の文字列に対して行なわせるようにするものです。 右引数は、検索パターン、置換、文字変換のいずれかです。 左引数は、デフォルトの $_ の代わりに検索、置換、文字変換の対象となるものです。 スカラコンテキストで使うと、返り値は一般的に演算の結果が成功したか否かです。 リストコンテキストでの振る舞いは演算子に依存します。 詳しくは "Regexp Quote-Like Operators" を参照して下さい。

If the right argument is an expression rather than a search pattern, substitution, or transliteration, it is interpreted as a search pattern at run time. This can be less efficient than an explicit search, because the pattern must be compiled every time the expression is evaluated.

右引数が検索パターン、置換、文字変換ではなく、式であれば、 それは実行時に決まる検索パターンと解釈されます。 明示的な検索に比べて効率が落ちるかもしれません。 式が評価されるたびにパターンをコンパイルする必要があるからです。

Binary "!~" is just like "=~" except the return value is negated in the logical sense.

二項演算子の "!~" は、返される値が論理否定されることを除いて "=~" と同じです。

乗法演算子

Binary "*" multiplies two numbers.

二項演算子の "*" は 2 つの数値の積を返します。

Binary "/" divides two numbers.

二項演算子の "/" は 2 つの数値の商を返します。

Binary "%" computes the modulus of two numbers. Given integer operands $a and $b: If $b is positive, then $a % $b is $a minus the largest multiple of $b that is not greater than $a. If $b is negative, then $a % $b is $a minus the smallest multiple of $b that is not less than $a (i.e. the result will be less than or equal to zero). Note than when use integer is in scope, "%" gives you direct access to the modulus operator as implemented by your C compiler. This operator is not as well defined for negative operands, but it will execute faster.

二項演算子の "%" は 2 つの数値の剰余を返します。 $a$b の二つの整数の被演算子を取ります。 $b が正の場合、$a % $b は、$a から $a を超えない 最大の $b の倍数を引いた値です。 $b が負の場合、$a % $b は、$a から $a を下回らない 最小の $b の倍数を引いた値です。(従って結果はゼロ以下になります。) use integer がスコープ内にある場合、 "%" は C コンパイラで実装された剰余演算子を使います。 この演算子は被演算子が負の場合の挙動が不確実ですが、 より高速です。

Binary "x" is the repetition operator. In scalar context or if the left operand is not enclosed in parentheses, it returns a string consisting of the left operand repeated the number of times specified by the right operand. In list context, if the left operand is enclosed in parentheses, it repeats the list.

二項演算子の "x" は繰り返し演算子です。 スカラコンテキストまたは左辺値が括弧で括られていない場合は、 左被演算子を右被演算子に示す数だけ繰り返したもので構成される 文字列を返します。 リストコンテキストでは、左被演算子が括弧で括られていれば、 リストを繰り返します。

    print '-' x 80;             # print row of dashes

    print "\t" x ($tab/8), ' ' x ($tab%8);      # tab over

    @ones = (1) x 80;           # a list of 80 1's
    @ones = (5) x @ones;        # set all elements to 5

加法演算子

Binary "+" returns the sum of two numbers.

二項演算子の "+" は 2 つの数値の和を返します。

Binary "-" returns the difference of two numbers.

二項演算子の "-" は 2 つの数値の差を返します。

Binary "." concatenates two strings.

二項演算子の "." は 2 つの文字列を連結します。

シフト演算子

Binary "<<" returns the value of its left argument shifted left by the number of bits specified by the right argument. Arguments should be integers. (See also "Integer Arithmetic".)

二項演算子の "<<" は左引数の値を、右引数で示すビット数だけ、 左にシフトした値を返します。 引数は整数でなければなりません。 ("Integer Arithmetic" も参照して下さい。)

Binary ">>" returns the value of its left argument shifted right by the number of bits specified by the right argument. Arguments should be integers. (See also "Integer Arithmetic".)

二項演算子の ">>" は左引数の値を、右引数で示すビット数だけ、 右にシフトした値を返します。 引数は整数でなければなりません。 ("Integer Arithmetic" も参照して下さい。)

名前付き単項演算子

The various named unary operators are treated as functions with one argument, with optional parentheses. These include the filetest operators, like -f, -M, etc. See perlfunc.

さまざまな名前付き単項演算子が、引数を 1 つ持ち、括弧が省略可能な、 関数として扱われます。 これには -f-M のようなファイルテスト演算子も含まれます。 perlfunc を参照してください。

If any list operator (print(), etc.) or any unary operator (chdir(), etc.) is followed by a left parenthesis as the next token, the operator and arguments within parentheses are taken to be of highest precedence, just like a normal function call. For example, because named unary operators are higher precedence than ||:

リスト演算子 (print() など) や単項演算子 (chdir() など) は、 すべて次のトークンとして開き括弧が続くと、その演算子と括弧内の引数は、 通常の関数呼び出しのようにもっとも高い優先順位として扱われます。 たとえば、名前つき単項演算子は || より優先順位が高いので、 以下のようになります:

    chdir $foo    || die;       # (chdir $foo) || die
    chdir($foo)   || die;       # (chdir $foo) || die
    chdir ($foo)  || die;       # (chdir $foo) || die
    chdir +($foo) || die;       # (chdir $foo) || die

but, because * is higher precedence than named operators:

しかし * は名前つき演算子より優先順位が高いので、以下のようになります:

    chdir $foo * 20;    # chdir ($foo * 20)
    chdir($foo) * 20;   # (chdir $foo) * 20
    chdir ($foo) * 20;  # (chdir $foo) * 20
    chdir +($foo) * 20; # chdir ($foo * 20)

    rand 10 * 20;       # rand (10 * 20)
    rand(10) * 20;      # (rand 10) * 20
    rand (10) * 20;     # (rand 10) * 20
    rand +(10) * 20;    # rand (10 * 20)

"Terms and List Operators (Leftward)" も参照して下さい。

比較演算子

Binary "<" returns true if the left argument is numerically less than the right argument.

二項演算子の "<" は左引数が数値的に右引数よりも小さければ、 真を返します。

Binary ">" returns true if the left argument is numerically greater than the right argument.

二項演算子の ">" は左引数が数値的に右引数よりも大きければ、 真を返します。

Binary "<=" returns true if the left argument is numerically less than or equal to the right argument.

二項演算子の "<=" は左引数が数値的に右引数よりも小さいか等しければ、 真を返します。

Binary ">=" returns true if the left argument is numerically greater than or equal to the right argument.

二項演算子の ">=" は左引数が数値的に右引数よりも大きいか等しければ、 真を返します。

Binary "lt" returns true if the left argument is stringwise less than the right argument.

二項演算子の "lt" は左引数が文字列的に右引数よりも小さければ、 真を返します。

Binary "gt" returns true if the left argument is stringwise greater than the right argument.

二項演算子の "gt" は左引数が文字列的に右引数よりも大きければ、 真を返します。

Binary "le" returns true if the left argument is stringwise less than or equal to the right argument.

二項演算子の "le" は左引数が文字列的に右引数よりも小さいか等しければ、 真を返します。

Binary "ge" returns true if the left argument is stringwise greater than or equal to the right argument.

二項演算子の "ge" は左引数が文字列的に右引数よりも大きいか等しければ、 真を返します。

等価演算子

Binary "==" returns true if the left argument is numerically equal to the right argument.

二項演算子の "==" は左引数が数値的に右引数と等しければ、 真を返します。

Binary "!=" returns true if the left argument is numerically not equal to the right argument.

二項演算子の "!=" は左引数が数値的に右引数と等しくなければ、 真を返します。

Binary "<=>" returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument. If your platform supports NaNs (not-a-numbers) as numeric values, using them with "<=>" returns undef. NaN is not "<", "==", ">", "<=" or ">=" anything (even NaN), so those 5 return false. NaN != NaN returns true, as does NaN != anything else. If your platform doesn't support NaNs then NaN is just a string with numeric value 0.

二項演算子の "<=>" は左引数が数値的に右引数より小さいか、等しいか、 大きいかに従って、-1, 0, 1 を返します。 数値として NaN (非数) に対応しているプラットフォームでは、 NaN に対して "<=>" を使うと undef を返します。 NaN はどの値に対しても(NaN に対してでさえも) "<", "==", ">", "<=", ">=" のいずれも成立しないので、これらは全て偽となります。 NaN != NaN は真を返しますが、その他のどの値に対しても != は偽を返します。 NaN に対応していないプラットフォームでは、NaN は 単に数としての値 0 を持つ文字列です。

    perl -le '$a = NaN; print "No NaN support here" if $a == $a'
    perl -le '$a = NaN; print "NaN support here" if $a != $a'

Binary "eq" returns true if the left argument is stringwise equal to the right argument.

二項演算子の "eq" は左引数が文字列的に右引数と等しければ、 真を返します。

Binary "ne" returns true if the left argument is stringwise not equal to the right argument.

二項演算子の "ne" は左引数が文字列的に右引数と等しくなければ、 真を返します。

Binary "cmp" returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument.

二項演算子の "cmp" は左引数が文字列的に右引数より小さいか、 等しいか、大きいかに従って、-1, 0, 1 を返します。

"lt", "le", "ge", "gt" and "cmp" use the collation (sort) order specified by the current locale if use locale is in effect. See perllocale.

"lt", "le", "ge", "gt", "cmp" は use locale が有効な場合は 現在のロケールで指定された辞書(ソート)順が使われます。 perllocale を参照して下さい。

ビットごとの AND

Binary "&" returns its operators ANDed together bit by bit. (See also "Integer Arithmetic" and "Bitwise String Operators".)

二項演算子の "&" は、両被演算子のビットごとに論理積をとって、 その結果を返します。 ("Integer Arithmetic""Bitwise String Operators" も参照して下さい。)

ビットごとの OR と XOR

Binary "|" returns its operators ORed together bit by bit. (See also "Integer Arithmetic" and "Bitwise String Operators".)

二項演算子の "|" は、両被演算子のビットごとに論理和をとって、 その結果を返します。 ("Integer Arithmetic""Bitwise String Operators" も参照して下さい。)

Binary "^" returns its operators XORed together bit by bit. (See also "Integer Arithmetic" and "Bitwise String Operators".)

二項演算子の "^" は、両被演算子のビットごとに排他論理和をとって、 その結果を返します。 ("Integer Arithmetic""Bitwise String Operators" も参照して下さい。)

C スタイルの論理積

Binary "&&" performs a short-circuit logical AND operation. That is, if the left operand is false, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it is evaluated.

二項演算子の "&&" は、短絡の論理積演算を行ないます。 つまり、左被演算子が偽であれば、右被演算子は評価さえ 行なわれないということです。 評価される場合には、スカラーかリストかというコンテキストは、 右被演算子にも及びます。

C スタイルの論理和

Binary "||" performs a short-circuit logical OR operation. That is, if the left operand is true, the right operand is not even evaluated. Scalar or list context propagates down to the right operand if it is evaluated.

二項演算子の "||" は、短絡の論理和演算を行ないます。 つまり、左被演算子が真であれば、右被演算子は評価さえ 行なわれないということです。 評価される場合には、スカラーかリストかというコンテキストは、 右被演算子にも及びます。

The || and && operators differ from C's in that, rather than returning 0 or 1, they return the last value evaluated. Thus, a reasonably portable way to find out the home directory (assuming it's not "0") might be:

|| 演算子と && 演算子は、単に 0 や 1 を返すのではなく、最後に評価された値を 返すという点において、C と違っています。 これにより、かなり一般的に使えるホームディレクトリ ("0" でないとして) を 探す方法は:

    $home = $ENV{'HOME'} || $ENV{'LOGDIR'} ||
        (getpwuid($<))[7] || die "You're homeless!\n";

In particular, this means that you shouldn't use this for selecting between two aggregates for assignment:

特に、これは代入のために二つの集合を選択するためには 使うべきではないことを意味します。

    @a = @b || @c;              # this is wrong
    @a = scalar(@b) || @c;      # really meant this
    @a = @b ? @b : @c;          # this works fine, though

As more readable alternatives to && and || when used for control flow, Perl provides and and or operators (see below). The short-circuit behavior is identical. The precedence of "and" and "or" is much lower, however, so that you can safely use them after a list operator without the need for parentheses:

Perl では、フロー制御に使う場合の多少読みやすい &&|| の同義語として、 and 演算子と or 演算子が用意されています (下記参照)。 短絡の動作は全く同じです。 しかし、"and" と "or" の優先順位はかなり低くしてあるので、 引数に括弧を使っていないリスト演算子のあとに続けて使う場合にも、 安心して使うことができます:

    unlink "alpha", "beta", "gamma"
            or gripe(), next LINE;

With the C-style operators that would have been written like this:

C スタイルの演算子では以下のように書く必要があります。

    unlink("alpha", "beta", "gamma")
            || (gripe(), next LINE);

Using "or" for assignment is unlikely to do what you want; see below.

代入で "or" を使うと、したいことと違うことになります。 以下を参照して下さい。

範囲演算子

Binary ".." is the range operator, which is really two different operators depending on the context. In list context, it returns an array of values counting (up by ones) from the left value to the right value. If the left value is greater than the right value then it returns the empty array. The range operator is useful for writing foreach (1..10) loops and for doing slice operations on arrays. In the current implementation, no temporary array is created when the range operator is used as the expression in foreach loops, but older versions of Perl might burn a lot of memory when you write something like this:

二項演算子の ".." は範囲演算子で、使われるコンテキストによって 異なる動作をする 2 つの演算子を合わせたものです。 リストコンテキストでは、左の値から右の値まで (1 づつ昇順で) 数えあげた値から なる配列を返します。 左側の値が右側の値より大きい場合は、空配列を返します。 範囲演算子は、foreach (1..10) のようなループを書くときや、 配列のスライス演算を行なうときに便利です。 現状の実装では、foreach ループの式の中で範囲演算子を使っても 一時配列は作りませんが、古い Perl は以下のようなことを書くと、 大量のメモリを消費することになります:

    for (1 .. 1_000_000) {
        # code
    }

In scalar context, ".." returns a boolean value. The operator is bistable, like a flip-flop, and emulates the line-range (comma) operator of sed, awk, and various editors. Each ".." operator maintains its own boolean state. It is false as long as its left operand is false. Once the left operand is true, the range operator stays true until the right operand is true, AFTER which the range operator becomes false again. It doesn't become false till the next time the range operator is evaluated. It can test the right operand and become false on the same evaluation it became true (as in awk), but it still returns true once. If you don't want it to test the right operand till the next evaluation, as in sed, just use three dots ("...") instead of two. In all other regards, "..." behaves just like ".." does.

スカラコンテキストで使われたときには、".." は真偽値を返します。 この演算子は、フリップフロップのように 2 値安定で、 sedawk や多くのエディタでの行範囲 (コンマ) 演算子を エミュレートするものとなります。 各々の ".." 演算子がそれぞれに独立して自分の真偽状態を管理します。 はじめは、左被演算子が偽である間、演算全体も偽となっています。 範囲演算子は、いったん左被演算子が真になると、右被演算子が真である間、 真を返すようになります。 右被演算子が偽になると、演算子も偽を返すようになります。 (次に範囲演算子が評価されるまでは、偽とはなりません。 (awk でのように) 真となった、その評価の中で右被演算子をテストし、 偽とすることができますが、1 度は真を返すことになります。 sed でのように、次に評価されるまで右被演算子をテストしたくなければ、 2 個のドットの代わりに 3 つのドット ("...") を使ってください。 その他の点では、"..." は ".." と同様に振舞います.

The right operand is not evaluated while the operator is in the "false" state, and the left operand is not evaluated while the operator is in the "true" state. The precedence is a little lower than || and &&. The value returned is either the empty string for false, or a sequence number (beginning with 1) for true. The sequence number is reset for each range encountered. The final sequence number in a range has the string "E0" appended to it, which doesn't affect its numeric value, but gives you something to search for if you want to exclude the endpoint. You can exclude the beginning point by waiting for the sequence number to be greater than 1. If either operand of scalar ".." is a constant expression, that operand is implicitly compared to the $. variable, the current line number. Examples:

右被演算子は、演算子の状態が「偽」である間は評価されることがなく、 左被演算子は、演算子の状態が「真」である間は評価されることがありません。 優先順位は、|| と && の少し下です。 偽としては空文字列が返され、 真としては (1 から始まる) 順に並んだ数値が返されます。 この通し番号は、新たに範囲が始まるごとにリセットされます。 範囲の最後の数字には、文字列 "E0" がお尻につけられます。 これは、数値としては何の影響もありませんが、範囲の終わりで何か特別なことを したい場合に、目印として使うことができます。 範囲の始まりで何かしたい場合には、通し番号が 1 よりも大きくなるのを 待っていればよいでしょう。 スカラの ".." の被演算子が定数表現であるときは、その被演算子は暗黙に、 変数 $. と比較されることになります。例:

As a scalar operator:

スカラー演算子として:

    if (101 .. 200) { print; }  # print 2nd hundred lines
    next line if (1 .. /^$/);   # skip header lines
    s/^/> / if (/^$/ .. eof()); # quote body

    # parse mail messages
    while (<>) {
        $in_header =   1  .. /^$/;
        $in_body   = /^$/ .. eof();
        # do something based on those
    } continue {
        close ARGV if eof;              # reset $. each file
    }

As a list operator:

リスト演算子として:

    for (101 .. 200) { print; } # print $_ 100 times
    @foo = @foo[0 .. $#foo];    # an expensive no-op
    @foo = @foo[$#foo-4 .. $#foo];      # slice last 5 items

The range operator (in list context) makes use of the magical auto-increment algorithm if the operands are strings. You can say

(リストコンテキストでの) 範囲演算子は、被演算子が文字列であるときには、 マジカルインクリメントの機能を使います。 大文字すべての配列を得るのに

    @alphabet = ('A' .. 'Z');

to get all normal letters of the alphabet, or

と書けますし、

    $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];

to get a hexadecimal digit, or

と書けば、16 進の数字が得られますし、

    @z2 = ('01' .. '31');  print $z2[$mday];

to get dates with leading zeros. If the final value specified is not in the sequence that the magical increment would produce, the sequence goes until the next value would be longer than the final value specified.

とすれば、0 付きの日付が得られます。 マジカルインクリメントによって得られる値の中に指定した最終値に ちょうど一致するものが見つからないような場合には、 マジカルインクリメントによって得られる次の値の文字列長が、 最終値として指定した値のものより長くなるまでインクリメントが続けられます。

条件演算子

Ternary "?:" is the conditional operator, just as in C. It works much like an if-then-else. If the argument before the ? is true, the argument before the : is returned, otherwise the argument after the : is returned. For example:

三項演算子の "?:" は、C の場合と同じ条件演算子です。 これは、if-then-else のように働きます。 "?" の前の引数が真であれば ":" の前の引数が返されますが、 真でなければ、":" の後の引数が返されます。例:

    printf "I have %d dog%s.\n", $n,
            ($n == 1) ? '' : "s";

Scalar or list context propagates downward into the 2nd or 3rd argument, whichever is selected.

スカラコンテキストかリストコンテキストかという状況は、 選択された 2 番目もしくは 3 番目の引数にまで伝わります。

    $a = $ok ? $b : $c;  # get a scalar
    @a = $ok ? @b : @c;  # get an array
    $a = $ok ? @b : @c;  # oops, that's just a count!

The operator may be assigned to if both the 2nd and 3rd arguments are legal lvalues (meaning that you can assign to them):

2 番目と 3 番目の引数双方が左辺値 (代入可能ということ)であれば、 この演算子に代入を行なうこともできます:

    ($a_or_b ? $a : $b) = $c;

Because this operator produces an assignable result, using assignments without parentheses will get you in trouble. For example, this:

この演算子は代入可能な結果を生み出すので、 括弧なしで代入を行うとおかしくなるかもしれません。例えば:

    $a % 2 ? $a += 10 : $a += 2

Really means this:

は以下を意味し:

    (($a % 2) ? ($a += 10) : $a) += 2

Rather than this:

以下のようにはなりません:

    ($a % 2) ? ($a += 10) : ($a += 2)

That should probably be written more simply as:

恐らく以下のようにもっと単純に書くべきでしょう:

    $a += ($a % 2) ? 10 : 2;

代入演算子

"=" is the ordinary assignment operator.

"=" は通常の代入演算子です。

Assignment operators work as in C. That is,

代入演算子は C の場合と同様の働きをします。つまり、

    $a += 2;

is equivalent to

は以下と等価です。

    $a = $a + 2;

although without duplicating any side effects that dereferencing the lvalue might trigger, such as from tie(). Other assignment operators work similarly. The following are recognized:

しかし、tie() のようなもので起こる左辺値の被参照による 副作用が 2 回起こることはありません。 他の代入演算も同様に働きます。以下のものが認識されます:

    **=    +=    *=    &=    <<=    &&=
           -=    /=    |=    >>=    ||=
           .=    %=    ^=
                 x=

Although these are grouped by family, they all have the precedence of assignment.

グループ分けしてありますが、これらはいずれも代入演算子として 同じ優先順位となっています。

Unlike in C, the scalar assignment operator produces a valid lvalue. Modifying an assignment is equivalent to doing the assignment and then modifying the variable that was assigned to. This is useful for modifying a copy of something, like this:

C と違って、スカラ代入演算子は有効な左辺値を作り出します。 代入を修正することは、代入を行なってから、その代入された変数を修正するのと 同じことになります。 これは、以下のように何かのコピーを変更したいときに便利です:

    ($tmp = $global) =~ tr [A-Z] [a-z];

Likewise,

同様に、

    ($a += 2) *= 3;

is equivalent to

は以下と同等です。

    $a += 2;
    $a *= 3;

Similarly, a list assignment in list context produces the list of lvalues assigned to, and a list assignment in scalar context returns the number of elements produced by the expression on the right hand side of the assignment.

同様に、リストコンテキストでのリストへの代入は代入可能な左辺値のリストとなり、 スカラコンテキストでのリストへの代入は代入の右側の式で作成された 要素の数を返します。

コンマ演算子

Binary "," is the comma operator. In scalar context it evaluates its left argument, throws that value away, then evaluates its right argument and returns that value. This is just like C's comma operator.

二項演算子の "," はコンマ演算子です。 スカラコンテキストではその左引数を評価し、その値を捨てて、 それから右引数を評価し、その値を返します。 これはちょうど、C のコンマ演算子と同じです。

In list context, it's just the list argument separator, and inserts both its arguments into the list.

リストコンテキストでは、これは単にリスト引数の区切り文字で、 双方の引数をそのリストに挿入する働きがあります。

The => digraph is mostly just a synonym for the comma operator. It's useful for documenting arguments that come in pairs. As of release 5.001, it also forces any word to the left of it to be interpreted as a string.

記号 => は単にコンマ演算子の同義語です。 これはペアで扱われる引数を記述するのに便利です。 5.001 以降では、左辺値の単語を必ず文字列として扱うという効果もあります。

リスト演算子 (右方向)

On the right side of a list operator, it has very low precedence, such that it controls all comma-separated expressions found there. The only operators with lower precedence are the logical operators "and", "or", and "not", which may be used to evaluate calls to list operators without the need for extra parentheses:

リスト演算子の右側のものにとって、リスト演算子はとても低い優先順位になります。 これによってコンマで区切った式をリスト演算子の引数として 置くことができます。 これよりも優先順位が低いものは、論理演算子の "and", "or", "not" のみで、 余分な括弧を付けないリスト演算子の呼び出しを評価するために使うことができます:

    open HANDLE, "filename"
        or die "Can't open: $!\n";

See also discussion of list operators in Terms and List Operators (Leftward).

Terms and List Operators (Leftward) のリスト演算子の議論も参照して下さい。

論理否定

Unary "not" returns the logical negation of the expression to its right. It's the equivalent of "!" except for the very low precedence.

単項演算子の "not" は右側に来る式の否定を返します。 これは、優先順位がずっと低いことを除いては "!" と等価です。

論理積

Binary "and" returns the logical conjunction of the two surrounding expressions. It's equivalent to && except for the very low precedence. This means that it short-circuits: i.e., the right expression is evaluated only if the left expression is true.

二項演算子の "and" は両側の式の論理積を返します。 これは、優先順位がずっと低いことを除けば && と等価です。 つまり、これも短絡演算を行ない、右側の式は左側の式が 「真」であった場合にのみ評価されます。

論理和と排他論理和

Binary "or" returns the logical disjunction of the two surrounding expressions. It's equivalent to || except for the very low precedence. This makes it useful for control flow

二項演算子の "or" は両側の式の論理和を返します。 これは、優先順位がずっと低いことを除いて || と等価です。 これはフローを制御するのに有用です:

    print FH $data              or die "Can't write to FH: $!";

This means that it short-circuits: i.e., the right expression is evaluated only if the left expression is false. Due to its precedence, you should probably avoid using this for assignment, only for control flow.

つまり、これも短絡演算を行ない、右側の式は左側の式が 「偽」であった場合にのみ評価されます。 優先度の関係で、これは代入には使わず、フローの制御のみに使うべきです。

    $a = $b or $c;              # bug: this is wrong
    ($a = $b) or $c;            # really means this
    $a = $b || $c;              # better written this way

However, when it's a list-context assignment and you're trying to use "||" for control flow, you probably need "or" so that the assignment takes higher precedence.

しかし、代入がリストコンテキストの時に "||" をフロー制御に使おうとする場合、 代入により大きな優先順位を持たせるために "or" が必要かもしれません。

    @info = stat($file) || die;     # oops, scalar sense of stat!
    @info = stat($file) or die;     # better, now @info gets its due

Then again, you could always use parentheses.

もちろん、常に括弧をつけてもよいです。

Binary "xor" returns the exclusive-OR of the two surrounding expressions. It cannot short circuit, of course.

二項演算子の "xor" は両側の式の排他論理和を返します。 これはもちろん、短絡ではありません。

Perl にない C の演算子

Here is what C has that Perl doesn't:

C にあって Perl に無いものは以下の通りです:

unary &

Address-of operator. (But see the "\" operator for taking a reference.)

単項 &

アドレス演算子。 ("\" 演算子がリファレンスのために用いられます。)

unary *

Dereference-address operator. (Perl's prefix dereferencing operators are typed: $, @, %, and &.)

単項 *

被アドレス参照演算子。 (Perl の被参照プリフィクス演算子が型づけを行ないます: $, @, %, &。)

(TYPE)

Type-casting operator.

(型)

型のキャスト演算子。

クォートとクォート風の演算子

While we usually think of quotes as literal values, in Perl they function as operators, providing various kinds of interpolating and pattern matching capabilities. Perl provides customary quote characters for these behaviors, but also provides a way for you to choose your quote character for any of them. In the following table, a {} represents any pair of delimiters you choose.

クォートはリテラル値であると考えるのが普通ですが、Perl において、 クォートは演算子として働き、さまざまな展開やパターンマッチの機能を 持っています。 そのような動作をさせるのに、Perl は慣習的にクォート文字を使っていますが、 どの種類のクォートも、自分でクォート文字を選べるようになっています。 以下の表では、{} がその選んだ区切文字のペアを示しています。

    Customary  Generic        Meaning        Interpolates
        ''       q{}          Literal             no
        ""      qq{}          Literal             yes
        ``      qx{}          Command             yes (unless '' is delimiter)
                qw{}         Word list            no
        //       m{}       Pattern match          yes (unless '' is delimiter)
                qr{}          Pattern             yes (unless '' is delimiter)
                 s{}{}      Substitution          yes (unless '' is delimiter)
                tr{}{}    Transliteration         no (but see below)
     通常記法  汎用記法        意味             展開
    =================================================
        ''       q{}         リテラル               不可
        ""      qq{}         リテラル               可
        ``      qx{}         コマンド               可 (''がデリミタでなければ)
                qw{}         単語リスト              不可
        //       m{}      パターンマッチ       可 (''がデリミタでなければ)
                qr{}         パターン               可 (''がデリミタでなければ)
                 s{}{}         置換               可 (''がデリミタでなければ)
                tr{}{}         変換               不可 (但し以下を参照のこと)

Non-bracketing delimiters use the same character fore and aft, but the four sorts of brackets (round, angle, square, curly) will all nest, which means that

選んだ区切文字が括弧の類でない場合には、前後の文字として同一のものを 使いますが、4 つの括弧 ((), <>, [], {}) の場合にはネストできます。 つまり、以下のものは、

        q{foo{bar}baz} 

is the same as

以下と同じです。

        'foo{bar}baz'

Note, however, that this does not always work for quoting Perl code:

しかし、以下のコードはクォートされた Perl コードでは いつも正しく動くわけではないことに注意してください:

        $s = q{ if($a eq "}") ... }; # WRONG

is a syntax error. The Text::Balanced module on CPAN is able to do this properly.

これは文法エラーとなります。 CPAN の Text::Balanced モジュールはこれを適切に行います。

There can be whitespace between the operator and the quoting characters, except when # is being used as the quoting character. q#foo# is parsed as the string foo, while q #foo# is the operator q followed by a comment. Its argument will be taken from the next line. This allows you to write:

演算子とクォート文字の間に空白を置くことも出来ます。 ただし、# をクォート文字として使う場合は例外です。 q#foo# は文字列 foo としてパースされますが、 q #foo#q 演算子の後にコメントがあるとみなされます。 この引数は次の行から取られます。つまり、以下のように書けます:

    s {foo}  # Replace foo
      {bar}  # with bar.

For constructs that do interpolate, variables beginning with "$" or "@" are interpolated, as are the following escape sequences. Within a transliteration, the first eleven of these sequences may be used.

展開が行なわれる構文では、"$" や "@" で始まる変数が、 以下のエスケープシーケンスと同時に展開されます。 文字変換の中では、シーケンスの 11 要素が使われます:

    \t          tab             (HT, TAB)
    \n          newline         (NL)
    \r          return          (CR)
    \f          form feed       (FF)
    \b          backspace       (BS)
    \a          alarm (bell)    (BEL)
    \e          escape          (ESC)
    \033        octal char      (ESC)
    \x1b        hex char        (ESC)
    \x{263a}    wide hex char   (SMILEY)
    \c[         control char    (ESC)
    \N{name}    named char
    \t          タブ
    \n          改行
    \r          復帰
    \f          改ページ
    \b          バックスペース
    \a          アラーム (ベル)
    \e          エスケープ
    \033        8 進数で表した文字
    \x1b        16 進数で表した文字
    \x{263a}    16 進数で表したワイド文字  (SMILEY)
    \c[         コントロール文字
    \N{name}    名前つき文字
    \l          lowercase next char
    \u          uppercase next char
    \L          lowercase till \E
    \U          uppercase till \E
    \E          end case modification
    \Q          quote non-word characters till \E
    \l          次の文字を小文字にする
    \u          次の文字を大文字にする
    \L          \E まで小文字にする
    \U          \E まで大文字にする
    \E          変更の終わり
    \Q          \E まで非単語文字をクォートする

If use locale is in effect, the case map used by \l, \L, \u and \U is taken from the current locale. See perllocale. For documentation of \N{name}, see charnames.

use locale が有効の場合、 \l, \L, \u, \U で使われる大文字小文字テーブルは 現在のロケールのものが使われます。 perllocale を参照して下さい。 \N{name} のドキュメントに関しては、charnames を参照して下さい。

All systems use the virtual "\n" to represent a line terminator, called a "newline". There is no such thing as an unvarying, physical newline character. It is only an illusion that the operating system, device drivers, C libraries, and Perl all conspire to preserve. Not all systems read "\r" as ASCII CR and "\n" as ASCII LF. For example, on a Mac, these are reversed, and on systems without line terminator, printing "\n" may emit no actual data. In general, use "\n" when you mean a "newline" for your system, but use the literal ASCII when you need an exact character. For example, most networking protocols expect and prefer a CR+LF ("\015\012" or "\cM\cJ") for line terminators, and although they often accept just "\012", they seldom tolerate just "\015". If you get in the habit of using "\n" for networking, you may be burned some day.

全てのシステムでは "newline" と呼ばれる行端末子を表現するために 仮想的な "\n" が用いられます。 普遍の、物理的な "newline" 文字と言うものはありません。 オペレーティングシステム、デバイスドライバ、C ライブラリ、 Perl が全て協力して保存しようとすると言うのは単なる幻想です。 全てのシステムで "\r" を ASCII CR として、また "\n" を ASCII LF として読み込むわけではありません。 例えば Mac ではこれらは保存され、行端末子のないシステムでは、 "\n" を print しても実際のデータは何も出力しません。 一般に、システムで "newline" を意味したいときには "\n" を使いますが、 正確な文字が必要な場合はリテラルな ASCII を使います。 例えば、ほとんどのネットワークプロトコルでは行端末子として CR+LF ("\015\012" または "\cM\cJ") を予想し、また好みますが、 しばしば "\012" だけでも許容し、さらに時々は "\015" だけでも認めます。 もしネットワーク関係で "\n" を使う習慣がついていると、 いつか痛い目を見ることになるでしょう。

You cannot include a literal $ or @ within a \Q sequence. An unescaped $ or @ interpolates the corresponding variable, while escaping will cause the literal string \$ to be inserted. You'll need to write something like m/\Quser\E\@\Qhost/.

\Q シーケンスの中にリテラルな $@ を入れることはできません。 エスケープされない $@ は対応する変数に変換されます。 一方、エスケープすると、リテラルな文字列 \$ が挿入されます。 m/\Quser\E\@\Qhost/ などという風に書く必要があります。

Patterns are subject to an additional level of interpretation as a regular expression. This is done as a second pass, after variables are interpolated, so that regular expressions may be incorporated into the pattern from the variables. If this is not what you want, use \Q to interpolate a variable literally.

パターンはさらに、正規表現として展開が行なわれます。 これは、変数が展開された後の 2 回目のパスで行なわれるので、 変数に正規表現を含めておき、パターンの中へ展開することができます。 もし、そうしたくないのであれば、\Q を使うと変数の内容を文字通りに 展開することができます。

Apart from the behavior described above, Perl does not expand multiple levels of interpolation. In particular, contrary to the expectations of shell programmers, back-quotes do NOT interpolate within double quotes, nor do single quotes impede evaluation of variables when used within double quotes.

上記の振る舞いを除けば、Perl は 複数の段階を踏んで展開を行ないません。 特に、シェルのプログラマの期待とは裏腹に、 バッククォートはダブルクォートの中では展開されませんし、シングルクォートが ダブルクォートの中で使われても、変数の展開を妨げることは ありません

正規表現のクォート風の演算子

Here are the quote-like operators that apply to pattern matching and related activities.

以下はパターンマッチングと関連する行動に関するクォート風の演算子です。

?PATTERN?

This is just like the /pattern/ search, except that it matches only once between calls to the reset() operator. This is a useful optimization when you want to see only the first occurrence of something in each file of a set of files, for instance. Only ?? patterns local to the current package are reset.

これは、reset() 演算子を呼び出すごとに 1 度だけしか マッチしないことを除いては /pattern/ による検索と全く同じです。 たとえば、ファイルの集まりの中で個々のファイルについて、 あるものを探すとき、最初の 1 つだけの存在がわかれば良いのであれば、 この機能を使って最適化をはかることができます。 現在のパッケージにローカルとなっている ?? のパターンだけが リセットされます。

    while (<>) {
        if (?^$?) {
                            # blank line between header and body
        }
    } continue {
        reset if eof;       # clear ?? status for next file
    }

This usage is vaguely deprecated, which means it just might possibly be removed in some distant future version of Perl, perhaps somewhere around the year 2168.

この方法は、あまりお勧めしません。 Perl の遠い将来のバージョン(おそらく 2168 年頃)では削除されるかもしれません。

m/PATTERN/cgimosx
/PATTERN/cgimosx

Searches a string for a pattern match, and in scalar context returns true if it succeeds, false if it fails. If no string is specified via the =~ or !~ operator, the $_ string is searched. (The string specified with =~ need not be an lvalue--it may be the result of an expression evaluation, but remember the =~ binds rather tightly.) See also perlre. See perllocale for discussion of additional considerations that apply when use locale is in effect.

Options are:

パターンマッチで文字列検索を行ない、スカラコンテキストでは成功したときは真、 失敗したときは偽を返します。 =~ 演算子か !~ 演算子で検索対象の文字列を示さなかったときには、 $_ の文字列が検索対象となります。 (=~ で指定される文字列は、左辺値である必要はありません。 式を評価した結果でもかまいませんが、=~ の優先順位がいくぶん高いことに 注意してください。) perlre も参照してください。 use locale が有効の場合の議論については perllocale を参照して下さい。

オプションには以下のものがあります。

    c   Do not reset search position on a failed match when /g is in effect.
    g   Match globally, i.e., find all occurrences.
    i   Do case-insensitive pattern matching.
    m   Treat string as multiple lines.
    o   Compile pattern only once.
    s   Treat string as single line.
    x   Use extended regular expressions.
    c   /g が有効なとき、マッチングに失敗しても検索位置をリセットしない
    g   グローバルにマッチ、つまり、すべてを探し出す
    i   大文字、小文字を区別しない
    m   文字列を複数行として扱う
    o   パターンのコンパイルを 1 度だけにする
    s   文字列を単一行として扱う
    x   拡張正規表現を使用する

If "/" is the delimiter then the initial m is optional. With the m you can use any pair of non-alphanumeric, non-whitespace characters as delimiters. This is particularly useful for matching path names that contain "/", to avoid LTS (leaning toothpick syndrome). If "?" is the delimiter, then the match-only-once rule of ?PATTERN? applies. If "'" is the delimiter, no interpolation is performed on the PATTERN.

区切文字が "/" のときには、最初の m は付けても付けなくてもかまいません。 m を付けるときには、英数字でも空白でもない、任意の文字のペアを 区切文字として使うことができます。 これは "/" を含むパス名にパターンパッチを行なうときに便利でしょう。 LTS (楊枝偏執症候群) を避けるためにも。 "'" がデリミタの場合、PATTERN に対する展開は行われません。

PATTERN may contain variables, which will be interpolated (and the pattern recompiled) every time the pattern search is evaluated, except for when the delimiter is a single quote. (Note that $(, $), and $| are not interpolated because they look like end-of-string tests.) If you want such a pattern to be compiled only once, add a /o after the trailing delimiter. This avoids expensive run-time recompilations, and is useful when the value you are interpolating won't change over the life of the script. However, mentioning /o constitutes a promise that you won't change the variables in the pattern. If you change them, Perl won't even notice. See also "STRING/imosx"" in "qr.

PATTERN には、変数が含まれていてもよく、パターンが評価されるごとに、 (デリミタがシングルクォートでない限り) 変数は展開され (パターンが再コンパイルされ) ます。 (変数 $(, $), $| は文字列の終わりを調べるパターンであると 解釈されるので、展開されません。) パターンがコンパイルされるのを 1 度だけにしたい場合には、 終わりの区切文字の後に /o 修飾子を付けます。 これにより、実行時に再コンパイルが頻繁に起こることが避けられ、 展開する値がスクリプトの実行中に変化しない場合に有効なものとなります。 しかし、/o を付けることは、パターンの中の変数を変更しないことを 約束するものです。 変更したとしても、Perl がそれに気付くことはありません。 "STRING/imosx"" in "qr も参照して下さい。

If the PATTERN evaluates to the empty string, the last successfully matched regular expression is used instead.

PATTERN を評価した結果が空文字列となった場合には、 最後にマッチに 成功した 正規表現が、代わりに使われます。

If the /g option is not used, m// in list context returns a list consisting of the subexpressions matched by the parentheses in the pattern, i.e., ($1, $2, $3...). (Note that here $1 etc. are also set, and that this differs from Perl 4's behavior.) When there are no parentheses in the pattern, the return value is the list (1) for success. With or without parentheses, an empty list is returned upon failure.

Examples:

/gオプションが使われなかった場合、リストコンテキストでのm//は パターンの中の括弧で括られた部分列にマッチしたもので構成されるリストを 返します。 これは、($1, $2, $3, ...) ということです。 (この場合、$1 なども設定されます。 この点で Perl 4 の動作と違っています。) パターンに括弧がない場合は、返り値は成功時はリスト (1) です。 括弧のあるなしに関わらず、失敗時は空リストを返します。

例を示します:

    open(TTY, '/dev/tty');
    <TTY> =~ /^y/i && foo();    # do foo if desired

    if (/Version: *([0-9.]*)/) { $version = $1; }

    next if m#^/usr/spool/uucp#;

    # poor man's grep
    $arg = shift;
    while (<>) {
        print if /$arg/o;       # compile only once
    }

    if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))

This last example splits $foo into the first two words and the remainder of the line, and assigns those three fields to $F1, $F2, and $Etc. The conditional is true if any variables were assigned, i.e., if the pattern matched.

最後の例は、$foo を最初の 2 つの単語と行の残りに分解し、 $F1 と $F2 と $Etc に代入しています。 変数に代入されれば、すなわちパターンがマッチすれば、 if の条件が真となります。

The /g modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the regular expression. If there are no parentheses, it returns a list of all the matched strings, as if there were parentheses around the whole pattern.

/g 修飾子は、グローバルなパターンマッチを指定するもので、 文字列の中で可能な限りたくさんマッチを行ないます。 この動作は、コンテキストに依存します。 リストコンテキストでは、正規表現内の括弧付けされたものにマッチした 部分文字列のリストが返されます。 括弧がなければ、パターン全体を括弧で括っていたかのように、 すべてのマッチした文字列のリストが返されます。

In scalar context, each execution of m//g finds the next match, returning true if it matches, and false if there is no further match. The position after the last match can be read or set using the pos() function; see "pos" in perlfunc. A failed match normally resets the search position to the beginning of the string, but you can avoid that by adding the /c modifier (e.g. m//gc). Modifying the target string also resets the search position.

スカラコンテキストでは、m//g を実行する毎に次のマッチを探します。 マッチした場合は真を返し、もうマッチしなくなったら偽を返します。 最後のマッチの位置は pos() 関数で読み出しや設定ができます。 "pos" in perlfunc を参照して下さい。 マッチに失敗すると通常は検索位置を文字列の先頭にリセットしますが、 /c 修飾子をつける(つまり m//gc)ことでこれを防ぐことができます。 ターゲットとなる文字列が変更された場合も検索位置はリセットされます。

You can intermix m//g matches with m/\G.../g, where \G is a zero-width assertion that matches the exact position where the previous m//g, if any, left off. Without the /g modifier, the \G assertion still anchors at pos(), but the match is of course only attempted once. Using \G without /g on a target string that has not previously had a /g match applied to it is the same as using the \A assertion to match the beginning of the string.

Examples:

m//g マッチを m/\G.../g と混ぜることもできます。 \G は前回の m//g があればその同じ位置でマッチする ゼロ文字幅のアサートです。 /g 修飾子なしの場合、\G アサートは pos() に固定しますが、 マッチはもちろん一度だけ試されます。 以前に /g マッチを適用していないターゲット文字列に対して /g なしで \G を使うと、文字列の先頭にマッチする \A アサートを 使うのと同じことになります。

例:

    # list context
    ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);

    # scalar context
    $/ = "";
    while (defined($paragraph = <>)) {
        while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
            $sentences++;
        }
    }
    print "$sentences\n";

    # using m//gc with \G
    $_ = "ppooqppqq";
    while ($i++ < 2) {
        print "1: '";
        print $1 while /(o)/gc; print "', pos=", pos, "\n";
        print "2: '";
        print $1 if /\G(q)/gc;  print "', pos=", pos, "\n";
        print "3: '";
        print $1 while /(p)/gc; print "', pos=", pos, "\n";
    }
    print "Final: '$1', pos=",pos,"\n" if /\G(.)/;

The last example should print:

最後のものは以下のものを表示するはずです:

    1: 'oo', pos=4
    2: 'q', pos=5
    3: 'pp', pos=7
    1: '', pos=7
    2: 'q', pos=8
    3: '', pos=8
    Final: 'q', pos=8

Notice that the final match matched q instead of p, which a match without the \G anchor would have done. Also note that the final match did not update pos -- pos is only updated on a /g match. If the final match did indeed match p, it's a good bet that you're running an older (pre-5.6.0) Perl.

\G なしでのマッチが行われたため、最後のマッチでは p ではなく q がマッチすることに注意してください。 また、最後のマッチは pos を更新しないことに注意してください。 pos/g マッチでのみ更新されます。 もし最後のマッチで p にマッチした場合、かなりの確率で 古い (5.6.0 以前の) Perl で実行しているはずです。

A useful idiom for lex-like scanners is /\G.../gc. You can combine several regexps like this to process a string part-by-part, doing different actions depending on which regexp matched. Each regexp tries to match where the previous one leaves off.

lex 風にスキャンするために便利な指定は /\G.../gc です。 文字列を部分ごとに処理するためにいくつかの正規表現をつなげて、 どの正規表現にマッチしたかによって異なる処理をすることができます。 それぞれの正規表現は前の正規表現が飛ばした部分に対して マッチを試みます。

 $_ = <<'EOL';
      $url = new URI::URL "http://www/";   die if $url eq "xXx";
 EOL
 LOOP:
    {
      print(" digits"),         redo LOOP if /\G\d+\b[,.;]?\s*/gc;
      print(" lowercase"),      redo LOOP if /\G[a-z]+\b[,.;]?\s*/gc;
      print(" UPPERCASE"),      redo LOOP if /\G[A-Z]+\b[,.;]?\s*/gc;
      print(" Capitalized"),    redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/gc;
      print(" MiXeD"),          redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/gc;
      print(" alphanumeric"),   redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/gc;
      print(" line-noise"),     redo LOOP if /\G[^A-Za-z0-9]+/gc;
      print ". That's all!\n";
    }

Here is the output (split into several lines):

出力は以下のようになります(何行かに分割しています):

 line-noise lowercase line-noise lowercase UPPERCASE line-noise
 UPPERCASE line-noise lowercase line-noise lowercase line-noise
 lowercase lowercase line-noise lowercase lowercase line-noise
 MiXeD line-noise. That's all!
q/STRING/
'STRING'

A single-quoted, literal string. A backslash represents a backslash unless followed by the delimiter or another backslash, in which case the delimiter or backslash is interpolated.

シングルクォートされた、リテラル文字列です。 バックスラッシュは、後ろに続くものが区切文字か、別のバックスラッシュで ある場合を除いて単なるバックスラッシュです。 区切文字やバックスラッシュが続く場合には、その区切文字自身もしくは バックスラッシュそのものが展開されます。

    $foo = q!I said, "You said, 'She said it.'"!;
    $bar = q('This is it.');
    $baz = '\n';                # a two-character string
qq/STRING/
"STRING"

A double-quoted, interpolated string.

ダブルクォートされた、リテラル文字列です。

    $_ .= qq
     (*** The previous line contains the naughty word "$1".\n)
                if /\b(tcl|java|python)\b/i;      # :-)
    $baz = "\n";                # a one-character string
qr/STRING/imosx

This operator quotes (and possibly compiles) its STRING as a regular expression. STRING is interpolated the same way as PATTERN in m/PATTERN/. If "'" is used as the delimiter, no interpolation is done. Returns a Perl value which may be used instead of the corresponding /STRING/imosx expression.

For example,

この演算子は STRING を正規表現としてクォートします (そして可能ならコンパイルします)。 STRINGm/PATTERN/ 内の PATTERN と同様に文字変換されます。 "'" がデリミタとして使用された場合、文字変換は行われません。 対応する /STRING/imosx 表現の代わりに使われた Perl の値を返します。

例えば:

    $rex = qr/my.STRING/is;
    s/$rex/foo/;

is equivalent to

は以下と等価です:

    s/my.STRING/foo/is;

The result may be used as a subpattern in a match:

結果はマッチのサブパターンとして使えます:

    $re = qr/$pattern/;
    $string =~ /foo${re}bar/;   # can be interpolated in other patterns
    $string =~ $re;             # or used standalone
    $string =~ /$re/;           # or this way

Since Perl may compile the pattern at the moment of execution of qr() operator, using qr() may have speed advantages in some situations, notably if the result of qr() is used standalone:

Perl は qr() 演算子を実行する瞬間にパターンをコンパイルするので、 qr() を使うことでいくつかの場面で速度的に有利になります。 特に qr() の結果が独立して使われる場合に有利になります。

    sub match {
        my $patterns = shift;
        my @compiled = map qr/$_/i, @$patterns;
        grep {
            my $success = 0;
            foreach my $pat (@compiled) {
                $success = 1, last if /$pat/;
            }
            $success;
        } @_;
    }

Precompilation of the pattern into an internal representation at the moment of qr() avoids a need to recompile the pattern every time a match /$pat/ is attempted. (Perl has many other internal optimizations, but none would be triggered in the above example if we did not use qr() operator.)

Options are:

qr() の時点でパターンを内部表現にプリコンパイルすることにより、 /$pat/ を試みる毎に毎回パターンを再コンパイルするのを避けることができます (Perl はその他にも多くの内部最適化を行いますが、 上の例で qr() 演算子を使わなかった場合はどの最適化も行われません)。

オプションは以下の通りです:

    i   Do case-insensitive pattern matching.
    m   Treat string as multiple lines.
    o   Compile pattern only once.
    s   Treat string as single line.
    x   Use extended regular expressions.
    i   パターンマッチにおいて大文字小文字を区別しない
    m   文字列を複数行として扱う
    o   一度だけコンパイルする
    s   文字列を一行として扱う
    x   拡張正規表現を使う

See perlre for additional information on valid syntax for STRING, and for a detailed look at the semantics of regular expressions.

STRING の有効な文法に関する追加の情報と、正規表現の意味論に関する 詳細については perlre を参照して下さい。

qx/STRING/
`STRING`

A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected. In scalar context, it comes back as a single (potentially multi-line) string, or undef if the command failed. In list context, returns a list of lines (however you've defined lines with $/ or $INPUT_RECORD_SEPARATOR), or an empty list if the command failed.

展開され、/bin/sh またはそれと等価なものでシステムのコマンドとして 実行される(であろう)文字列です。 シェルのワイルドカード、パイプ、リダイレクトが有効です。 そのコマンドの、標準出力を集めたものが返されます。 標準エラーは影響を与えません。 スカラコンテキストでは、(複数行を含むかもしれない) 1 つの文字列が戻ってきます。 コマンドが失敗したときは未定義値を返します。 リストコンテキストでは、($/ もしくは $INPUT_RECORD_SEPARATOR を どのように設定していても) 行のリストを返します。 コマンドが失敗したときは空リストを返します。

Because backticks do not affect standard error, use shell file descriptor syntax (assuming the shell supports this) if you care to address this. To capture a command's STDERR and STDOUT together:

バッククォートは標準エラーには影響を与えないので、 標準エラーを使いたい場合は(シェルが対応しているものとして) シェルのファイル記述子の文法を使ってください。 コマンドの STDERR と STDOUT を共に取得したい場合は:

    $output = `cmd 2>&1`;

To capture a command's STDOUT but discard its STDERR:

コマンドの STDOUT は取得するが STDERR は捨てる場合は:

    $output = `cmd 2>/dev/null`;

To capture a command's STDERR but discard its STDOUT (ordering is important here):

コマンドの STDERR は取得するが STDOUT は捨てる場合は (ここでは順序が重要です):

    $output = `cmd 2>&1 1>/dev/null`;

To exchange a command's STDOUT and STDERR in order to capture the STDERR but leave its STDOUT to come out the old STDERR:

STDERR を取得するが、STDOUT は古い STDERR のために残しておくために STDOUT と STDERR を交換するには:

    $output = `cmd 3>&1 1>&2 2>&3 3>&-`;

To read both a command's STDOUT and its STDERR separately, it's easiest and safest to redirect them separately to files, and then read from those files when the program is done:

コマンドの STDOUT と STDERR の両方を別々に読み込みたい場合、 一番簡単で安全な方法は別々のファイルにリダイレクトし、 プログラムが終了してからそのファイルを読むことです:

    system("program args 1>/tmp/program.stdout 2>/tmp/program.stderr");

Using single-quote as a delimiter protects the command from Perl's double-quote interpolation, passing it on to the shell instead:

シングルクォートをデリミタとして使うと Perl のダブルクォート展開から 保護され、そのままシェルに渡されます:

    $perl_info  = qx(ps $$);            # that's Perl's $$
    $shell_info = qx'ps $$';            # that's the new shell's $$

How that string gets evaluated is entirely subject to the command interpreter on your system. On most platforms, you will have to protect shell metacharacters if you want them treated literally. This is in practice difficult to do, as it's unclear how to escape which characters. See perlsec for a clean and safe example of a manual fork() and exec() to emulate backticks safely.

この文字列がどのように評価されるかは完全にシステムの コマンドインタプリタに依存します。 ほとんどのプラットフォームでは、シェルのメタキャラクタを リテラルに扱ってほしい場合はそれを守る必要があります。 文字をエスケープする方法が明確ではないので、これは理論的には難しいことです。 逆クォートを安全にエミュレートするために手動で fork() と exec() を 行うためのきれいで安全な例については perlsec を参照してください。

On some platforms (notably DOS-like ones), the shell may not be capable of dealing with multiline commands, so putting newlines in the string may not get you what you want. You may be able to evaluate multiple commands in a single line by separating them with the command separator character, if your shell supports that (e.g. ; on many Unix shells; & on the Windows NT cmd shell).

(特に DOS 風の)プラットフォームには、シェルが複数行のコマンドを 扱うことができないものがあるので、文字列に改行を入れると あなたの望まない結果になる場合があります。 シェルが対応していれば、コマンド分割文字で分割することで 1 行に複数のコマンドを入れて解釈させることができます (この文字は、多くの Unix シェルでは ;、Windows NT cmd シェルでは & です)。

Beginning with v5.6.0, Perl will attempt to flush all files opened for output before starting the child process, but this may not be supported on some platforms (see perlport). To be safe, you may need to set $| ($AUTOFLUSH in English) or call the autoflush() method of IO::Handle on any open handles.

v5.6.0 以降、Perl は子プロセスの実行前に書き込み用に開いている全ての ファイルをフラッシュしようとしますが、これに対応していない プラットフォームもあります(perlport を参照してください)。 安全のためには、$| (English モジュールでは $AUTOFLUSH)をセットするか、 開いている全てのハンドルに対して IO::Handleautoflush() メソッドを 呼び出す必要があります。

Beware that some command shells may place restrictions on the length of the command line. You must ensure your strings don't exceed this limit after any necessary interpolations. See the platform-specific release notes for more details about your particular environment.

コマンド行の長さに制限があるコマンドシェルがあることに注意してください。 全ての必要な変換が行われた後、コマンド文字列がこの制限を越えないことを 保障する必要があります。 特定の環境に関するさらなる詳細についてはプラットフォーム固有の リリースノートを参照してください。

Using this operator can lead to programs that are difficult to port, because the shell commands called vary between systems, and may in fact not be present at all. As one example, the type command under the POSIX shell is very different from the type command under DOS. That doesn't mean you should go out of your way to avoid backticks when they're the right way to get something done. Perl was made to be a glue language, and one of the things it glues together is commands. Just understand what you're getting yourself into.

この演算子を使うと、プログラムの移殖が困難になります。 呼び出されるシェルコマンドはシステムによって異なり、 実際全く存在しないこともあるからです。 一つの例としては、POSIX シェルの type コマンドは DOS の type コマンドと大きく異なっています。 これは、何かを為すために正しい方法として逆クォートを使うことを 避けるべきであることを意味しません。 Perl は接着剤のような言語として作られ、接着されるべきものの一つは コマンドです。 単にあなたが何をしようとしているかを理解しておいてください。

See "O Operators"" in "I for more discussion.

さらなる議論については "O Operators"" in "I を参照して下さい。

qw/STRING/

Evaluates to a list of the words extracted out of STRING, using embedded whitespace as the word delimiters. It can be understood as being roughly equivalent to:

埋め込まれた空白を区切文字として、STRING から抜き出した 単語のリストを評価します。 これは、以下の式と大体同じと考えられます:

    split(' ', q/STRING/);

the difference being that it generates a real list at compile time. So this expression:

違いは、実際のリストをコンパイル時に生成することです。 従って、以下の表現は:

    qw(foo bar baz)

is semantically equivalent to the list:

以下のリストと文法的に等価です。

    'foo', 'bar', 'baz'

Some frequently seen examples:

よく行なわれる例としては以下のものです:

    use POSIX qw( setlocale localeconv )
    @EXPORT = qw( foo bar baz );

A common mistake is to try to separate the words with comma or to put comments into a multi-line qw-string. For this reason, the use warnings pragma and the -w switch (that is, the $^W variable) produces warnings if the STRING contains the "," or the "#" character.

よくある間違いは、単語をカンマで区切ったり、複数行の qw 文字列の中に コメントを書いたりすることです。 このために、usr warnings プラグマと -w スイッチ (つまり、$^W 変数) は STRING に "," や "#" の文字が入っていると 警告を出します。

s/PATTERN/REPLACEMENT/egimosx

Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made. Otherwise it returns false (specifically, the empty string).

文字列中でパターンを検索し、もし見つかれば、置換テキストで置き換え、 置換した数を返します。 見つからなければ、偽 (具体的には、空文字列) を返します。

If no string is specified via the =~ or !~ operator, the $_ variable is searched and modified. (The string specified with =~ must be scalar variable, an array element, a hash element, or an assignment to one of those, i.e., an lvalue.)

=~ 演算子や !~ 演算子によって文字列が指定されていなければ、 変数 $_ が検索され、修正されます。 (=~ で指定される文字列は、スカラ変数、配列要素、ハッシュ要素、 あるいは、これらへの代入式といった左辺値でなければなりません。)

If the delimiter chosen is a single quote, no interpolation is done on either the PATTERN or the REPLACEMENT. Otherwise, if the PATTERN contains a $ that looks like a variable rather than an end-of-string test, the variable will be interpolated into the pattern at run-time. If you want the pattern compiled only once the first time the variable is interpolated, use the /o option. If the pattern evaluates to the empty string, the last successfully executed regular expression is used instead. See perlre for further explanation on these. See perllocale for discussion of additional considerations that apply when use locale is in effect.

あとで述べますが、区切り文字はスラッシュとは限りません。 シングルクォートを区切り文字として使った場合には、 PATTERN にも REPLACEMENT にも変数の展開を行ないません。 それ以外の場合、文字列の最後を表わすものには見えない $ が PATTERN に含まれると、実行時に変数がパターン内に展開されます。 最初に変数が展開されるときにだけパターンのコンパイルを行ないたいときには、 /o オプションを使ってください。 パターンの評価結果が空文字列になった場合には、最後に成功した正規表現が 代わりに使われます。 これについてさらに詳しくは、perlre を参照してください。 use locale が有効の場合の議論については perllocale を参照して下さい。

Options are:

    e   Evaluate the right side as an expression.
    g   Replace globally, i.e., all occurrences.
    i   Do case-insensitive pattern matching.
    m   Treat string as multiple lines.
    o   Compile pattern only once.
    s   Treat string as single line.
    x   Use extended regular expressions.

オプションには以下のものがあります:

    e   式の右側の評価を行なう
    g   グローバルな置換、つまり見つかったものすべて
    i   大文字、小文字を区別しないで検索
    m   文字列を複数行として扱う
    o   パターンのコンパイルを 1 度だけにする
    s   文字列を単一行として扱う
    x   拡張正規表現を使用する

Any non-alphanumeric, non-whitespace delimiter may replace the slashes. If single quotes are used, no interpretation is done on the replacement string (the /e modifier overrides this, however). Unlike Perl 4, Perl 5 treats backticks as normal delimiters; the replacement text is not evaluated as a command. If the PATTERN is delimited by bracketing quotes, the REPLACEMENT has its own pair of quotes, which may or may not be bracketing quotes, e.g., s(foo)(bar) or s<foo>/bar/. A /e will cause the replacement portion to be treated as a full-fledged Perl expression and evaluated right then and there. It is, however, syntax checked at compile-time. A second e modifier will cause the replacement portion to be evaled before being run as a Perl expression.

Examples:

英数字、空白ではない任意の区切り文字で、スラッシュを 置き換えることができます。 先に述べたように、シングルクォートを使うと 置換文字列での展開はされません (/e修飾子を使えば可能です)。 Perl 4 と違って、 Perl 5 はバッククォートを通常のデリミタとして扱います。 置換テキストはコマンドとして評価されません。 PATTERN を括弧類で括った場合には、 REPLACEMENT 用にもう一組の区切り文字を用意します。 これは、括弧類であっても、なくてもかまいません。 例: s(foo)(bar)s<foo>/bar//e は置換文字列を完全な Perl の式として扱い、その場所で直ちに解釈します。 しかし、これはコンパイル時に構文チェックされます。 二番目の e 修飾子を指定すると、置換部分がまず Perl の式として eval されます。

例:

    s/\bgreen\b/mauve/g;                # don't change wintergreen

    $path =~ s|/usr/bin|/usr/local/bin|;

    s/Login: $foo/Login: $bar/; # run-time pattern

    ($foo = $bar) =~ s/this/that/;      # copy first, then change

    $count = ($paragraph =~ s/Mister\b/Mr./g);  # get change-count

    $_ = 'abc123xyz';
    s/\d+/$&*2/e;               # yields 'abc246xyz'
    s/\d+/sprintf("%5d",$&)/e;  # yields 'abc  246xyz'
    s/\w/$& x 2/eg;             # yields 'aabbcc  224466xxyyzz'

    s/%(.)/$percent{$1}/g;      # change percent escapes; no /e
    s/%(.)/$percent{$1} || $&/ge;       # expr now, so /e
    s/^=(\w+)/&pod($1)/ge;      # use function call

    # expand variables in $_, but dynamics only, using
    # symbolic dereferencing
    s/\$(\w+)/${$1}/g;

    # Add one to the value of any numbers in the string
    s/(\d+)/1 + $1/eg;

    # This will expand any embedded scalar variable
    # (including lexicals) in $_ : First $1 is interpolated
    # to the variable name, and then evaluated
    s/(\$\w+)/$1/eeg;

    # Delete (most) C comments.
    $program =~ s {
        /\*     # Match the opening delimiter.
        .*?     # Match a minimal number of characters.
        \*/     # Match the closing delimiter.
    } []gsx;

    s/^\s*(.*?)\s*$/$1/;        # trim white space in $_, expensively

    for ($variable) {           # trim white space in $variable, cheap
        s/^\s+//;
        s/\s+$//;
    }

    s/([^ ]*) *([^ ]*)/$2 $1/;  # reverse 1st two fields

Note the use of $ instead of \ in the last example. Unlike sed, we use the \<digit> form in only the left hand side. Anywhere else it's $<digit>.

最後の例で \ の代わりに $ を使っているのに注意してください。 sed と違って、\<数字> の形式はパターンの方でのみ使用できます。 その他の場所では、$<数字> を使います。

Occasionally, you can't use just a /g to get all the changes to occur that you might want. Here are two common cases:

ときには、/g を付けるだけでは、あなたが望んでいるような形で すべてを変更することができないことがあります。 2 つ例を示します:

    # put commas in the right places in an integer
    1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;  

    # expand tabs to 8-column spacing
    1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
tr/SEARCHLIST/REPLACEMENTLIST/cds
y/SEARCHLIST/REPLACEMENTLIST/cds

Transliterates all occurrences of the characters found in the search list with the corresponding character in the replacement list. It returns the number of characters replaced or deleted. If no string is specified via the =~ or !~ operator, the $_ string is transliterated. (The string specified with =~ must be a scalar variable, an array element, a hash element, or an assignment to one of those, i.e., an lvalue.)

検索リスト (SEARCHLIST) に含まれる文字を、対応する置換リスト (REPLACEMENTLIST) の文字に変換します。 置換または削除が行なわれた、文字数を返します。 =~ 演算子や =! 演算子で文字列が指定されていなければ、$_ の文字列が変換されます。 (=~ で指定される文字列は、スカラ変数、配列要素、ハッシュ要素、 あるいはこれらへの代入式といった左辺値でなければなりません。)

A character range may be specified with a hyphen, so tr/A-J/0-9/ does the same replacement as tr/ACEGIBDFHJ/0246813579/. For sed devotees, y is provided as a synonym for tr. If the SEARCHLIST is delimited by bracketing quotes, the REPLACEMENTLIST has its own pair of quotes, which may or may not be bracketing quotes, e.g., tr[A-Z][a-z] or tr(+\-*/)/ABCD/.

文字の範囲はハイフンを使って指定できます。 tr/A-J/0-9/tr/ACEGIBDFHJ/0246813579/ と同じ置換を行います。 sed の信仰者のために ytr の同義語として提供されています。 SEARCHLIST を括弧類で括った場合には、 REPLACEMENTLIST 用に、もう一組の区切り文字を用意します。 これは、括弧類であっても、なくてもかまいません。 例: tr[A-Z][a-z]tr(+\-*/)/ABCD/

Note that tr does not do regular expression character classes such as \d or [:lower:]. The <tr> operator is not equivalent to the tr(1) utility. If you want to map strings between lower/upper cases, see "lc" in perlfunc and "uc" in perlfunc, and in general consider using the s operator if you need regular expressions.

tr\d[:lower:] といった正規表現文字クラスを 使わない ことに注意してください。 tr 演算子は tr(1) ユーティリティと等価ではありません。 文字列の大文字小文字をマップしたい場合は、 "lc" in perlfunc"uc" in perlfunc を参照して下さい。 また正規表現が必要な場合には一般的に s 演算子を使うことを 考慮してみてください。

Note also that the whole range idea is rather unportable between character sets--and even within character sets they may cause results you probably didn't expect. A sound principle is to use only ranges that begin from and end at either alphabets of equal case (a-e, A-E), or digits (0-4). Anything else is unsafe. If in doubt, spell out the character sets in full.

範囲指定という考え方は文字セットが異なる場合はやや移植性に欠けることにも 注意してください -- そして同じ文字セットでも恐らく期待しているのとは違う 結果を引き起こすこともあります。 健全な原則としては、範囲の最初と最後をどちらもアルファベット (大文字小文字も同じ)(a-e, A-E)にするか、どちらも数字にする(0-4)ことです。 それ以外は全て安全ではありません。 疑わしいときは、文字セットを完全に書き出してください。

Options:

    c   Complement the SEARCHLIST.
    d   Delete found but unreplaced characters.
    s   Squash duplicate replaced characters.

オプションは以下の通りです:

    c   SEARCHLIST を補集合にする
    d   見つかったが置換されなかった文字を削除する
    s   置換された文字が重なったときに圧縮する

If the /c modifier is specified, the SEARCHLIST character set is complemented. If the /d modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted. (Note that this is slightly more flexible than the behavior of some tr programs, which delete anything they find in the SEARCHLIST, period.) If the /s modifier is specified, sequences of characters that were transliterated to the same character are squashed down to a single instance of the character.

/c 修飾子が指定されると、SEARCHLIST には補集合が指定されたものと 解釈されます。 /d 修飾子が指定されると、SEARCHLIST に指定されて、 REPLACEMENTLIST に対応するものがない文字が削除されます。 (これは、SEARCHLIST で見つかったものを削除する、ただそれだけの、ある種の tr プログラムの動作よりと比べれば、いく分柔軟なものになっています。) /s 修飾子が指定されると、同じ文字に文字変換された文字の並びを、 その文字 1 文字だけに圧縮します。

If the /d modifier is used, the REPLACEMENTLIST is always interpreted exactly as specified. Otherwise, if the REPLACEMENTLIST is shorter than the SEARCHLIST, the final character is replicated till it is long enough. If the REPLACEMENTLIST is empty, the SEARCHLIST is replicated. This latter is useful for counting characters in a class or for squashing character sequences in a class.

Examples:

/d 修飾子が使われると、REPLACEMENTLIST は、常に指定された通りに 解釈されます。 /d が指定されない場合で、REPLACEMENTLIST が SEARCHLIST よりも短いと、 同じ長さになるまで、REPLACEMENTLIST の最後の文字が 繰り返されているものとして扱われます。 REPLACEMENTLIST が空文字列でのときには、SEARCHLIST と同じになります。 後者は、ある文字クラスに含まれる文字数を数えるときや、 ある文字クラスの文字の並びを圧縮するようなときに便利です。

例:

    $ARGV[1] =~ tr/A-Z/a-z/;    # canonicalize to lower case

    $cnt = tr/*/*/;             # count the stars in $_

    $cnt = $sky =~ tr/*/*/;     # count the stars in $sky

    $cnt = tr/0-9//;            # count the digits in $_

    tr/a-zA-Z//s;               # bookkeeper -> bokeper

    ($HOST = $host) =~ tr/a-z/A-Z/;

    tr/a-zA-Z/ /cs;             # change non-alphas to single space

    tr [\200-\377]
       [\000-\177];             # delete 8th bit

If multiple transliterations are given for a character, only the first one is used:

複数の文字変換が一つの文字について指定されると、最初のものだけが使われます。

    tr/AAA/XYZ/

will transliterate any A to X.

は A を X に変換します。

Because the transliteration table is built at compile time, neither the SEARCHLIST nor the REPLACEMENTLIST are subjected to double quote interpolation. That means that if you want to use variables, you must use an eval():

変換テーブルはコンパイル時に作られるので、SEARCHLIST も REPLACEMENTLIST もダブルクォート展開の対象とはなりません。 変数を使いたい場合には、eval() を使わなければならないということです:

    eval "tr/$oldlist/$newlist/";
    die $@ if $@;

    eval "tr/$oldlist/$newlist/, 1" or die $@;

クォートされた構造のパースに関する詳細

When presented with something that might have several different interpretations, Perl uses the DWIM (that's "Do What I Mean") principle to pick the most probable interpretation. This strategy is so successful that Perl programmers often do not suspect the ambivalence of what they write. But from time to time, Perl's notions differ substantially from what the author honestly meant.

何か複数の解釈が可能な表現があった場合、Perl は最も確からしい解釈を 選択するために DWIM ("Do What I Mean")原則を使います。 この戦略は非常に成功したので、Perl プログラマはしばしば 自分が書いたものの矛盾を疑いません。 しかし時間がたつにつれて、Perl の概念は作者が本当に意味していたものから かなり変わりました。

This section hopes to clarify how Perl handles quoted constructs. Although the most common reason to learn this is to unravel labyrinthine regular expressions, because the initial steps of parsing are the same for all quoting operators, they are all discussed together.

この章では Perl がどのようにクォートされた構造を扱うかを 明確にしようと思います。 これを学ぼうとする最もよくある理由は正規表現の迷宮をほぐすためですが、 パースの初期ステップは全てのクォート演算子で同じなので、全て同時に扱います。

The most important Perl parsing rule is the first one discussed below: when processing a quoted construct, Perl first finds the end of that construct, then interprets its contents. If you understand this rule, you may skip the rest of this section on the first reading. The other rules are likely to contradict the user's expectations much less frequently than this first one.

Perl のパースに関するルールで最も重要なものは以下で述べているうち 最初のものです。 つまり、クォートされた構造を処理するときは、Perl はまずその構造の 最後を探して、それから中身を解釈します。 このルールがわかれば、とりあえずはこの章の残りは読み飛ばしてもかまいません。 その他のルールは最初のルールに比べてユーザーの予想に反する頻度は はるかに少ないです。

Some passes discussed below are performed concurrently, but because their results are the same, we consider them individually. For different quoting constructs, Perl performs different numbers of passes, from one to five, but these passes are always performed in the same order.

以下で議論するパスには同時に実行されるものもありますが、 結果は同じことなので、別々に考えることにします。 クォート構造の種類によって、Perl が実行するパスの数は 1 から 5 まで異なりますが、これらのパスは常に同じ順番で実行されます。

Finding the end

(最後を探す)

The first pass is finding the end of the quoted construct, whether it be a multicharacter delimiter "\nEOF\n" in the <<EOF construct, a / that terminates a qq// construct, a ] which terminates qq[] construct, or a > which terminates a fileglob started with <.

最初のパスはクォートされた構造の最後を探すことです。 <<EOF 構造の複数文字デリミタである "\nEOF\n"qq// 構造の終わりである /qq[] 構造の終わりである ]< で始まるファイルグロブの終わりである > などです。

When searching for single-character non-pairing delimiters, such as /, combinations of \\ and \/ are skipped. However, when searching for single-character pairing delimiter like [, combinations of \\, \], and \[ are all skipped, and nested [, ] are skipped as well. When searching for multicharacter delimiters, nothing is skipped.

/のように、1 文字でペアでないデリミタを探す場合、 \\\/ を読み飛ばします。 しかし、[のように 1 文字でペアになるデリミタの場合、 \\, \], \[ を読み飛ばし、 さらにネストした [, ] も読み飛ばします。 複数文字のデリミタの場合、何も読み飛ばしません。

For constructs with three-part delimiters (s///, y///, and tr///), the search is repeated once more.

3 つのデリミタからなる構造 (s///, y///, tr///) の場合、 検索はもう一度繰り返されます。

During this search no attention is paid to the semantics of the construct. Thus:

検索する間、構造の文脈は考慮しません。従って、

    "$hash{"$foo/$bar"}"

or:

や、

    m/ 
      bar       # NOT a comment, this slash / terminated m//!
     /x

do not form legal quoted expressions. The quoted part ends on the first " and /, and the rest happens to be a syntax error. Because the slash that terminated m// was followed by a SPACE, the example above is not m//x, but rather m// with no /x modifier. So the embedded # is interpreted as a literal #.

は正しいクォート表現ではありません。 クォートは最初の "/ で終わりとなり、 残りの部分は文法エラーとなります。 m// を終わらせているスラッシュの次に来ているのが 空白 なので、 上の例では m//x ではなく、/x なしの m// となります。 従って、中にある # はリテラルな # として扱われます。

Removal of backslashes before delimiters

(デリミタの前のバックスラッシュの削除)

During the second pass, text between the starting and ending delimiters is copied to a safe location, and the \ is removed from combinations consisting of \ and delimiter--or delimiters, meaning both starting and ending delimiters will should these differ. This removal does not happen for multi-character delimiters. Note that the combination \\ is left intact, just as it was.

第二のパスとして、開始デリミタと終了デリミタの間のテキストは 安全な場所にコピーされ、\ とデリミタの組み合わせから \ を削除します。 開始デリミタと終了デリミタが異なる場合はその両方に対してです。 この削除は複数文字デリミタに対しては行われません。 今までと同様、\\ はそのまま残されることに注意してください。

Starting from this step no information about the delimiters is used in parsing.

このステップの開始から、デリミタに関する情報は一切パースには 使われません。

Interpolation

(文字変換)

The next step is interpolation in the text obtained, which is now delimiter-independent. There are four different cases.

次のステップは、得られた(デリミタに依存しない)テキストに対する文字変換です。 4 つのケースがあります。

<<'EOF', m'', s''', tr///, y///

No interpolation is performed.

文字変換は行われません。

'', q//

The only interpolation is removal of \ from pairs \\.

\\ の組における \ の削除のみが行われます。

"", ``, qq//, qx//, <file*glob>

\Q, \U, \u, \L, \l (possibly paired with \E) are converted to corresponding Perl constructs. Thus, "$foo\Qbaz$bar" is converted to $foo . (quotemeta("baz" . $bar)) internally. The other combinations are replaced with appropriate expansions.

\Q, \U, \u, \L, \l (おそらくは \E との組)は 対応する Perl 構造に変換されます。 従って、"$foo\Qbaz$bar" は内部的に $foo . (quotemeta("baz" . $bar)) に変換されます。 その他の組み合わせは適切な拡張に置換されます。

Let it be stressed that whatever falls between \Q and \E is interpolated in the usual way. Something like "\Q\\E" has no \E inside. instead, it has \Q, \\, and E, so the result is the same as for "\\\\E". As a general rule, backslashes between \Q and \E may lead to counterintuitive results. So, "\Q\t\E" is converted to quotemeta("\t"), which is the same as "\\\t" (since TAB is not alphanumeric). Note also that:

\Q\E の間にある全てのもの が通常の方法で展開されます。 "\Q\\E" のようなものは内部にあるのは \E ではなく、 \Q, \\, E であるので、結果は "\\\\E" と同じになります。 一般的なルールとして、\Q\E の間にあるバックスラッシュは 直感に反した結果になります。 それで、"\Q\t\E"quotemeta("\t") に変換され、これは(TAB は 英数字ではないので "\\\t" と同じです。 以下のようなことにも注意してください:

  $str = '\t';
  return "\Q$str";

may be closer to the conjectural intention of the writer of "\Q\t\E".

これは "\Q\t\E" を書いた人の憶測上の 意図 により近いです。

Interpolated scalars and arrays are converted internally to the join and . catenation operations. Thus, "$foo XXX '@arr'" becomes:

展開されたスカラと配列は内部で join. の結合操作に変換されます。 従って、"$foo XXX '@arr'" は以下のようになります:

  $foo . " XXX '" . (join $", @arr) . "'";

All operations above are performed simultaneously, left to right.

上記の全ての操作は、左から右に同時に行われます。

Because the result of "\Q STRING \E" has all metacharacters quoted, there is no way to insert a literal $ or @ inside a \Q\E pair. If protected by \, $ will be quoted to became "\\\$"; if not, it is interpreted as the start of an interpolated scalar.

"\Q STRING \E" の結果は全てのメタ文字がクォートされているので、 \Q\E の組の内側にリテラルの $@ を挿入する方法はありません。 \ によって守られている場合、$ はクォートされて "\\\$" と なります。 そうでない場合、これは展開されるスカラ変数の開始として解釈されます。

Note also that the interpolation code needs to make a decision on where the interpolated scalar ends. For instance, whether "a $b -> {c}" really means:

展開コードは、展開するスカラ変数がどこで終わるかを決定する必要が あることにも注意してください。 例えば、"a $b -> {c}" が実際には以下のようになるか:

  "a " . $b . " -> {c}";

以下のようになるかです:

  "a " . $b -> {c};

Most of the time, the longest possible text that does not include spaces between components and which contains matching braces or brackets. because the outcome may be determined by voting based on heuristic estimators, the result is not strictly predictable. Fortunately, it's usually correct for ambiguous cases.

ほとんどの場合、要素と、マッチする中かっこや大かっこの間に空白を含まない、 最も長いテキストになります。 出力は発見的な推定器をよる投票によって決定されるので、結果は厳密には 予測できません。 幸い、紛らわしい場合でも普通は正しいです。

?RE?, /RE/, m/RE/, s/RE/foo/,

Processing of \Q, \U, \u, \L, \l, and interpolation happens (almost) as with qq// constructs, but the substitution of \ followed by RE-special chars (including \) is not performed. Moreover, inside (?{BLOCK}), (?# comment ), and a #-comment in a //x-regular expression, no processing is performed whatsoever. This is the first step at which the presence of the //x modifier is relevant.

\Q, \U, \u, \L, \l の処理と展開が qq// 構造と(ほとんど) 同じように起こりますが, \ の後に正規表現の特殊文字(\ を含みます)が 続く場合の置換は行われません。 さらに、(?{BLOCK}), (?# comment ), //x 正規表現での # の コメントの中では、どのような処理も行われません。 これは //x 修飾子が影響を与える最初のステップです。

Interpolation has several quirks: $|, $(, and $) are not interpolated, and constructs $var[SOMETHING] are voted (by several different estimators) to be either an array element or $var followed by an RE alternative. This is where the notation ${arr[$bar]} comes handy: /${arr[0-9]}/ is interpreted as array element -9, not as a regular expression from the variable $arr followed by a digit, which would be the interpretation of /$arr[0-9]/. Since voting among different estimators may occur, the result is not predictable.

展開ではいくつか特殊な動作をします: $|, $(, $) は展開されず、 $var[SOMETHING] は(いくつかの異なる推定器によって)配列の要素か $var の後に正規表現が続いているのかが投票されます。 これは ${arr[$bar]} が便利になるところです: /${arr[0-9]}/ は 配列要素 -9 として解釈され、/$arr[0-9]/ の場合のように $arr の後に 数値が続いているような正規表現としては解釈されません。 異なった推定器によって投票されることがあるので、結果は予測できません。

It is at this step that \1 is begrudgingly converted to $1 in the replacement text of s/// to correct the incorrigible sed hackers who haven't picked up the saner idiom yet. A warning is emitted if the use warnings pragma or the -w command-line flag (that is, the $^W variable) was set.

このステップでは、より健全な文法をまだ導入していない、手に負えない sed ハッカーのために、s/// の置換テキストの中にある \1 を、しぶしぶながら $1 に変換します。 use warnings プラグマやコマンドラインオプション -w (これは $^W 変数です) がセットされていると警告が生成されます。

The lack of processing of \\ creates specific restrictions on the post-processed text. If the delimiter is /, one cannot get the combination \/ into the result of this step. / will finish the regular expression, \/ will be stripped to / on the previous step, and \\/ will be left as is. Because / is equivalent to \/ inside a regular expression, this does not matter unless the delimiter happens to be character special to the RE engine, such as in s*foo*bar*, m[foo], or ?foo?; or an alphanumeric char, as in:

\\ を処理しないことにより、後処理したテキストに特定の制限があります。 デリミタが / の場合、このステップの結果として \/ を得ることは できません。 / は正規表現を終わらせ、\/ は前のステップで / に展開され、 \\/ はそのまま残されます。 / は正規表現の中では \/ と等価なので、これはたまたまデリミタが 正規検索エンジンにとって特別な文字の場合、つまり s*foo*bar*, m[foo], ?foo? のような場合、あるいは以下のように英数字でなければ、 問題にはなりません:

  m m ^ a \s* b mmx;

In the RE above, which is intentionally obfuscated for illustration, the delimiter is m, the modifier is mx, and after backslash-removal the RE is the same as for m/ ^ a s* b /mx). There's more than one reason you're encouraged to restrict your delimiters to non-alphanumeric, non-whitespace choices.

上記の正規表現では、説明のために意図的にわかりにくくしていますが、 デリミタは m で、修飾子は mx で、バックスラッシュを取り除いた後の 正規表現は m/ ^ a s* b /mx) と同じです。 デリミタを英数字や空白でないものに制限するべきである理由は複数あります。

This step is the last one for all constructs except regular expressions, which are processed further.

これは正規表現以外の全ての構造にとって最後のステップです。 正規表現はさらに処理が続きます。

Interpolation of regular expressions

(正規表現の文字変換)

Previous steps were performed during the compilation of Perl code, but this one happens at run time--although it may be optimized to be calculated at compile time if appropriate. After preprocessing described above, and possibly after evaluation if catenation, joining, casing translation, or metaquoting are involved, the resulting string is passed to the RE engine for compilation.

以前のステップは Perl コードのコンパイル中に実行されますが、 これは実行時に起こります -- しかし、もし適切ならコンパイル時に 計算できるように最適化されることもあります。 上記の前処理の後、そして必要なら連結、結合、大文字小文字変換、 メタクォート化が行われた後、結果の 文字列 がコンパイルのために 正規表現エンジンに渡されます。

Whatever happens in the RE engine might be better discussed in perlre, but for the sake of continuity, we shall do so here.

正規表現エンジンで起こることについては perlre で議論した方が よいでしょうが、継続性のために、ここでそれを行います。

This is another step where the presence of the //x modifier is relevant. The RE engine scans the string from left to right and converts it to a finite automaton.

これも //x 修飾子の存在が関連するステップの一つです。 正規表現エンジンは文字列を左から右にスキャンして、有限状態オートマトンに 変換します。

Backslashed characters are either replaced with corresponding literal strings (as with \{), or else they generate special nodes in the finite automaton (as with \b). Characters special to the RE engine (such as |) generate corresponding nodes or groups of nodes. (?#...) comments are ignored. All the rest is either converted to literal strings to match, or else is ignored (as is whitespace and #-style comments if //x is present).

バックスラッシュ付きの文字は(\{ のように)対応するリテラル文字列に 置換されるか、あるいは(\b のように)有限状態オートマトンの特別な ノードを生成します。 (| のような)正規表現エンジンにとって特別な文字は対応するノードか ノードのグループを生成します。 残りの全てはマッチするリテラル文字列に変換されるか、そうでなければ (//x が指定された時の空白と # スタイルのコメントと同様に) 無視されます。

Parsing of the bracketed character class construct, [...], is rather different than the rule used for the rest of the pattern. The terminator of this construct is found using the same rules as for finding the terminator of a {}-delimited construct, the only exception being that ] immediately following [ is treated as though preceded by a backslash. Similarly, the terminator of (?{...}) is found using the same rules as for finding the terminator of a {}-delimited construct.

文字クラス構造 [...] のパースは他のパターンとはルールが異なります。 この構造の終端は {} でデリミタされた構造の終端を検索するのと同じルールで 検索されます; 唯一の例外は、[ の直後の ] はバックスラッシュが 先行しているものとして扱われます。 同様に、(?{...}) の終端は {} でデリミタされた構造の終端を 検索されるのと同じルールで検索されます。

It is possible to inspect both the string given to RE engine and the resulting finite automaton. See the arguments debug/debugcolor in the use re pragma, as well as Perl's -Dr command-line switch documented in "Command Switches" in perlrun.

正規表現に与えられる文字列と、結果としての有限状態オートマトンの両方を 検査できます。 use re プラグマの debug/debugcolor 引数と、 "Command Switches" in perlrun に記述されている -Dr コマンドライン オプションを参照してください。

Optimization of regular expressions

(正規表現の最適化)

This step is listed for completeness only. Since it does not change semantics, details of this step are not documented and are subject to change without notice. This step is performed over the finite automaton that was generated during the previous pass.

このステップは完全性のためだけにリストされています。 これは意味論的には変化がないので、このステップの詳細は文書化されておらず、 将来予告なしに変更されることがあります。 このステップはここまでの処理で生成された有限オートマトンに対して 適用されます。

It is at this stage that split() silently optimizes /^/ to mean /^/m.

split()/^/ を暗黙に /^/m に最適化するのもこのステップです。

I/O 演算子

There are several I/O operators you should know about.

知っておいた方がよい I/O 演算子もいくつかあります。

A string enclosed by backticks (grave accents) first undergoes double-quote interpolation. It is then interpreted as an external command, and the output of that command is the value of the backtick string, like in a shell. In scalar context, a single string consisting of all output is returned. In list context, a list of values is returned, one per line of output. (You can set $/ to use a different line terminator.) The command is executed each time the pseudo-literal is evaluated. The status value of the command is returned in $? (see perlvar for the interpretation of $?). Unlike in csh, no translation is done on the return data--newlines remain newlines. Unlike in any of the shells, single quotes do not hide variable names in the command from interpretation. To pass a literal dollar-sign through to the shell you need to hide it with a backslash. The generalized form of backticks is qx//. (Because backticks always undergo shell expansion as well, see perlsec for security concerns.)

バッククォートで括られた文字列は、まず、ダブルクォート補完のように 変数の展開が行なわれます。 その後、シェルでの場合と同じように、外部コマンドとして解釈され、 そのコマンドの出力がこのバッククォート文字列の値となります。 スカラーコンテキストでは、出力すべてを含む一個の文字列が返されます。 リストコンテキストでは、出力の 1 行 1 行が個々の要素となるリストが返されます。 ($/ を設定すれば、行の終わりを示す文字を変えることができます。) コマンドは、この擬似リテラルが評価されるごとに実行されます。 コマンドのステータス値は $? に返されます ($? の解釈については、 perlvar を参照してください)。 csh での場合とは違って、結果のデータに対する変換は行なわれず、 改行は改行のままです。 どのシェルとも違って、シングルクォートがコマンド中の変数名を 解釈させないようにすることはありません。 シェルにリテラルなドル記号を渡すには、バックスラッシュで エスケープしなければなりません。 バッククォートの一般形は、qx// です。 (バッククォートは常にシェル展開されます。 セキュリティに関しては perlsec を参照して下さい)

In scalar context, evaluating a filehandle in angle brackets yields the next line from that file (the newline, if any, included), or undef at end-of-file or on error. When $/ is set to undef (sometimes known as file-slurp mode) and the file is empty, it returns '' the first time, followed by undef subsequently.

スカラーコンテキストで山括弧の中のファイルハンドルを評価すると、 そのファイルから、次の行を読み込むことになります (改行があればそれも含まれます)。 ファイルの最後またはエラーの場合は undef を返します。 $/undef に設定されている場合(ファイル吸い込みモードと呼ばれます) でファイルが空の場合、 最初は '' を返し、次は undef を返します。

Ordinarily you must assign the returned value to a variable, but there is one situation where an automatic assignment happens. If and only if the input symbol is the only thing inside the conditional of a while statement (even if disguised as a for(;;) loop), the value is automatically assigned to the global variable $_, destroying whatever was there previously. (This may seem like an odd thing to you, but you'll use the construct in almost every Perl script you write.) The $_ variable is not implicitly localized. You'll have to put a local $_; before the loop if you want that to happen.

The following lines are equivalent:

通常は、返された値を変数に代入しなければなりませんが、自動的に 代入される場合が 1 つだけあります。 この入力シンボルが、while 文(for(;;) の形になっていたとしても)の条件式中に 単独で現れた場合だけは、その値が自動的にグローバル変数 $_ に代入されます。 以前の値は破壊されます。 (これは、奇妙に思えるかもしれませんが、ほとんどすべての Perl スクリプトで これが必要になることでしょう。) $_ 変数は暗黙にはローカル化されません。 そうしたい場合はループの前に local $_; と書く必要があります。

以下のものは、お互いに同値なものです:

    while (defined($_ = <STDIN>)) { print; }
    while ($_ = <STDIN>) { print; }
    while (<STDIN>) { print; }
    for (;<STDIN>;) { print; }
    print while defined($_ = <STDIN>);
    print while ($_ = <STDIN>);
    print while <STDIN>;

This also behaves similarly, but avoids $_ :

以下は同様の振る舞いをしますが、$_ を使いません:

    while (my $line = <STDIN>) { print $line }    

In these loop constructs, the assigned value (whether assignment is automatic or explicit) is then tested to see whether it is defined. The defined test avoids problems where line has a string value that would be treated as false by Perl, for example a "" or a "0" with no trailing newline. If you really mean for such values to terminate the loop, they should be tested for explicitly:

これらのループ構造の中で、代入された値は (代入が自動か明示的かに関わりなく) 定義されているかどうかを見るためにテストされます。 定義テストは、行が Perl にとって偽となる文字列値を持っているかどうかの 問題を避けます。例えば newline のついていない "" や "0" です。 もし本当にこのような値でループを終了させたいときは、 以下のように明示的にテストするべきです:

    while (($_ = <STDIN>) ne '0') { ... }
    while (<STDIN>) { last unless $_; ... }

In other boolean contexts, <filehandle> without an explicit defined test or comparison elicit a warning if the use warnings pragma or the -w command-line switch (the $^W variable) is in effect.

その他のブール値コンテキストでは、明示的な defined や比較なしに <filehandle> を使うと、use warnings プラグマや -w コマンドラインスイッチ ($^W 変数) が有効なときには、 警告を発生させます。

The filehandles STDIN, STDOUT, and STDERR are predefined. (The filehandles stdin, stdout, and stderr will also work except in packages, where they would be interpreted as local identifiers rather than global.) Additional filehandles may be created with the open() function, amongst others. See perlopentut and "open" in perlfunc for details on this.

STDIN、STDOUT、STDERR というファイルハンドルは、あらかじめ定義されています。 (stdinstdoutstderr というファイルハンドルも、 ローカルな名前でこれらのグローバルな名前が見えなくなっている パッケージを除けば、使用することができます。) その他のファイルハンドルは、open() 関数などで作ることができます。 これに関する詳細については perlopentut"open" in perlfunc を 参照して下さい。

If a <FILEHANDLE> is used in a context that is looking for a list, a list comprising all input lines is returned, one line per list element. It's easy to grow to a rather large data space this way, so use with care.

<FILEHANDLE> がリストを必要とするコンテキストで用いられると、 1 要素に 1 行の入力行すべてからなるリストが返されます。 これを使うと簡単にかなり大きなデータになってしまいますので、 注意を要します。

<FILEHANDLE> may also be spelled readline(*FILEHANDLE). See "readline" in perlfunc.

<FILEHANDLE> は readline(*FILEHANDLE) とも書けます。 "readline" in perlfunc を参照して下さい。

The null filehandle <> is special: it can be used to emulate the behavior of sed and awk. Input from <> comes either from standard input, or from each file listed on the command line. Here's how it works: the first time <> is evaluated, the @ARGV array is checked, and if it is empty, $ARGV[0] is set to "-", which when opened gives you standard input. The @ARGV array is then processed as a list of filenames. The loop

ヌルファイルハンドル <> は特別で、sedawk の動作を エミュレートするために使われます。 <> からの入力は、標準入力からか、コマンドライン上に並べられた個々の ファイルから行なわれます。 動作の概要は、以下のようになります。 最初に <> が評価されると、配列 @ARGV が調べられ、空であれば、 $ARGV[0] に "-"を設定します。 これは、open されるとき標準入力となります。 その後、配列 @ARGV がファイル名のリストとして処理されます。

    while (<>) {
        ...                     # code for each line
    }

is equivalent to the following Perl-like pseudo code:

は以下ののような Perl の擬似コードと等価です:

    unshift(@ARGV, '-') unless @ARGV;
    while ($ARGV = shift) {
        open(ARGV, $ARGV);
        while (<ARGV>) {
            ...         # code for each line
        }
    }

except that it isn't so cumbersome to say, and will actually work. It really does shift the @ARGV array and put the current filename into the $ARGV variable. It also uses filehandle ARGV internally--<> is just a synonym for <ARGV>, which is magical. (The pseudo code above doesn't work because it treats <ARGV> as non-magical.)

但し、わずらわしく書かなくても、動作します。 実際に @ARGV を shift しますし、その時点のファイル名を変数 $ARGV に 入れています。 また、内部的にファイルハンドル ARGV を使っていて、<> はマジカルな <ARGV> の同義語となっています。 (上記の擬似コードは、<ARGV> を通常のものとして扱っているので、 うまく動作しません。)

You can modify @ARGV before the first <> as long as the array ends up containing the list of filenames you really want. Line numbers ($.) continue as though the input were one big happy file. See the example in "eof" in perlfunc for how to reset line numbers on each file.

最終的に、@ARGV に扱いたいと思っているファイル名が含まれるのであれば、 最初に <> を評価する前に @ARGV を変更することも可能です。 行番号 ($.) は、入力ファイルがあたかも 1 つの大きなファイルで あるかのように、続けてカウントされます。 個々のファイルごとにリセットする方法は、"eof" in perlfunc の例を 参照してください。

If you want to set @ARGV to your own list of files, go right ahead. This sets @ARGV to all plain text files if no @ARGV was given:

最初から @ARGV に自分でファイルのリストを設定してもかまいません。 以下は @ARGV が与えられなかったときに全てのテキストファイルを @ARGV に設定します。

    @ARGV = grep { -f && -T } glob('*') unless @ARGV;

You can even set them to pipe commands. For example, this automatically filters compressed arguments through gzip:

ここにパイプコマンドを置くことも出来ます。 例えば、以下は圧縮された引数を自動的に gzip のフィルタに通します:

    @ARGV = map { /\.(gz|Z)$/ ? "gzip -dc < $_ |" : $_ } @ARGV;

If you want to pass switches into your script, you can use one of the Getopts modules or put a loop on the front like this:

スクリプトにスイッチを渡したいのであれば、Getopts モジュールを 使うこともできますし、実際の処理の前にのようなループを置くこともできます。

    while ($_ = $ARGV[0], /^-/) {
        shift;
        last if /^--$/;
        if (/^-D(.*)/) { $debug = $1 }
        if (/^-v/)     { $verbose++  }
        # ...           # other switches
    }

    while (<>) {
        # ...           # code for each line
    }

The <> symbol will return undef for end-of-file only once. If you call it again after this, it will assume you are processing another @ARGV list, and if you haven't set @ARGV, will read input from STDIN.

シンボル <> がファイルの最後で undef を返すのは一度きりです。 そのあとでもう一度呼び出すと、新たに別の @ARGV を処理するものとみなされ、 その時に @ARGV を設定しなおしていないと、STDIN からの入力を 読み込むことになります。

If angle brackets contain is a simple scalar variable (e.g., <$foo>), then that variable contains the name of the filehandle to input from, or its typeglob, or a reference to the same. For example:

山括弧の中の文字列が (<$foo> のような) 単純スカラ変数を囲っていれば、 その変数が入力を行なうファイルハンドルの名前そのもの、名前への型グロブ、 名前へのリファレンスのいずれかを示しているとみなされます。

    $fh = \*STDIN;
    $line = <$fh>;

If what's within the angle brackets is neither a filehandle nor a simple scalar variable containing a filehandle name, typeglob, or typeglob reference, it is interpreted as a filename pattern to be globbed, and either a list of filenames or the next filename in the list is returned, depending on context. This distinction is determined on syntactic grounds alone. That means <$x> is always a readline() from an indirect handle, but <$hash{key}> is always a glob(). That's because $x is a simple scalar variable, but $hash{key} is not--it's a hash element.

山括弧の中の文字列がファイルハンドルでもファイルハンドル名、型グロブ、 型グロブリファレンスのいずれかが入った単純スカラ変数でもなければ、 グロブを行なうファイル名のパターンと解釈され、コンテキストによって ファイル名のリストか、そのリストの次のファイル名が返されます。 この区別は単に構文的に行われます。 <$x> は常に間接ハンドルから readline() しますが、 <$hash{key}> は常に glob() します。 $x は単純スカラー変数ですが、$hash{key} は違う(ハッシュ要素)からです。

One level of double-quote interpretation is done first, but you can't say <$foo> because that's an indirect filehandle as explained in the previous paragraph. (In older versions of Perl, programmers would insert curly brackets to force interpretation as a filename glob: <${foo}>. These days, it's considered cleaner to call the internal function directly as glob($foo), which is probably the right way to have done it in the first place.) For example:

まず、1 段階だけダブルクォート展開が行なわれますが、前の段落に書いた 間接ファイルハンドルと同じになる、<$foo> のようには書けません。 (Perl の古いバージョンでは、ファイル名グロブと解釈させるために <${foo}> のように中括弧を入れていました。 最近ではより明確にするために、glob($foo) と内部関数を 呼ぶこともできます。 おそらく、まず、こちらの方で試すのが正解でしょう。) 例:

    while (<*.c>) {
        chmod 0644, $_;
    }

is roughly equivalent to:

はだいたい以下と等価です:

    open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
    while (<FOO>) {
        chomp;
        chmod 0644, $_;
    }

except that the globbing is actually done internally using the standard File::Glob extension. Of course, the shortest way to do the above is:

但し実際のグロブは内部的に標準の File::Glob モジュールを使います。 もちろん、もっと簡単に以下のように書けます:

    chmod 0644, <*.c>;

A (file)glob evaluates its (embedded) argument only when it is starting a new list. All values must be read before it will start over. In list context, this isn't important because you automatically get them all anyway. However, in scalar context the operator returns the next value each time it's called, or undef when the list has run out. As with filehandle reads, an automatic defined is generated when the glob occurs in the test part of a while, because legal glob returns (e.g. a file called 0) would otherwise terminate the loop. Again, undef is returned only once. So if you're expecting a single value from a glob, it is much better to say

(ファイル)グロブは新しいリストを開始するときにだけ(組み込みの)引数を 評価します。 全ての値は開始する前に読み込んでいなければなりません。 これはリストコンテキストでは、とにかく自動的に全てを取り込むので 重要ではありません。 しかし、スカラーコンテキストではこの演算子は呼び出された時の 次の値か、リストがなくなったときには undef を返します。 ファイルハンドルを読み込む場合は、グロブが while の条件部にある場合は 自動的な defined が生成されます。 なぜならそうしないと、本来の glob の返り値 (0 というファイル) が ループを終了させるからです。 ここでも、undef は一度だけ返されます。 従って、もしグロブから一つの値だけを想定している場合、 以下のように書くことが:

    ($file) = <blurch*>;

than

以下のように書くよりはるかに良いです:

    $file = <blurch*>;

because the latter will alternate between returning a filename and returning false.

なぜなら後者はファイル名を返す場合と偽を返す場合があるからです。

It you're trying to do variable interpolation, it's definitely better to use the glob() function, because the older notation can cause people to become confused with the indirect filehandle notation.

変数変換に挑戦する場合、明らかに glob() 関数を使う方が良いです。 なぜなら古い表記は間接ファイルハンドル表記と混乱するかも知れないからです。

    @files = glob("$dir/*.[ch]");
    @files = glob($files[$i]);

定数の畳み込み

Like C, Perl does a certain amount of expression evaluation at compile time whenever it determines that all arguments to an operator are static and have no side effects. In particular, string concatenation happens at compile time between literals that don't do variable substitution. Backslash interpolation also happens at compile time. You can say

C と同じように Perl でも、演算子に対するすべての引数がスタティックで、 副作用がないと判断できれば、コンパイル時に式の評価を行なってしまいます。 特に、変数置換の無いリテラルどうしの文字列連結はコンパイル時に行なわれます。 バックスラッシュの解釈もコンパイル時に行なわれます。

    'Now is the time for all' . "\n" .
        'good men to come to.'

and this all reduces to one string internally. Likewise, if you say

と書いても、内部的に 1 つの文字列になります。同様に

    foreach $file (@filenames) {
        if (-s $file > 5 + 100 * 2**16) {  }
    }

the compiler will precompute the number which that expression represents so that the interpreter won't have to.

と書くとコンパイラは、式が表わす数値をあらかじめ計算しますので、 インタプリタで計算する必要がなくなっています。

ビット列演算子

Bitstrings of any size may be manipulated by the bitwise operators (~ | & ^).

任意のサイズのビット列はビット単位演算子(~ | & ^)で操作できます。

If the operands to a binary bitwise op are strings of different sizes, | and ^ ops act as though the shorter operand had additional zero bits on the right, while the & op acts as though the longer operand were truncated to the length of the shorter. The granularity for such extension or truncation is one or more bytes.

二項ビット単位演算子のオペランドが異なった長さの文字列だった場合、 |^ の演算子は短い側のオペランドの右側に追加のゼロが ついているとみなします。 一方 & 演算子は長い方のオペランドが短い方に切り詰められます。 この拡張や短縮の粒度はバイト単位です。

    # ASCII-based examples 
    print "j p \n" ^ " a h";            # prints "JAPH\n"
    print "JA" | "  ph\n";              # prints "japh\n"
    print "japh\nJunk" & '_____';       # prints "JAPH\n";
    print 'p N$' ^ " E<H\n";            # prints "Perl\n";

If you are intending to manipulate bitstrings, be certain that you're supplying bitstrings: If an operand is a number, that will imply a numeric bitwise operation. You may explicitly show which type of operation you intend by using "" or 0+, as in the examples below.

ビット列を操作したい場合は、確実にビット列が渡されるようにしてください: オペランドが数字の場合、数値 ビット単位演算を仮定します。 明示的に演算の型を指定するときには、以下の例のように ""0+ を使ってください。

    $foo =  150  |  105 ;       # yields 255  (0x96 | 0x69 is 0xFF)
    $foo = '150' |  105 ;       # yields 255
    $foo =  150  | '105';       # yields 255
    $foo = '150' | '105';       # yields string '155' (under ASCII)

    $baz = 0+$foo & 0+$bar;     # both ops explicitly numeric
    $biz = "$foo" ^ "$bar";     # both ops explicitly stringy

See "vec" in perlfunc for information on how to manipulate individual bits in a bit vector.

ビットベクタの個々のビットをどのように操作するかの情報については "vec" in perlfunc を参照して下さい。

整数演算

By default, Perl assumes that it must do most of its arithmetic in floating point. But by saying

デフォルトでは、Perl は演算を浮動小数で行なわなければならないものと しています。 しかし、(もしそうしたいなら)

    use integer;

you may tell the compiler that it's okay to use integer operations (if it feels like it) from here to the end of the enclosing BLOCK. An inner BLOCK may countermand this by saying

と書けば、その場所から現在の BLOCK の終わりまでは、整数演算を 行なってよいと、コンパイラに指示することができます。 内部の BLOCK で、

    no integer;

which lasts until the end of that BLOCK. Note that this doesn't mean everything is only an integer, merely that Perl may use integer operations if it is so inclined. For example, even under use integer, if you take the sqrt(2), you'll still get 1.4142135623731 or so.

と書けば、その BLOCK の終わりまでは、指示を取り消すことになります。 これは全てを整数だけを使って処理することを意味するわけではないことに 注意してください。 これは単に Perl が整数を使いたいと思ったときに使うかもしれない、 というだけです。 例えば、use integer の指定があっても、sqrt(2) とすると、 1.4142135623731 といった結果が返ってきます。

Used on numbers, the bitwise operators ("&", "|", "^", "~", "<<", and ">>") always produce integral results. (But see also "Bitwise String Operators".) However, use integer still has meaning for them. By default, their results are interpreted as unsigned integers, but if use integer is in effect, their results are interpreted as signed integers. For example, ~0 usually evaluates to a large integral value. However, use integer; ~0 is -1 on twos-complement machines.

数値を使う場合、ビット単位演算子 ("&", "|", "^", "~", "<<", ">>") は 常に整数の結果を生成します(但し "Bitwise String Operators" も 参照して下さい)。 しかし、それでも use integer は意味があります。 デフォルトでは、これらの結果は符号なし整数として解釈されますが、 use integer が有効の場合は、符号付き整数として解釈されます。 例えば、~0 は通常大きな整数の値として評価されます。 しかし、use integer; ~0 は 2 の補数のマシンでは -1 になります。

浮動小数点演算

While use integer provides integer-only arithmetic, there is no analogous mechanism to provide automatic rounding or truncation to a certain number of decimal places. For rounding to a certain number of digits, sprintf() or printf() is usually the easiest route. See perlfaq4.

use integer が整数演算を提供する一方、数を特定の桁で自動的に丸めたり 切り捨てたりする機構はありません。 数を丸めるには、sprintf() や printf() を使うのが一番簡単な方法です。 perlfaq4 を参照して下さい。

Floating-point numbers are only approximations to what a mathematician would call real numbers. There are infinitely more reals than floats, so some corners must be cut. For example:

浮動小数点数は数学者が実数と呼ぶものの近似でしかありません。 実数は浮動小数点より無限に続くので、多少角が丸められます。例:

    printf "%.20g\n", 123456789123456789;
    #        produces 123456789123456784

Testing for exact equality of floating-point equality or inequality is not a good idea. Here's a (relatively expensive) work-around to compare whether two floating-point numbers are equal to a particular number of decimal places. See Knuth, volume II, for a more robust treatment of this topic.

浮動小数点数が等しいかどうかをちょうど同じかどうかで比較するのは いいアイデアではありません。 以下に、二つの浮動小数点数が指定された桁まで等しいかどうかを 比較する(比較的重い)次善の策を示します。 この問題に関するより厳密な扱いについては Knuth, volume II を参照して下さい。

    sub fp_equal {
        my ($X, $Y, $POINTS) = @_;
        my ($tX, $tY);
        $tX = sprintf("%.${POINTS}g", $X);
        $tY = sprintf("%.${POINTS}g", $Y);
        return $tX eq $tY;
    }

The POSIX module (part of the standard perl distribution) implements ceil(), floor(), and other mathematical and trigonometric functions. The Math::Complex module (part of the standard perl distribution) defines mathematical functions that work on both the reals and the imaginary numbers. Math::Complex not as efficient as POSIX, but POSIX can't work with complex numbers.

POSIX モジュール(Perl 標準配布パッケージの一部) は ceil(), floor() 及び その他の数学関数や三角関数を実装しています。 Math::Complex モジュール(Perl 標準配布パッケージの一部)は 実数と虚数の両方で動作する数学関数を定義しています。 Math::Complex は POSIX ほど効率的ではありませんが、 POSIX は複素数は扱えません。

Rounding in financial applications can have serious implications, and the rounding method used should be specified precisely. In these cases, it probably pays not to trust whichever system rounding is being used by Perl, but to instead implement the rounding function you need yourself.

金融アプリケーションにおける丸めは深刻な影響を与える可能性があり、 使用する丸めメソッドは指定された精度で行われるべきです。 このような場合、Perl が使用するシステム丸めを信用せず、 代わりに自分自身で丸め関数を実装するべきです。

より大きな数

The standard Math::BigInt and Math::BigFloat modules provide variable-precision arithmetic and overloaded operators, although they're currently pretty slow. At the cost of some space and considerable speed, they avoid the normal pitfalls associated with limited-precision representations.

標準の Math::BigInt と Math::BigFloat モジュールは多倍長演算を提供し、 演算子をオーバーロードしますが、これらは現在のところかなり遅いです。 多少の領域とかなりの速度を犠牲にして、桁数が制限されていることによる ありがちな落とし穴を避けることができます。

    use Math::BigInt;
    $x = Math::BigInt->new('123456789123456789');
    print $x * $x;

    # prints +15241578780673678515622620750190521

There are several modules that let you calculate with (bound only by memory and cpu-time) unlimited or fixed precision. There are also some non-standard modules that provide faster implementations via external C libraries.

(メモリと CPU 時間のみに依存する)無制限か固定の精度での計算ができる モジュールがいくつかあります。 さらに外部 C ライブラリを使ってより速い実装を提供する 非標準のモジュールもあります。

Here is a short, but incomplete summary:

        Math::Fraction          big, unlimited fractions like 9973 / 12967
        Math::String            treat string sequences like numbers
        Math::FixedPrecision    calculate with a fixed precision
        Math::Currency          for currency calculations
        Bit::Vector             manipulate bit vectors fast (uses C)
        Math::BigIntFast        Bit::Vector wrapper for big numbers
        Math::Pari              provides access to the Pari C library
        Math::BigInteger        uses an external C library
        Math::Cephes            uses external Cephes C library (no big numbers)
        Math::Cephes::Fraction  fractions via the Cephes library
        Math::GMP               another one using an external C library

Choose wisely.

以下は短いですが不完全なリストです。

        Math::Fraction          9973 / 12967 のような、大きくて無制限の分数
        Math::String            文字列を数値のように扱う
        Math::FixedPrecision    固定精度で計算する
        Math::Currency          通貨の計算用
        Bit::Vector             (C を使って)ビットベクタを速く操作する
        Math::BigIntFast        大きな数のための Bit::Vector のラッパー
        Math::Pari              Pari C ライブラリへのアクセスを提供する
        Math::BigInteger        外部 C ライブラリを使う
        Math::Cephes            外部の Cephes C を使う(大きな数はなし)
        Math::Cephes::Fraction  Cephes ライブラリを使った分数
        Math::GMP               これも外部 C ライブラリを使う

うまく選んでください。

POD ERRORS

Hey! The above document had some coding errors, which are explained below:

Around line 1562:

=end original without matching =begin. (Stack: =begin original; =over)

Around line 1599:

You forgot a '=back' before '=head2'