- NAME
- 説明
- 演算子の優先順位と結合性
- 項とリスト演算子 (左方向)
- 矢印演算子
- インクリメントとデクリメント
- 指数演算子
- 単項演算子
- 拘束演算子
- 乗法演算子
- 加法演算子
- シフト演算子
- 名前付き単項演算子
- 比較演算子
- 等価演算子
- ビットごとの AND
- ビットごとの OR と XOR
- C スタイルの論理積
- C スタイルの論理和
- C スタイルの定義性和
- 範囲演算子
- 条件演算子
- 代入演算子
- コンマ演算子
- ヤダヤダ演算子
- リスト演算子 (右方向)
- 論理否定
- 論理積
- 論理和と定義性和と排他論理和
- Perl にない C の演算子
- クォートとクォート風の演算子
- 正規表現のクォート風の演算子
- クォート風演算子
- クォートされた構造のパースに関する詳細
- I/O 演算子
- 定数の畳み込み
- 無実行
- ビット列演算子
- 整数演算
- 浮動小数点演算
- より大きな数
NAME ¶
perlop - Perl operators and precedence
perlop - Perl の演算子と優先順位
説明¶
演算子の優先順位と結合性¶
Operator precedence and associativity work in Perl more or less like they do in mathematics.
Perl での演算子の優先順位と結合性は多かれ少なかれ数学のものと似ています。
Operator precedence means some operators are evaluated before others. For example, in 2 + 4 * 5, the multiplication has higher precedence so 4 * 5 is evaluated first yielding 2 + 20 == 22 and not 6 * 5 == 30.
演算子の優先順位 とは、他の演算子より先に評価される演算子が あるということです。 例えば、2 + 4 * 5 の場合、乗算が高い優先順位を持っているので、 4 * 5 が先に評価され、結果は 6 * 5 == 30 ではなく、 2 + 20 == 22 となります。
Operator associativity defines what happens if a sequence of the same operators is used one after another: whether the evaluator will evaluate the left operations first or the right. For example, in 8 - 4 - 2, subtraction is left associative so Perl evaluates the expression left to right. 8 - 4 is evaluated first making the expression 4 - 2 == 2 and not 8 - 2 == 6.
演算子の結合性 は、同じ演算子が連続して現れた場合に何が起こるかを 定義します: 評価器が左側を先に評価するか右側を先に評価するかです。 例えば、8 - 4 - 2 の場合、減算は左結合なので、Perl は式を左から 右に評価します。 8 - 4 が先に評価されるので、8 - 2 == 6 ではなく 4 - 2 == 2 となります。
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.
# 以下は print を行なう前に exit を評価します:
print($foo, exit); # 明らかにやりたいことではないでしょう。
print $foo, exit; # これでもない。
# 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.
# 以下は 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. The parentheses enclose the argument list for print which is evaluated (printing the result of $foo & 255). Then one is added to the return value of print (usually 1). The result is something like this:
の動作を一目見ただけで判断するのは、難しいでしょう。 かっこは print のために評価される引数リストを囲っています ($foo & 255 の結果が表示されます)。 それから print の返り値 (通常は 1) に 1 が加えられます。 結果は以下のようになります:
1 + 1, "\n"; # Obviously not what you meant.
To do what you meant properly, you must write:
意味したいことを適切に行うには、以下のように書く必要があります:
print(($foo & 255) + 1, "\n");
See "Named Unary Operators" for more discussion of this.
詳しくは、"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 "I/O Operators".
後の方の"Quote and Quote-like Operators"や "I/O Operators"も参照してください。
矢印演算子¶
"->" 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 by one before returning the value, and if placed after, increment or decrement after returning the value.
"++" と "--" は、C の場合と同じように動作します。 つまり、変数の前に置かれれば、値を返す前に変数を 1 インクリメントまたは デクリメントし、後に置かれれば、値を返した後で変数を インクリメントまたはデクリメントします。
$i = 0; $j = 0;
print $i++; # prints 0
print ++$j; # prints 1
Note that just as in C, Perl doesn't define when the variable is incremented or decremented. You just know it will be done sometime before or after the value is returned. This also means that modifying a variable twice in the same statement will lead to undefined behaviour. Avoid statements like:
C と同様、Perl は いつ 変数がインクリメントまたはデクリメントされるかは 定義されません。 値が返される前か後のどこかで行われる、ということだけがわかります。 これは、同じ文である変数を 2 回修正すると、振る舞いが未定義になることを 意味します。 以下のような文は避けてください:
$i = $i ++;
print ++ $i + $i ++;
Perl will not guarantee what the result of the above statements is.
Perl は上記の文の結果について保障しません。
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'
undef is always treated as numeric, and in particular is changed to 0 before incrementing (so that a post-increment of an undef value will return 0 rather than undef).
undef は常に数値として扱われ、特にインクリメントされる前には 0 に 変換されます(従って、undef のポストインクリメント値は undef ではなく 0 になります)。
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 the string "-bareword". If, however, the string begins with a non-alphabetic character (excluding "+" or "-"), Perl will attempt to convert the string to a numeric and the arithmetic negation is performed. If the string cannot be cleanly converted to a numeric, Perl will give the warning Argument "the string" isn't numeric in negation (-) at ....
単項演算子の "-" は被演算子が数値であれば、算術否定を行ないます。 被演算子が識別子ならば、マイナス記号にその識別子をつなげた 文字列が返されます。 これ以外で被演算子の最初の文字がプラスかマイナスのときには、 その記号を逆のものに置き換えた文字列を返します。 この規則の結果、-bareword が文字列 "-bareword" に等価となります。 しかし、文字列が英字以外("+" と "-" を除く)で始まっていると、 Perl は文字列を数値に変換しようとし、それから算術否定が実行されます。 もし文字列が明確に数値に変換できない場合、Perl は Argument "the string" isn't numeric in negation (-) at ... という 警告を出します。
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 to 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 and perlretut for examples using these operators.
二項演算子の "=~" は、スカラ式をパターンマッチに拘束します。 デフォルトで $_ の文字列を検索したり、変更したりする演算があります。 この演算子は、そのような演算を他の文字列に対して行なわせるようにするものです。 右引数は、検索パターン、置換、文字変換のいずれかです。 左引数は、デフォルトの $_ の代わりに検索、置換、文字変換の対象となるものです。 スカラコンテキストで使うと、返り値は一般的に演算の結果が成功したか否かです。 リストコンテキストでの振る舞いは演算子に依存します。 詳しくは "Regexp Quote-Like Operators" を、これらの演算子を使った 例については perlretut を参照して下さい。
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. Note that this means that its contents will be interpolated twice, so
右引数が検索パターン、置換、文字変換ではなく、式であれば、 それは実行時に決まる検索パターンと解釈されます。 これは、内容が 2 回展開されることを意味することに注意してください; つまり:
'\\' =~ q'\\';
is not ok, as the regex engine will end up trying to compile the pattern \, which it will consider a syntax error.
は正しくありません; 正規表現エンジンは最終的にパターン \ を コンパイルしようとして、これは文法エラーと考えるからです。
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 "%" is the modulo operator, which computes the division remainder of its first argument with respect to its second argument. Given integer operands $a and $b: If $b is positive, then $a % $b is $a minus the largest multiple of $b less than or equal to $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). If the operands $a and $b are floating point values and the absolute value of $b (that is abs($b)) is less than (UV_MAX + 1), only the integer portion of $a and $b will be used in the operation (Note: here UV_MAX means the maximum of the unsigned integer type). If the absolute value of the right operand (abs($b)) is greater than or equal to (UV_MAX + 1), "%" computes the floating-point remainder $r in the equation ($r = $a - $i*$b) where $i is a certain integer that makes $r have the same sign as the right operand $b (not as the left operand $a like C function fmod()) and the absolute value less than that of $b. Note that when use integer is in scope, "%" gives you direct access to the modulo operator as implemented by your C compiler. This operator is not as well defined for negative operands, but it will execute faster.
二項演算子の "%" は剰余演算子で、一つ目の引数を二つ目の引数で割ったときの 余りを返します。 $a と $b の二つの整数の被演算子を取ったとすると: $b が正の場合、$a % $b は、$a から $a 以下の最大の $b の倍数を引いた値です。 $b が負の場合、$a % $b は、$a から $a を下回らない 最小の $b の倍数を引いた値です。(従って結果はゼロ以下になります。) オペランド $a と $b が浮動小数点数で、$b の絶対値 (つまり abs($b)) が (UV_MAX + 1) より小さい場合、 $a と $b の整数部のみが操作で使われます (注意: ここで UV_MAX は符号なし整数の最大値を意味します)。 右オペランドの絶対値 (abs($b)) が (UV_MAX + 1) 以上の場合、 "%" は、($r = $a - $i*$b) となる浮動小数点剰余 $r を計算します; ここで $i は、$r が右オペランド $b と同じ符号 (C の 関数 fmod() のように左オペランド $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 or is a list formed by qw/STRING/, it repeats the list. If the right operand is zero or negative, it returns an empty string or an empty list, depending on the context.
二項演算子の "x" は繰り返し演算子です。 スカラコンテキストまたは左辺値が括弧で括られていない場合は、 左被演算子を右被演算子に示す数だけ繰り返したもので構成される 文字列を返します。 リストコンテキストでは、左被演算子が括弧で括られているか、qw/STRING の 形のリストの場合、リストを繰り返します。 右オペランドが 0 か負数の場合、コンテキストによって、空文字列か空リストを 返します。
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" も参照して下さい。)
Note that both "<<" and ">>" in Perl are implemented directly using "<<" and ">>" in C. If use integer (see "Integer Arithmetic") is in force then signed C integers are used, else unsigned C integers are used. Either way, the implementation isn't going to generate results larger than the size of the integer type Perl was built with (32 bits or 64 bits).
Perl での "<<" と ">>" は C での "<<" と ">>" を直接利用して 実装されていることに注意してください。 use integer ("Integer Arithmetic" を参照してください)が有効な場合、 C の符号付き整数が使われ、そうでない場合は C の符号なし整数が使われます。 どちらの場合も、この実装は Perl がビルドされた整数型のサイズ(32 ビットか 64 ビット)よりも大きい結果を生成することはありません。
The result of overflowing the range of the integers is undefined because it is undefined also in C. In other words, using 32-bit integers, 1 << 32 is undefined. Shifting by a negative number of bits is also undefined.
整数の範囲をオーバーフローした場合の結果は、C でも未定義なので、未定義です。 言い換えると、32 ビット整数を使っているとき、1 << 32 は未定義です。 シフトするビット数として負の数を指定した場合も未定義です。
名前付き単項演算子¶
The various named unary operators are treated as functions with one argument, with optional parentheses.
さまざまな名前付き単項演算子が、引数を 1 つ持ち、括弧が省略可能な、 関数として扱われます。
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)
Regarding precedence, the filetest operators, like -f, -M, etc. are treated like named unary operators, but they don't follow this functional parenthesis rule. That means, for example, that -f($file).".bak" is equivalent to -f "$file.bak".
優先順位に関して、-f や -M のようなファイルテスト演算子は、名前付き 単項演算子として扱われますが、この関数のかっこルールは適用されません。 これは、例えば -f($file).".bak" は -f "$file.bak" と等価であることを 意味します。
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 を返します。
Binary "~~" does a smart match between its arguments. Smart matching is described in "Smart matching in detail" in perlsyn.
二項演算子の "~~" はスマートマッチングとして働きます。 スマートマッチングについては "Smart matching in detail" in perlsyn で 述べられています。
"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 operands ANDed together bit by bit. (See also "Integer Arithmetic" and "Bitwise String Operators".)
二項演算子の "&" は、両オペランドのビットごとに論理積をとって、 その結果を返します。 ("Integer Arithmetic" と "Bitwise String Operators" も参照して下さい。)
Note that "&" has lower priority than relational operators, so for example the brackets are essential in a test like
"&" は関係演算子より優先順位が低いので、例えば以下のようなテストでは、 かっこが重要です:
print "Even\n" if ($x & 1) == 0;
ビットごとの OR と XOR¶
Binary "|" returns its operands ORed together bit by bit. (See also "Integer Arithmetic" and "Bitwise String Operators".)
二項演算子の "|" は、両オペランドのビットごとに論理和をとって、 その結果を返します。 ("Integer Arithmetic" と "Bitwise String Operators" も参照して下さい。)
Binary "^" returns its operands XORed together bit by bit. (See also "Integer Arithmetic" and "Bitwise String Operators".)
二項演算子の "^" は、両オペランドのビットごとに排他論理和をとって、 その結果を返します。 ("Integer Arithmetic" と "Bitwise String Operators" も参照して下さい。)
Note that "|" and "^" have lower priority than relational operators, so for example the brackets are essential in a test like
"|" と "^" は関係演算子より優先順位が低いので、例えば以下のような テストでは、かっこが重要です:
print "false\n" if (8 | 2) != 10;
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.
二項演算子の "||" は、短絡の論理和演算を行ないます。 つまり、左被演算子が真であれば、右被演算子は評価さえ 行なわれないということです。 評価される場合には、スカラーかリストかというコンテキストは、 右被演算子にも及びます。
C スタイルの定義性和¶
Although it has no direct equivalent in C, Perl's // operator is related to its C-style or. In fact, it's exactly the same as ||, except that it tests the left hand side's definedness instead of its truth. Thus, $a // $b is similar to defined($a) || $b (except that it returns the value of $a rather than the value of defined($a)) and is exactly equivalent to defined($a) ? $a : $b. This is very useful for providing default values for variables. If you actually want to test if at least one of $a and $b is defined, use defined($a // $b).
C では直接等価なものはありませんが、Perl の // 演算子は C スタイル 論理和に関連しています。 実際、左辺の真偽ではなく定義されているかを判定することを除けば || と同じです。 したがって $a // $b は defined($a) || $b と似ていて (ただし、 defined($a) ではなく $a の値を返します)、defined($a) ? $a : $b と 完全に等価です。 これは、変数に対するデフォルト値を設定するのにとても有用です。 実際に、$a と $b の少なくとも片方が定義されているかを判定したいなら、 defined($a // $b) を使ってください。
The ||, // and && operators return the last value evaluated (unlike C's || and &&, which return 0 or 1). Thus, a reasonably portable way to find out the home directory might be:
||, //, && 演算子は、(C のように 単に 0 や 1 を返すのではなく) 最後に評価された値を返します。 これにより、かなり一般的に使えるホームディレクトリを探す方法は:
$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 the 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 a list 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 list. 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
}
The range operator also works on strings, using the magical auto-increment, see below.
範囲演算子は、マジカル自動インクリメントを使うことで文字列でも動作します。 以下を参照してください。
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, even across calls to a subroutine that contains it. 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 until 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.
右被演算子は、演算子の状態が「偽」である間は評価されることがなく、 左被演算子は、演算子の状態が「真」である間は評価されることがありません。 優先順位は、|| と && の少し下です。 偽としては空文字列が返され、 真としては (1 から始まる) 順に並んだ数値が返されます。 この通し番号は、新たに範囲が始まるごとにリセットされます。 範囲の最後の数字には、文字列 "E0" が末尾につけられます。 これは、数値としては何の影響もありませんが、範囲の終わりで何か特別なことを したい場合に、目印として使うことができます。 範囲の始まりで何かしたい場合には、通し番号が 1 よりも大きくなるのを 待っていればよいでしょう。
If either operand of scalar ".." is a constant expression, that operand is considered true if it is equal (==) to the current input line number (the $. variable).
スカラの ".." の被演算子が定数表現であるときは、その被演算子は暗黙に、 現在の入力行番号(変数 $.) と等しい(==) 場合に真となります。
To be pedantic, the comparison is actually int(EXPR) == int(EXPR), but that is only an issue if you use a floating point expression; when implicitly using $. as described in the previous paragraph, the comparison is int(EXPR) == int($.) which is only an issue when $. is set to a floating point value and you are not reading from a file. Furthermore, "span" .. "spat" or 2.18 .. 3.14 will not do what you want in scalar context because each of the operands are evaluated using their integer representation.
とても細かい話をすると、比較は実際には int(EXPR) == int(EXPR) ですが、 これは浮動小数点数を使うときにだけ問題になります; 前の段落で記述したように 明示的に $. を使ったとき、比較は int(EXPR) == int($.) となり、 $. に浮動小数点数がセットされ、ファイルから読み込みを行わない場合にのみ 問題になります。 さらに、"span" .. "spat" や 2.18 .. 3.14 は、それぞれのオペランドが 整数表現を使って評価されるため、スカラコンテキストでは望みどおりの結果に なりません。
Examples:
例:
As a scalar operator:
スカラ演算子として:
if (101 .. 200) { print; } # print 2nd hundred lines, short for
# if ($. == 101 .. $. == 200) { print; }
next LINE if (1 .. /^$/); # skip header lines, short for
# next LINE if ($. == 1 .. /^$/);
# (typically in a loop labeled LINE)
s/^/> / if (/^$/ .. eof()); # quote body
# parse mail messages
while (<>) {
$in_header = 1 .. /^$/;
$in_body = /^$/ .. eof;
if ($in_header) {
# do something
} else { # in body
# do something else
}
} continue {
close ARGV if eof; # reset $. each file
}
Here's a simple example to illustrate the difference between the two range operators:
以下は二つの範囲演算子の違いを示す単純な例です:
@lines = (" - Foo",
"01 - Bar",
"1 - Baz",
" - Quux");
foreach (@lines) {
if (/0/ .. /1/) {
print "$_\n";
}
}
This program will print only the line containing "Bar". If the range operator is changed to ..., it will also print the "Baz" line.
このプログラムは "Bar" を含む行だけを表示します。 範囲演算子を ... に変更すると、"Baz" の行も表示します。
And now some examples 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 English 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.
とすれば、0 付きの日付が得られます。
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.
マジカルインクリメントによって得られる値の中に指定した最終値に ちょうど一致するものが見つからないような場合には、 マジカルインクリメントによって得られる次の値の文字列長が、 最終値として指定した値のものより長くなるまでインクリメントが続けられます。
If the initial value specified isn't part of a magical increment sequence (that is, a non-empty string matching "/^[a-zA-Z]*[0-9]*\z/"), only the initial value will be returned. So the following will only return an alpha:
指定された初期値がマジカルインクリメント処理の一部でない場合 (つまり、"/^[a-zA-Z]*[0-9]*\z/" にマッチングする、空でない文字列の場合)、 初期値のみが返されます。 従って、以下はαのみを返します:
use charnames 'greek';
my @greek_small = ("\N{alpha}" .. "\N{omega}");
To get lower-case greek letters, use this instead:
小文字のギリシャ文字を得るためには、代わりに以下のようにしてください:
my @greek_small = map { chr } ( ord("\N{alpha}") .. ord("\N{omega}") );
Because each operand is evaluated in integer form, 2.18 .. 3.14 will return two elements in list context.
それぞれのオペランドは整数の形で評価されるので、2.18 .. 3.14 は リストコンテキストでは二つの要素を返します。
@list = (2.18 .. 3.14); # same as @list = (2 .. 3);
条件演算子¶
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. These arguments are also evaluated from left to right.
リストコンテキストでは、これは単にリスト引数の区切り文字で、 双方の引数をそのリストに挿入する働きがあります。 これらの引数も左から右に評価されます。
The => operator is a synonym for the comma except that it causes its left operand to be interpreted as a string if it begins with a letter or underscore and is composed only of letters, digits and underscores. This includes operands that might otherwise be interpreted as operators, constants, single number v-strings or function calls. If in doubt about this behaviour, the left operand can be quoted explicitly.
=> 演算子はコンマ演算子の同義語ですが、 もし左オペランドが文字か下線で始まっていて、かつ文字、数字、下線でのみ 構成されている場合、これを文字列として扱うという効果もあります。 これには他の場所では演算子、定数、v-文字列、関数呼び出しとして扱われる オペランドを含みます。 この振る舞いについて迷うことがあるなら、左オペランドを明示的に クォートすることも出来ます。
Otherwise, the => operator behaves exactly as the comma operator or list argument separator, according to context.
さもなければ、=> 演算子はコンテキストによって、 カンマ演算子かリスト引数の区切り文字と全く同様に振る舞います。
For example:
例えば:
use constant FOO => "something";
my %h = ( FOO => 23 );
is equivalent to:
は、以下と等価です:
my %h = ("FOO", 23);
It is NOT:
これは 違います:
my %h = ("something", 23);
The => operator is helpful in documenting the correspondence between keys and values in hashes, and other paired elements in lists.
=> 演算子は、ハッシュのキーと値や、その他のリスト中の組となる 要素の関係を表現するのに便利です。
%hash = ( $key => $value );
login( $username => $password );
ヤダヤダ演算子¶
The yada yada operator (noted ...) is a placeholder for code. Perl parses it without error, but when you try to execute a yada yada, it throws an exception with the text Unimplemented:
(... と書く) ヤダヤダ演算子はコードのためのプレースホルダです。 Perl はこれをエラーを出すことなくパースしますが、ヤダヤダを 実行しようとすると、Unimplemented の文章と共に例外を発生させます:
sub unimplemented { ... }
eval { unimplemented() };
if( $@ eq 'Unimplemented' ) {
print "I found the yada yada!\n";
}
You can only use the yada yada to stand in for a complete statement. These examples of the yada yada work:
ヤダヤダは完全な文の代わりにのみ使えます。 以下の例のヤダヤダは動作します:
{ ... }
sub foo { ... }
...;
eval { ... };
sub foo {
my( $self ) = shift;
...;
}
do { my $n; ...; print 'Hurrah!' };
The yada yada cannot stand in for an expression that is part of a larger statement since the ... is also the three-dot version of the range operator (see "Range Operators"). These examples of the yada yada are still syntax errors:
... は範囲演算子("Range Operators" を参照してください)の 3 ドット版でも あるので、より大きな文の一部の式としては使えません。 以下の例のヤダヤダは文法エラーになります:
print ...;
open my($fh), '>', '/dev/passwd' or ...;
if( $condition && ... ) { print "Hello\n" };
There are some cases where Perl can't immediately tell the difference between an expression and a statement. For instance, the syntax for a block and an anonymous hash reference constructor look the same unless there's something in the braces that give Perl a hint. The yada yada is a syntax error if Perl doesn't guess that the { ... } is a block. In that case, it doesn't think the ... is the yada yada because it's expecting an expression instead of a statement:
式と文との違いをすぐに説明できない場合があります。 例えば、ブロックと無名ハッシュリファレンスのコンストラクタは、 Perl にヒントを与える中かっこがなければ同じに見えます。 ヤダヤダは Perl が { ... } をブロックと判断できなかった場合は 文法エラーとなります。 この場合、文ではなく式と推測するので、... はヤダヤダとは 判断されません:
my @transformed = map { ... } @input; # syntax error
You can use a ; inside your block to denote that the { ... } is a block and not a hash reference constructor. Now the yada yada works:
{ ... } がブロックであって、ハッシュリファレンスのコンストラクタでは ないことを示すためにブロックの中で ; を使えます。 これでヤダヤダは動作します:
my @transformed = map {; ... } @input; # ; disambiguates
my @transformed = map { ...; } @input; # ; disambiguates
リスト演算子 (右方向)¶
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*
qw{} Word list no
// m{} Pattern match yes*
qr{} Pattern yes*
s{}{} Substitution yes*
tr{}{} Transliteration no (but see below)
<<EOF here-doc yes*
* unless the delimiter is ''.
通常記法 汎用記法 意味 展開
=================================================
'' q{} リテラル 不可
"" qq{} リテラル 可
`` qx{} コマンド 可 *
qw{} 単語リスト 不可
// m{} パターンマッチ 可 *
qr{} パターン 可 *
s{}{} 置換 可 *
tr{}{} 変換 不可 (但し以下を参照のこと)
<<EOF ヒアドキュメント 可 *
* '' がデリミタでない場合のみ
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 (from CPAN, and starting from Perl 5.8 part of the standard distribution) is able to do this properly.
これは文法エラーとなります。 Text::Balanced モジュール(CPAN から、または Perl 5.8 からは標準配布の 一部です)はこれを適切に行います。
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.
The following escape sequences are available in constructs that interpolate and in transliterations.
以下のエスケープシーケンスが展開と文字変換の構文で利用可能です。
\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 (example: ESC)
\x1b hex char (example: ESC)
\x{263a} wide hex char (example: SMILEY)
\c[ control char (example: ESC)
\N{name} named Unicode character
\N{U+263D} Unicode character (example: FIRST QUARTER MOON)