- 名前
- 概要
- 説明
- 項とリスト演算子 (左方向)
- 矢印演算子
- インクリメントとデクリメント
- 指数演算子
- 単項演算子
- 拘束演算子
- 乗法演算子
- 加法演算子
- シフト演算子
- 名前付き単項演算子
- 比較演算子
- 等価演算子
- ビットごとの AND
- ビットごとの OR と XOR
- C スタイルの論理積
- C スタイルの論理和
- 範囲演算子
- 条件演算子
- 代入演算子
- コンマ演算子
- リスト演算子 (右方向)
- 論理否定
- 論理積
- 論理和と排他論理和
- Perl にない C の演算子
- クォートとクォート風の演算子
- 正規表現のクォート風の演算子
- クォートされた構造のパースに関する詳細
- I/O 演算子
- 定数の畳み込み
- ビット列演算子
- 整数演算
- 浮動小数点演算
- より大きな数
- POD ERRORS
名前¶
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
括弧が無い場合には、print、sort、chmod のようなリスト演算子の 優先順位は、演算子の左側をからすると非常に高く、右側からすると 非常に低く見えます。たとえば、
@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++ と同じように "->" は中置の被参照演算子です。 右側が [...], {...}, (...) のいずれかの形の添字であれば、左側は配列、ハッシュ、 サブルーチンへのハードリファレンスかシンボリックリファレンス (あるいは 技術的には、配列またはハードリファレンスが代入可能であれば ハードリファレンスを保持できる場所) でなければなりません。perlreftut と perlref を参照してください。
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.
単項演算子の "\" はその後に続くものへのリファレンスを生成します。 perlreftut と perlref を参照してください。 この用法も文字列中のバックスラッシュも、後に続くものが展開されるのを 防ぐことになりますが、動作を混同しないでください。
拘束演算子¶
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)
See also "Terms and List Operators (Leftward)".
"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 値安定で、 sed や awk や多くのエディタでの行範囲 (コンマ) 演算子を エミュレートするものとなります。 各々の ".." 演算子がそれぞれに独立して自分の真偽状態を管理します。 はじめは、左被演算子が偽である間、演算全体も偽となっています。 範囲演算子は、いったん左被演算子が真になると、右被演算子が真である間、 真を返すようになります。 右被演算子が偽になると、演算子も偽を返すようになります。 (次に範囲演算子が評価されるまでは、偽とはなりません。 (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