perlop > 5.10.1 との差分

perlop 5.10.1 と 5.14.1 の差分

11
22=encoding euc-jp
33
44=head1 NAME
55X<operator>
66
77=begin original
88
99perlop - Perl operators and precedence
1010
1111=end original
1212
1313perlop - Perl の演算子と優先順位
1414
1515=head1 DESCRIPTION
1616
1717=head2 Operator Precedence and Associativity
1818X<operator, precedence> X<precedence> X<associativity>
1919
2020(演算子の優先順位と結合性)
2121
2222=begin original
2323
2424Operator precedence and associativity work in Perl more or less like
2525they do in mathematics.
2626
2727=end original
2828
2929Perl での演算子の優先順位と結合性は多かれ少なかれ数学のものと似ています。
3030
3131=begin original
3232
3333I<Operator precedence> means some operators are evaluated before
3434others. For example, in C<2 + 4 * 5>, the multiplication has higher
3535precedence so C<4 * 5> is evaluated first yielding C<2 + 20 ==
363622> and not C<6 * 5 == 30>.
3737
3838=end original
3939
4040I<演算子の優先順位> とは、他の演算子より先に評価される演算子が
4141あるということです。
4242例えば、C<2 + 4 * 5> の場合、乗算が高い優先順位を持っているので、
4343C<4 * 5> が先に評価され、結果は C<6 * 5 == 30> ではなく、
4444C<2 + 20 == 22> となります。
4545
4646=begin original
4747
4848I<Operator associativity> defines what happens if a sequence of the
4949same operators is used one after another: whether the evaluator will
5050evaluate the left operations first or the right. For example, in C<8
5151- 4 - 2>, subtraction is left associative so Perl evaluates the
5252expression left to right. C<8 - 4> is evaluated first making the
5353expression C<4 - 2 == 2> and not C<8 - 2 == 6>.
5454
5555=end original
5656
5757I<演算子の結合性> は、同じ演算子が連続して現れた場合に何が起こるかを
5858定義します: 評価器が左側を先に評価するか右側を先に評価するかです。
5959例えば、C<8 - 4 - 2> の場合、減算は左結合なので、Perl は式を左から
6060右に評価します。
6161C<8 - 4> が先に評価されるので、C<8 - 2 == 6> ではなく
6262C<4 - 2 == 2> となります。
6363
6464=begin original
6565
6666Perl operators have the following associativity and precedence,
6767listed from highest precedence to lowest. Operators borrowed from
6868C keep the same precedence relationship with each other, even where
6969C's precedence is slightly screwy. (This makes learning Perl easier
7070for C folks.) With very few exceptions, these all operate on scalar
7171values only, not array values.
7272
7373=end original
7474
7575Perl の演算子には、以下のような結合性と優先順位 (高い優先順位から
7676低いものへ並べている) があります。
7777C から持ってきた演算子の優先順位は、C での優先順位が多少おかしくても、
7878そのままにしてあります。
7979(これによって、C を使っている方が Perl に移りやすくなっています。)
8080ごく僅かな例外を別として、全ての演算子はスカラ値のみを持ち、
8181配列値を持ちません。
8282
8383=begin original
8484
8585 left terms and list operators (leftward)
8686 left ->
8787 nonassoc ++ --
8888 right **
8989 right ! ~ \ and unary + and -
9090 left =~ !~
9191 left * / % x
9292 left + - .
9393 left << >>
9494 nonassoc named unary operators
9595 nonassoc < > <= >= lt gt le ge
9696 nonassoc == != <=> eq ne cmp ~~
9797 left &
9898 left | ^
9999 left &&
100100 left || //
101101 nonassoc .. ...
102102 right ?:
103103 right = += -= *= etc.
104104 left , =>
105105 nonassoc list operators (rightward)
106106 right not
107107 left and
108108 left or xor
109109
110110=end original
111111
112112 左結合 項 リスト演算子 (左方向に対して)
113113 左結合 ->
114114 非結合 ++ --
115115 右結合 **
116116 右結合 ! ~ \ 単項の+ 単項の-
117117 左結合 =~ !~
118118 左結合 * / % x
119119 左結合 + - .
120120 左結合 << >>
121121 非結合 名前付き単項演算子
122122 非結合 < > <= >= lt gt le ge
123123 非結合 == != <=> eq ne cmp ~~
124124 左結合 &
125125 左結合 | ^
126126 左結合 &&
127127 左結合 || //
128128 非結合 .. ...
129129 右結合 ?:
130130 右結合 = += -= *= などの代入演算子
131131 左結合 , =>
132132 非結合 リスト演算子 (右方向に対して)
133133 右結合 not
134134 左結合 and
135135 左結合 or xor
136136
137137=begin original
138138
139139In the following sections, these operators are covered in precedence order.
140140
141141=end original
142142
143143以下の章では、演算子は優先順位の順に記述されています。
144144
145145=begin original
146146
147147Many operators can be overloaded for objects. See L<overload>.
148148
149149=end original
150150
151151多くの演算子はオブジェクトでオーバーロードできます。
152152L<overload> を参照して下さい。
153153
154154=head2 Terms and List Operators (Leftward)
155155X<list operator> X<operator, list> X<term>
156156
157157(項とリスト演算子 (左方向))
158158
159159=begin original
160160
161161A TERM has the highest precedence in Perl. They include variables,
162162quote and quote-like operators, any expression in parentheses,
163163and any function whose arguments are parenthesized. Actually, there
164164aren't really functions in this sense, just list operators and unary
165165operators behaving as functions because you put parentheses around
166166the arguments. These are all documented in L<perlfunc>.
167167
168168=end original
169169
170170「項」は Perl でもっとも優先順位が高いものです。
171171これには、変数、クォートとクォート的な演算子、括弧で括った任意の式、
172172引数を括弧で括った任意の関数が含まれます。
173173実際には、この意味では本当の関数はなく、リスト演算子と関数のように働く
174174単項演算子が、引数を括弧で括るためそのように見えます。
175175これらはすべて L<perlfunc> に記述しています。
176176
177177=begin original
178178
179179If any list operator (print(), etc.) or any unary operator (chdir(), etc.)
180180is followed by a left parenthesis as the next token, the operator and
181181arguments within parentheses are taken to be of highest precedence,
182182just like a normal function call.
183183
184184=end original
185185
186もし、リスト演算子 (print() など) や単項演算子 (chdir() など)
186リスト演算子 (print() など) や単項演算子 (chdir() など) は、
187名前後に開き括弧が続く場合には、その演算子と括弧内の引数は、
187すべて次トークンとして開き括弧が続く、その演算子と括弧内の引数は、
188通常の関数呼び出しのようにもっとも高い優先順位で処理されます。
188通常の関数呼び出しのようにもっとも高い優先順位として扱われます。
189189
190190=begin original
191191
192192In the absence of parentheses, the precedence of list operators such as
193193C<print>, C<sort>, or C<chmod> is either very high or very low depending on
194194whether you are looking at the left side or the right side of the operator.
195195For example, in
196196
197197=end original
198198
199199括弧が無い場合には、C<print>、C<sort>、C<chmod> のようなリスト演算子の
200200優先順位は、演算子の左側をからすると非常に高く、右側からすると
201201非常に低く見えます。たとえば、
202202
203203 @ary = (1, 3, sort 4, 2);
204204 print @ary; # prints 1324
205205
206206=begin original
207207
208208the commas on the right of the sort are evaluated before the sort,
209209but the commas on the left are evaluated after. In other words,
210210list operators tend to gobble up all arguments that follow, and
211211then act like a simple TERM with regard to the preceding expression.
212212Be careful with parentheses:
213213
214214=end original
215215
216216では、sort の右のコンマは sort よりも前に評価されます (右側から見ると
217217sort の優先順位が低い) が、左側のコンマは sort のあとに評価されます
218218(左側から見ると sort の方が優先順位が高くなっている)。
219219言い方を変えると、リスト演算子は自分の後にある引数をすべて使って処理を行ない、
220220その結果を自分の前の式に対する「項」であるかのように見せるということです。
221221ただし、括弧には気を付けないといけません:
222222
223223=begin original
224224
225225 # These evaluate exit before doing the print:
226226 print($foo, exit); # Obviously not what you want.
227227 print $foo, exit; # Nor is this.
228228
229229=end original
230230
231231 # 以下は print を行なう前に exit を評価します:
232232 print($foo, exit); # 明らかにやりたいことではないでしょう。
233233 print $foo, exit; # これでもない。
234234
235235=begin original
236236
237237 # These do the print before evaluating exit:
238238 (print $foo), exit; # This is what you want.
239239 print($foo), exit; # Or this.
240240 print ($foo), exit; # Or even this.
241241
242242=end original
243243
244244 # 以下は exit を評価する前に print を行ないます:
245245 (print $foo), exit; # これがしたかった。
246246 print($foo), exit; # これでもいい。
247247 print ($foo), exit; # これも OK。
248248
249249=begin original
250250
251251Also note that
252252
253253=end original
254254
255255また、
256256
257257 print ($foo & 255) + 1, "\n";
258258
259259=begin original
260260
261261probably doesn't do what you expect at first glance. The parentheses
262262enclose the argument list for C<print> which is evaluated (printing
263263the result of C<$foo & 255>). Then one is added to the return value
264264of C<print> (usually 1). The result is something like this:
265265
266266=end original
267267
268268の動作を一目見ただけで判断するのは、難しいでしょう。
269269かっこは C<print> のために評価される引数リストを囲っています
270270(C<$foo & 255> の結果が表示されます)。
271271それから C<print> の返り値 (通常は 1) に 1 が加えられます。
272272結果は以下のようになります:
273273
274=begin original
275
274276 1 + 1, "\n"; # Obviously not what you meant.
275277
278=end original
279
280 1 + 1, "\n"; # 明らかにやりたいことではないでしょう。
281
276282=begin original
277283
278284To do what you meant properly, you must write:
279285
280286=end original
281287
282288意味したいことを適切に行うには、以下のように書く必要があります:
283289
284290 print(($foo & 255) + 1, "\n");
285291
286292=begin original
287293
288294See L<Named Unary Operators> for more discussion of this.
289295
290296=end original
291297
292298詳しくは、L<Named Unary Operators> を参照してください。
293299
294300=begin original
295301
296302Also parsed as terms are the C<do {}> and C<eval {}> constructs, as
297303well as subroutine and method calls, and the anonymous
298304constructors C<[]> and C<{}>.
299305
300306=end original
301307
302308この他に「項」として解析されるものには、C<do {}> や C<eval {}> の
303309構成、サブルーティンやメソッドの呼び出し、無名のコンストラクタ
304310C<[]> と C<{}> があります。
305311
306312=begin original
307313
308314See also L<Quote and Quote-like Operators> toward the end of this section,
309315as well as L</"I/O Operators">.
310316
311317=end original
312318
313319後の方のL<Quote and Quote-like Operators>や
314320L</"I/O Operators">も参照してください。
315321
316322=head2 The Arrow Operator
317323X<arrow> X<dereference> X<< -> >>
318324
319325(矢印演算子)
320326
321327=begin original
322328
323329"C<< -> >>" is an infix dereference operator, just as it is in C
324330and C++. If the right side is either a C<[...]>, C<{...}>, or a
325331C<(...)> subscript, then the left side must be either a hard or
326332symbolic reference to an array, a hash, or a subroutine respectively.
327333(Or technically speaking, a location capable of holding a hard
328334reference, if it's an array or hash reference being used for
329335assignment.) See L<perlreftut> and L<perlref>.
330336
331337=end original
332338
333339C や C++ と同じように "C<< -> >>" は中置の被参照演算子です。
334340右側が C<[...]>, C<{...}>,
335341C<(...)> のいずれかの形の添字であれば、左側は配列、ハッシュ、
336サブルーチンへのハードリファレンスかシンボリックリファレンス (あるいは
342サブルーチンへのハードリファレンスかシンボリックリファレンスでなければなりません。
337技術的には、配列またはハードリファレンスが代入可能であれば
343(あるいは技術的には、配列またはハードリファレンスが代入可能であれば
338ハードリファレンスを保持できる場所)
344ハードリファレンスを保持できる場所です。)
339でなければなりません。L<perlreftut> と L<perlref> を参照してください。
345L<perlreftut> と L<perlref> を参照してください。
340346
341347=begin original
342348
343349Otherwise, the right side is a method name or a simple scalar
344350variable containing either the method name or a subroutine reference,
345351and the left side must be either an object (a blessed reference)
346352or a class name (that is, a package name). See L<perlobj>.
347353
348354=end original
349355
350356そうでなければ、右側はメソッド名かサブルーチンのリファレンスを持った
351357単純スカラ変数で、左側はオブジェクト (bless されたリファレンス) か
352358クラス名でなければなりません。
353359L<perlobj> を参照してください。
354360
355361=head2 Auto-increment and Auto-decrement
356362X<increment> X<auto-increment> X<++> X<decrement> X<auto-decrement> X<-->
357363
358364(インクリメントとデクリメント)
359365
360366=begin original
361367
362368"++" and "--" work as in C. That is, if placed before a variable,
363369they increment or decrement the variable by one before returning the
364370value, and if placed after, increment or decrement after returning the
365371value.
366372
367373=end original
368374
369375"++" と "--" は、C の場合と同じように動作します。
370376つまり、変数の前に置かれれば、値を返す前に変数を 1 インクリメントまたは
371377デクリメントし、後に置かれれば、値を返した後で変数を
372378インクリメントまたはデクリメントします。
373379
374380 $i = 0; $j = 0;
375381 print $i++; # prints 0
376382 print ++$j; # prints 1
377383
378384=begin original
379385
380386Note that just as in C, Perl doesn't define B<when> the variable is
381387incremented or decremented. You just know it will be done sometime
382388before or after the value is returned. This also means that modifying
383a variable twice in the same statement will lead to undefined behaviour.
389a variable twice in the same statement will lead to undefined behavior.
384390Avoid statements like:
385391
386392=end original
387393
388394C と同様、Perl は B<いつ> 変数がインクリメントまたはデクリメントされるかは
389395定義されません。
390396値が返される前か後のどこかで行われる、ということだけがわかります。
391397これは、同じ文である変数を 2 回修正すると、振る舞いが未定義になることを
392398意味します。
393399以下のような文は避けてください:
394400
395401 $i = $i ++;
396402 print ++ $i + $i ++;
397403
398404=begin original
399405
400406Perl will not guarantee what the result of the above statements is.
401407
402408=end original
403409
404410Perl は上記の文の結果について保障しません。
405411
406412=begin original
407413
408414The auto-increment operator has a little extra builtin magic to it. If
409415you increment a variable that is numeric, or that has ever been used in
410416a numeric context, you get a normal increment. If, however, the
411417variable has been used in only string contexts since it was set, and
412418has a value that is not the empty string and matches the pattern
413419C</^[a-zA-Z]*[0-9]*\z/>, the increment is done as a string, preserving each
414420character within its range, with carry:
415421
416422=end original
417423
418424インクリメント演算子には、ちょっと風変わりな機能が組み込まれています。
419425数値が入った変数や、数値の文脈で使われてきた変数を
420426インクリメントする場合には、通常のインクリメントとして動作します。
421427しかし、その変数が設定されてからずっと文字列の文脈で
422428しか使われていなくて、空文字列でなく、 C</^[a-zA-Z]*[0-9]*\z/> にマッチする
423429値を持っているときには、個々の文字の範囲を保ちながら桁あげを行なって、
424430文字列としてインクリメントが行なわれます (マジカルインクリメントと呼ばれます):
425431
426 print ++($foo = '99'); # prints '100'
432 print ++($foo = "99"); # prints "100"
427 print ++($foo = 'a0'); # prints 'a1'
433 print ++($foo = "a0"); # prints "a1"
428 print ++($foo = 'Az'); # prints 'Ba'
434 print ++($foo = "Az"); # prints "Ba"
429 print ++($foo = 'zz'); # prints 'aaa'
435 print ++($foo = "zz"); # prints "aaa"
430436
431437=begin original
432438
433439C<undef> is always treated as numeric, and in particular is changed
434440to C<0> before incrementing (so that a post-increment of an undef value
435441will return C<0> rather than C<undef>).
436442
437443=end original
438444
439445C<undef> は常に数値として扱われ、特にインクリメントされる前には C<0> に
440446変換されます(従って、undef のポストインクリメント値は C<undef> ではなく
441447C<0> になります)。
442448
443449=begin original
444450
445451The auto-decrement operator is not magical.
446452
447453=end original
448454
449455デクリメント演算子には、マジカルなものはありません。
450456
451457=head2 Exponentiation
452458X<**> X<exponentiation> X<power>
453459
454460(指数演算子)
455461
456462=begin original
457463
458464Binary "**" is the exponentiation operator. It binds even more
459465tightly than unary minus, so -2**4 is -(2**4), not (-2)**4. (This is
460466implemented using C's pow(3) function, which actually works on doubles
461467internally.)
462468
463469=end original
464470
465471二項演算子の "**" は指数演算子です。
466472この演算子は、単項のマイナスよりも結合が強い演算子で、
467473-2**4 は (-2)**4 ではなく、-(2**4) と解釈されます。
468474(これは C の pow(3) を使って実装されていますので、
469475内部的には double で動作します。)
470476
471477=head2 Symbolic Unary Operators
472478X<unary operator> X<operator, unary>
473479
474480(単項演算子)
475481
476482=begin original
477483
478484Unary "!" performs logical negation, i.e., "not". See also C<not> for a lower
479485precedence version of this.
480486X<!>
481487
482488=end original
483489
484単項演算子の "!" は論理否定を行ないます。
490単項演算子の "!" は論理否定を行ないます; つまり「not」ということです
485つまり 「not」 ということです。
486491この演算子の優先順位を低くしたものとして、C<not> が用意されています。
487492X<!>
488493
489494=begin original
490495
491Unary "-" performs arithmetic negation if the operand is numeric. If
496Unary "-" performs arithmetic negation if the operand is numeric,
492the operand is an identifier, a string consisting of a minus sign
497including any string that looks like a number. If the operand is
493concatenated with the identifier is returned. Otherwise, if the string
498an identifier, a string consisting of a minus sign concatenated
494starts with a plus or minus, a string starting with the opposite sign
499with the identifier is returned. Otherwise, if the string starts
495is returned. One effect of these rules is that -bareword is equivalent
500with a plus or minus, a string starting with the opposite sign is
501returned. One effect of these rules is that -bareword is equivalent
496502to the string "-bareword". If, however, the string begins with a
497503non-alphabetic character (excluding "+" or "-"), Perl will attempt to convert
498504the string to a numeric and the arithmetic negation is performed. If the
499505string cannot be cleanly converted to a numeric, Perl will give the warning
500506B<Argument "the string" isn't numeric in negation (-) at ...>.
501507X<-> X<negation, arithmetic>
502508
503509=end original
504510
505単項演算子の "-" は被演算子が数値であれば、算術否定を行ないます。
511単項演算子の "-" は被演算子が数値または数値に見える文字列であれば、
512算術否定を行ないます。
506513被演算子が識別子ならば、マイナス記号にその識別子をつなげた
507514文字列が返されます。
508515これ以外で被演算子の最初の文字がプラスかマイナスのときには、
509516その記号を逆のものに置き換えた文字列を返します。
510517この規則の結果、-bareword が文字列 "-bareword" に等価となります。
511518しかし、文字列が英字以外("+" と "-" を除く)で始まっていると、
512519Perl は文字列を数値に変換しようとし、それから算術否定が実行されます。
513520もし文字列が明確に数値に変換できない場合、Perl は
514521B<Argument "the string" isn't numeric in negation (-) at ...> という
515522警告を出します。
516523X<-> X<negation, arithmetic>
517524
518525=begin original
519526
520527Unary "~" performs bitwise negation, i.e., 1's complement. For
521528example, C<0666 & ~027> is 0640. (See also L<Integer Arithmetic> and
522529L<Bitwise String Operators>.) Note that the width of the result is
523530platform-dependent: ~0 is 32 bits wide on a 32-bit platform, but 64
524531bits wide on a 64-bit platform, so if you are expecting a certain bit
525width, remember to use the & operator to mask off the excess bits.
532width, remember to use the "&" operator to mask off the excess bits.
526533X<~> X<negation, binary>
527534
528535=end original
529536
530単項演算子の "~" はビットごとの否定を行ないます。
537単項演算子の "~" はビットごとの否定を行ないます; つまり、1 の補数を返します
531つまり、1 の補数を返します。
532538例えば、C<0666 & ~027> は 0640 です。
533539(L<Integer Arithmetic> と L<Bitwise String Operators> も参照して下さい。)
534結果の幅はプラットホーム依存であることに注意してください
540結果の幅はプラットホーム依存であることに注意してください: ~0 は
535~0 は 32-bit プラットホームでは 32 ビット幅ですが、
54132 ビットプラットホームでは 32 ビット幅ですが、64 ビットプラットホームでは
53664-bit プラットホームは 64 ビット幅ので
54264 ット幅なの、特定のビット幅を仮定る場合は
537特定のビット仮定する場合は、
543余分なビットをマスクするために "&" 演算子を使うことを忘れないでください。
538余分なビットをマスクするために & 演算子を使うことを忘れないでください。
539544X<~> X<negation, binary>
540545
541546=begin original
542547
548When complementing strings, if all characters have ordinal values under
549256, then their complements will, also. But if they do not, all
550characters will be in either 32- or 64-bit complements, depending on your
551architecture. So for example, C<~"\x{3B1}"> is C<"\x{FFFF_FC4E}"> on
55232-bit machines and C<"\x{FFFF_FFFF_FFFF_FC4E}"> on 64-bit machines.
553
554=end original
555
556文字列の補数を計算するとき、全ての文字の値が 256 未満の場合は、その値の
557補数が計算されます。
558そうでない場合は、全ての文字はアーキテクチャに依存しいて 32 ビットまたは
55964 ビットで補数が計算されます。
560従って例えば、C<~"\x{3B1}"> は 32 ビットマシンでは C<"\x{FFFF_FC4E}"> に、
56164 ビットマシンでは C<"\x{FFFF_FFFF_FFFF_FC4E}"> になります。
562
563=begin original
564
543565Unary "+" has no effect whatsoever, even on strings. It is useful
544566syntactically for separating a function name from a parenthesized expression
545567that would otherwise be interpreted as the complete list of function
546568arguments. (See examples above under L<Terms and List Operators (Leftward)>.)
547569X<+>
548570
549571=end original
550572
551573単項演算子の "+" は、たとえ文字列に対して用いられた場合にも、何もしません。
552574関数名に続けて括弧付きの式を書く場合に、関数の引数リストと
553575解釈されないようにするために用いることができます。
554576(下記 L<Terms and List Operators (Leftward)> の例を参照してください。)
555577X<+>
556578
557579=begin original
558580
559581Unary "\" creates a reference to whatever follows it. See L<perlreftut>
560582and L<perlref>. Do not confuse this behavior with the behavior of
561583backslash within a string, although both forms do convey the notion
562584of protecting the next thing from interpolation.
563585X<\> X<reference> X<backslash>
564586
565587=end original
566588
567589単項演算子の "\" はその後に続くものへのリファレンスを生成します。
568590L<perlreftut> と L<perlref> を参照してください。
569591この用法も文字列中のバックスラッシュも、後に続くものが展開されるのを
570592防ぐことになりますが、動作を混同しないでください。
571593X<\> X<reference> X<backslash>
572594
573595=head2 Binding Operators
574596X<binding> X<operator, binding> X<=~> X<!~>
575597
576598(拘束演算子)
577599
578600=begin original
579601
580602Binary "=~" binds a scalar expression to a pattern match. Certain operations
581603search or modify the string $_ by default. This operator makes that kind
582604of operation work on some other string. The right argument is a search
583605pattern, substitution, or transliteration. The left argument is what is
584606supposed to be searched, substituted, or transliterated instead of the default
585607$_. When used in scalar context, the return value generally indicates the
586success of the operation. Behavior in list context depends on the particular
608success of the operation. The exceptions are substitution (s///)
587operator. See L</"Regexp Quote-Like Operators"> for details and
609and transliteration (y///) with the C</r> (non-destructive) option,
588L<perlretut> for examples using these operators.
610which cause the B<r>eturn value to be the result of the substitution.
611Behavior in list context depends on the particular operator.
612See L</"Regexp Quote-Like Operators"> for details and L<perlretut> for
613examples using these operators.
589614
590615=end original
591616
592617二項演算子の "=~" は、スカラ式をパターンマッチに拘束します。
593618デフォルトで $_ の文字列を検索したり、変更したりする演算があります。
594619この演算子は、そのような演算を他の文字列に対して行なわせるようにするものです。
595620右引数は、検索パターン、置換、文字変換のいずれかです。
596621左引数は、デフォルトの $_ の代わりに検索、置換、文字変換の対象となるものです。
597622スカラコンテキストで使うと、返り値は一般的に演算の結果が成功したか否かです。
623例外は、C</r> (非破壊) オプション付きの置換 (s///) と文字変換
624(y///) です; この場合は変換した結果を返します。
598625リストコンテキストでの振る舞いは演算子に依存します。
599626詳しくは L</"Regexp Quote-Like Operators"> を、これらの演算子を使った
600627例については L<perlretut> を参照して下さい。
601628
602629=begin original
603630
604631If the right argument is an expression rather than a search pattern,
605632substitution, or transliteration, it is interpreted as a search pattern at run
606633time. Note that this means that its contents will be interpolated twice, so
607634
608635=end original
609636
610637右引数が検索パターン、置換、文字変換ではなく、式であれば、
611638それは実行時に決まる検索パターンと解釈されます。
612639これは、内容が 2 回展開されることを意味することに注意してください;
613640つまり:
614641
615642 '\\' =~ q'\\';
616643
617644=begin original
618645
619646is not ok, as the regex engine will end up trying to compile the
620647pattern C<\>, which it will consider a syntax error.
621648
622649=end original
623650
624651は正しくありません; 正規表現エンジンは最終的にパターン C<\> を
625652コンパイルしようとして、これは文法エラーと考えるからです。
626653
627654=begin original
628655
629656Binary "!~" is just like "=~" except the return value is negated in
630657the logical sense.
631658
632659=end original
633660
634661二項演算子の "!~" は、返される値が論理否定されることを除いて
635662"=~" と同じです。
636663
664=begin original
665
666Binary "!~" with a non-destructive substitution (s///r) or transliteration
667(y///r) is a syntax error.
668
669=end original
670
671二項演算子の "!~" を非破壊置換 (s///r) や変換 (y///r) で使うと
672文法エラーとなります。
673
637674=head2 Multiplicative Operators
638675X<operator, multiplicative>
639676
640677(乗法演算子)
641678
642679=begin original
643680
644681Binary "*" multiplies two numbers.
645682X<*>
646683
647684=end original
648685
649686二項演算子の "*" は 2 つの数値の積を返します。
650687X<*>
651688
652689=begin original
653690
654691Binary "/" divides two numbers.
655692X</> X<slash>
656693
657694=end original
658695
659696二項演算子の "/" は 2 つの数値の商を返します。
660697X</> X<slash>
661698
662699=begin original
663700
664701Binary "%" is the modulo operator, which computes the division
665702remainder of its first argument with respect to its second argument.
666703Given integer
667704operands C<$a> and C<$b>: If C<$b> is positive, then C<$a % $b> is
668705C<$a> minus the largest multiple of C<$b> less than or equal to
669706C<$a>. If C<$b> is negative, then C<$a % $b> is C<$a> minus the
670707smallest multiple of C<$b> that is not less than C<$a> (i.e. the
671708result will be less than or equal to zero). If the operands
672709C<$a> and C<$b> are floating point values and the absolute value of
673710C<$b> (that is C<abs($b)>) is less than C<(UV_MAX + 1)>, only
674711the integer portion of C<$a> and C<$b> will be used in the operation
675712(Note: here C<UV_MAX> means the maximum of the unsigned integer type).
676713If the absolute value of the right operand (C<abs($b)>) is greater than
677714or equal to C<(UV_MAX + 1)>, "%" computes the floating-point remainder
678715C<$r> in the equation C<($r = $a - $i*$b)> where C<$i> is a certain
679716integer that makes C<$r> have the same sign as the right operand
680717C<$b> (B<not> as the left operand C<$a> like C function C<fmod()>)
681718and the absolute value less than that of C<$b>.
682719Note that when C<use integer> is in scope, "%" gives you direct access
683720to the modulo operator as implemented by your C compiler. This
684721operator is not as well defined for negative operands, but it will
685722execute faster.
686723X<%> X<remainder> X<modulo> X<mod>
687724
688725=end original
689726
690727二項演算子の "%" は剰余演算子で、一つ目の引数を二つ目の引数で割ったときの
691728余りを返します。
692729C<$a> と C<$b> の二つの整数の被演算子を取ったとすると:
693730C<$b> が正の場合、C<$a % $b> は、C<$a> から C<$a> 以下の最大の
694731C<$b> の倍数を引いた値です。
695732C<$b> が負の場合、C<$a % $b> は、C<$a> から C<$a> を下回らない
696最小の C<$b> の倍数を引いた値です(従って結果はゼロ以下になります)
733最小の C<$b> の倍数を引いた値です(従って結果はゼロ以下になります)
697734オペランド C<$a> と C<$b> が浮動小数点数で、C<$b> の絶対値
698735(つまり C<abs($b)>) が C<(UV_MAX + 1)> より小さい場合、
699736C<$a> と C<$b> の整数部のみが操作で使われます
700737(注意: ここで C<UV_MAX> は符号なし整数の最大値を意味します)。
701738右オペランドの絶対値 (C<abs($b)>) が C<(UV_MAX + 1)> 以上の場合、
702739"%" は、C<($r = $a - $i*$b)> となる浮動小数点剰余 C<$r> を計算します;
703740ここで C<$i> は、C<$r> が右オペランド C<$b> と同じ符号 (C の
704741関数 C<fmod()> のように左オペランド C<$a> B<ではありません>) で、
705742絶対値が C<$b> より小さいものになるような、ある整数です。
706743C<use integer> がスコープ内にある場合、
707744"%" は C コンパイラで実装された剰余演算子を使います。
708745この演算子は被演算子が負の場合の挙動が不確実ですが、
709746より高速です。
710747X<%> X<remainder> X<modulo> X<mod>
711748
712749=begin original
713750
714751Binary "x" is the repetition operator. In scalar context or if the left
715752operand is not enclosed in parentheses, it returns a string consisting
716753of the left operand repeated the number of times specified by the right
717754operand. In list context, if the left operand is enclosed in
718755parentheses or is a list formed by C<qw/STRING/>, it repeats the list.
719756If the right operand is zero or negative, it returns an empty string
720757or an empty list, depending on the context.
721758X<x>
722759
723760=end original
724761
725762二項演算子の "x" は繰り返し演算子です。
726763スカラコンテキストまたは左辺値が括弧で括られていない場合は、
727764左被演算子を右被演算子に示す数だけ繰り返したもので構成される
728765文字列を返します。
729766リストコンテキストでは、左被演算子が括弧で括られているか、C<qw/STRING> の
730767形のリストの場合、リストを繰り返します。
731768右オペランドが 0 か負数の場合、コンテキストによって、空文字列か空リストを
732769返します。
733770X<x>
734771
735772 print '-' x 80; # print row of dashes
736773
737774 print "\t" x ($tab/8), ' ' x ($tab%8); # tab over
738775
739776 @ones = (1) x 80; # a list of 80 1's
740777 @ones = (5) x @ones; # set all elements to 5
741778
742779
743780=head2 Additive Operators
744781X<operator, additive>
745782
746783(加法演算子)
747784
748785=begin original
749786
750787Binary "+" returns the sum of two numbers.
751788X<+>
752789
753790=end original
754791
755792二項演算子の "+" は 2 つの数値の和を返します。
756793X<+>
757794
758795=begin original
759796
760797Binary "-" returns the difference of two numbers.
761798X<->
762799
763800=end original
764801
765802二項演算子の "-" は 2 つの数値の差を返します。
766803X<->
767804
768805=begin original
769806
770807Binary "." concatenates two strings.
771808X<string, concatenation> X<concatenation>
772809X<cat> X<concat> X<concatenate> X<.>
773810
774811=end original
775812
776813二項演算子の "." は 2 つの文字列を連結します。
777814X<string, concatenation> X<concatenation>
778815X<cat> X<concat> X<concatenate> X<.>
779816
780817=head2 Shift Operators
781818X<shift operator> X<operator, shift> X<<< << >>>
782819X<<< >> >>> X<right shift> X<left shift> X<bitwise shift>
783820X<shl> X<shr> X<shift, right> X<shift, left>
784821
785822(シフト演算子)
786823
787824=begin original
788825
789826Binary "<<" returns the value of its left argument shifted left by the
790827number of bits specified by the right argument. Arguments should be
791828integers. (See also L<Integer Arithmetic>.)
792829
793830=end original
794831
795832二項演算子の "<<" は左引数の値を、右引数で示すビット数だけ、
796833左にシフトした値を返します。
797834引数は整数でなければなりません。
798835(L<Integer Arithmetic> も参照して下さい。)
799836
800837=begin original
801838
802839Binary ">>" returns the value of its left argument shifted right by
803840the number of bits specified by the right argument. Arguments should
804841be integers. (See also L<Integer Arithmetic>.)
805842
806843=end original
807844
808845二項演算子の ">>" は左引数の値を、右引数で示すビット数だけ、
809846右にシフトした値を返します。
810847引数は整数でなければなりません。
811848(L<Integer Arithmetic> も参照して下さい。)
812849
813850=begin original
814851
815852Note that both "<<" and ">>" in Perl are implemented directly using
816853"<<" and ">>" in C. If C<use integer> (see L<Integer Arithmetic>) is
817854in force then signed C integers are used, else unsigned C integers are
818855used. Either way, the implementation isn't going to generate results
819856larger than the size of the integer type Perl was built with (32 bits
820857or 64 bits).
821858
822859=end original
823860
824861Perl での "<<" と ">>" は C での "<<" と ">>" を直接利用して
825862実装されていることに注意してください。
826863C<use integer> (L<Integer Arithmetic> を参照してください)が有効な場合、
827864C の符号付き整数が使われ、そうでない場合は C の符号なし整数が使われます。
828865どちらの場合も、この実装は Perl がビルドされた整数型のサイズ(32 ビットか
82986664 ビット)よりも大きい結果を生成することはありません。
830867
831868=begin original
832869
833870The result of overflowing the range of the integers is undefined
834871because it is undefined also in C. In other words, using 32-bit
835872integers, C<< 1 << 32 >> is undefined. Shifting by a negative number
836873of bits is also undefined.
837874
838875=end original
839876
840877整数の範囲をオーバーフローした場合の結果は、C でも未定義なので、未定義です。
841878言い換えると、32 ビット整数を使っているとき、C<< 1 << 32 >> は未定義です。
842879シフトするビット数として負の数を指定した場合も未定義です。
843880
844881=head2 Named Unary Operators
845882X<operator, named unary>
846883
847884(名前付き単項演算子)
848885
849886=begin original
850887
851888The various named unary operators are treated as functions with one
852889argument, with optional parentheses.
853890
854891=end original
855892
856893さまざまな名前付き単項演算子が、引数を 1 つ持ち、括弧が省略可能な、
857894関数として扱われます。
858895
859896=begin original
860897
861898If any list operator (print(), etc.) or any unary operator (chdir(), etc.)
862899is followed by a left parenthesis as the next token, the operator and
863900arguments within parentheses are taken to be of highest precedence,
864901just like a normal function call. For example,
865902because named unary operators are higher precedence than ||:
866903
867904=end original
868905
869906リスト演算子 (print() など) や単項演算子 (chdir() など) は、
870907すべて次のトークンとして開き括弧が続くと、その演算子と括弧内の引数は、
871908通常の関数呼び出しのようにもっとも高い優先順位として扱われます。
872909たとえば、名前つき単項演算子は || より優先順位が高いので、
873910以下のようになります:
874911
875912 chdir $foo || die; # (chdir $foo) || die
876913 chdir($foo) || die; # (chdir $foo) || die
877914 chdir ($foo) || die; # (chdir $foo) || die
878915 chdir +($foo) || die; # (chdir $foo) || die
879916
880917=begin original
881918
882919but, because * is higher precedence than named operators:
883920
884921=end original
885922
886923しかし * は名前つき演算子より優先順位が高いので、以下のようになります:
887924
888925 chdir $foo * 20; # chdir ($foo * 20)
889926 chdir($foo) * 20; # (chdir $foo) * 20
890927 chdir ($foo) * 20; # (chdir $foo) * 20
891928 chdir +($foo) * 20; # chdir ($foo * 20)
892929
893930 rand 10 * 20; # rand (10 * 20)
894931 rand(10) * 20; # (rand 10) * 20
895932 rand (10) * 20; # (rand 10) * 20
896933 rand +(10) * 20; # rand (10 * 20)
897934
898935=begin original
899936
900937Regarding precedence, the filetest operators, like C<-f>, C<-M>, etc. are
901938treated like named unary operators, but they don't follow this functional
902939parenthesis rule. That means, for example, that C<-f($file).".bak"> is
903940equivalent to C<-f "$file.bak">.
904941X<-X> X<filetest> X<operator, filetest>
905942
906943=end original
907944
908945優先順位に関して、C<-f> や C<-M> のようなファイルテスト演算子は、名前付き
909946単項演算子として扱われますが、この関数のかっこルールは適用されません。
910947これは、例えば C<-f($file).".bak"> は C<-f "$file.bak"> と等価であることを
911948意味します。
912949X<-X> X<filetest> X<operator, filetest>
913950
914951=begin original
915952
916953See also L<"Terms and List Operators (Leftward)">.
917954
918955=end original
919956
920957L<"Terms and List Operators (Leftward)"> も参照して下さい。
921958
922959=head2 Relational Operators
923960X<relational operator> X<operator, relational>
924961
925962(比較演算子)
926963
927964=begin original
928965
929966Binary "<" returns true if the left argument is numerically less than
930967the right argument.
931968X<< < >>
932969
933970=end original
934971
935972二項演算子の "<" は左引数が数値的に右引数よりも小さければ、
936973真を返します。
974X<< < >>
937975
938976=begin original
939977
940978Binary ">" returns true if the left argument is numerically greater
941979than the right argument.
942980X<< > >>
943981
944982=end original
945983
946984二項演算子の ">" は左引数が数値的に右引数よりも大きければ、
947985真を返します。
986X<< > >>
948987
949988=begin original
950989
951990Binary "<=" returns true if the left argument is numerically less than
952991or equal to the right argument.
953992X<< <= >>
954993
955994=end original
956995
957996二項演算子の "<=" は左引数が数値的に右引数よりも小さいか等しければ、
958997真を返します。
998X<< <= >>
959999
9601000=begin original
9611001
9621002Binary ">=" returns true if the left argument is numerically greater
9631003than or equal to the right argument.
9641004X<< >= >>
9651005
9661006=end original
9671007
9681008二項演算子の ">=" は左引数が数値的に右引数よりも大きいか等しければ、
9691009真を返します。
1010X<< >= >>
9701011
9711012=begin original
9721013
9731014Binary "lt" returns true if the left argument is stringwise less than
9741015the right argument.
9751016X<< lt >>
9761017
9771018=end original
9781019
9791020二項演算子の "lt" は左引数が文字列的に右引数よりも小さければ、
9801021真を返します。
1022X<< lt >>
9811023
9821024=begin original
9831025
9841026Binary "gt" returns true if the left argument is stringwise greater
9851027than the right argument.
9861028X<< gt >>
9871029
9881030=end original
9891031
9901032二項演算子の "gt" は左引数が文字列的に右引数よりも大きければ、
9911033真を返します。
1034X<< gt >>
9921035
9931036=begin original
9941037
9951038Binary "le" returns true if the left argument is stringwise less than
9961039or equal to the right argument.
9971040X<< le >>
9981041
9991042=end original
10001043
10011044二項演算子の "le" は左引数が文字列的に右引数よりも小さいか等しければ、
10021045真を返します。
1046X<< le >>
10031047
10041048=begin original
10051049
10061050Binary "ge" returns true if the left argument is stringwise greater
10071051than or equal to the right argument.
10081052X<< ge >>
10091053
10101054=end original
10111055
10121056二項演算子の "ge" は左引数が文字列的に右引数よりも大きいか等しければ、
10131057真を返します。
1058X<< ge >>
10141059
10151060=head2 Equality Operators
10161061X<equality> X<equal> X<equals> X<operator, equality>
10171062
10181063(等価演算子)
10191064
10201065=begin original
10211066
10221067Binary "==" returns true if the left argument is numerically equal to
10231068the right argument.
10241069X<==>
10251070
10261071=end original
10271072
10281073二項演算子の "==" は左引数が数値的に右引数と等しければ、
10291074真を返します。
1075X<==>
10301076
10311077=begin original
10321078
10331079Binary "!=" returns true if the left argument is numerically not equal
10341080to the right argument.
10351081X<!=>
10361082
10371083=end original
10381084
10391085二項演算子の "!=" は左引数が数値的に右引数と等しくなければ、
10401086真を返します。
1087X<!=>
10411088
10421089=begin original
10431090
10441091Binary "<=>" returns -1, 0, or 1 depending on whether the left
10451092argument is numerically less than, equal to, or greater than the right
10461093argument. If your platform supports NaNs (not-a-numbers) as numeric
10471094values, using them with "<=>" returns undef. NaN is not "<", "==", ">",
10481095"<=" or ">=" anything (even NaN), so those 5 return false. NaN != NaN
10491096returns true, as does NaN != anything else. If your platform doesn't
10501097support NaNs then NaN is just a string with numeric value 0.
10511098X<< <=> >> X<spaceship>
10521099
10531100=end original
10541101
10551102二項演算子の "<=>" は左引数が数値的に右引数より小さいか、等しいか、
10561103大きいかに従って、-1, 0, 1 を返します。
10571104数値として NaN (非数) に対応しているプラットフォームでは、
10581105NaN に対して "<=>" を使うと undef を返します。
10591106NaN はどの値に対しても(NaN に対してでさえも) "<", "==", ">",
10601107"<=", ">=" のいずれも成立しないので、これらは全て偽となります。
10611108NaN != NaN は真を返しますが、その他のどの値に対しても != は偽を返します。
10621109NaN に対応していないプラットフォームでは、NaN は単に数としての値 0 を持つ
10631110文字列です。
1111X<< <=> >> X<spaceship>
10641112
10651113 perl -le '$a = "NaN"; print "No NaN support here" if $a == $a'
10661114 perl -le '$a = "NaN"; print "NaN support here" if $a != $a'
10671115
10681116=begin original
10691117
10701118Binary "eq" returns true if the left argument is stringwise equal to
10711119the right argument.
10721120X<eq>
10731121
10741122=end original
10751123
10761124二項演算子の "eq" は左引数が文字列的に右引数と等しければ、
10771125真を返します。
1126X<eq>
10781127
10791128=begin original
10801129
10811130Binary "ne" returns true if the left argument is stringwise not equal
10821131to the right argument.
10831132X<ne>
10841133
10851134=end original
10861135
10871136二項演算子の "ne" は左引数が文字列的に右引数と等しくなければ、
10881137真を返します。
1138X<ne>
10891139
10901140=begin original
10911141
10921142Binary "cmp" returns -1, 0, or 1 depending on whether the left
10931143argument is stringwise less than, equal to, or greater than the right
10941144argument.
10951145X<cmp>
10961146
10971147=end original
10981148
10991149二項演算子の "cmp" は左引数が文字列的に右引数より小さいか、
11001150等しいか、大きいかに従って、-1, 0, 1 を返します。
1151X<cmp>
11011152
11021153=begin original
11031154
11041155Binary "~~" does a smart match between its arguments. Smart matching
11051156is described in L<perlsyn/"Smart matching in detail">.
11061157X<~~>
11071158
11081159=end original
11091160
11101161二項演算子の "~~" はスマートマッチングとして働きます。
11111162スマートマッチングについては L<perlsyn/"Smart matching in detail"> で
11121163述べられています。
11131164X<~~>
11141165
11151166=begin original
11161167
11171168"lt", "le", "ge", "gt" and "cmp" use the collation (sort) order specified
11181169by the current locale if C<use locale> is in effect. See L<perllocale>.
11191170
11201171=end original
11211172
11221173"lt", "le", "ge", "gt", "cmp" は C<use locale> が有効な場合は
11231174現在のロケールで指定された辞書(ソート)順が使われます。
11241175L<perllocale> を参照して下さい。
11251176
11261177=head2 Bitwise And
11271178X<operator, bitwise, and> X<bitwise and> X<&>
11281179
11291180(ビットごとの AND)
11301181
11311182=begin original
11321183
11331184Binary "&" returns its operands ANDed together bit by bit.
11341185(See also L<Integer Arithmetic> and L<Bitwise String Operators>.)
11351186
11361187=end original
11371188
11381189二項演算子の "&" は、両オペランドのビットごとに論理積をとって、
11391190その結果を返します。
11401191(L<Integer Arithmetic> と L<Bitwise String Operators> も参照して下さい。)
11411192
11421193=begin original
11431194
11441195Note that "&" has lower priority than relational operators, so for example
11451196the brackets are essential in a test like
11461197
11471198=end original
11481199
11491200"&" は関係演算子より優先順位が低いので、例えば以下のようなテストでは、
11501201かっこが重要です:
11511202
11521203 print "Even\n" if ($x & 1) == 0;
11531204
11541205=head2 Bitwise Or and Exclusive Or
11551206X<operator, bitwise, or> X<bitwise or> X<|> X<operator, bitwise, xor>
11561207X<bitwise xor> X<^>
11571208
11581209(ビットごとの OR と XOR)
11591210
11601211=begin original
11611212
11621213Binary "|" returns its operands ORed together bit by bit.
11631214(See also L<Integer Arithmetic> and L<Bitwise String Operators>.)
11641215
11651216=end original
11661217
11671218二項演算子の "|" は、両オペランドのビットごとに論理和をとって、
11681219その結果を返します。
11691220(L<Integer Arithmetic> と L<Bitwise String Operators> も参照して下さい。)
11701221
11711222=begin original
11721223
11731224Binary "^" returns its operands XORed together bit by bit.
11741225(See also L<Integer Arithmetic> and L<Bitwise String Operators>.)
11751226
11761227=end original
11771228
11781229二項演算子の "^" は、両オペランドのビットごとに排他論理和をとって、
11791230その結果を返します。
11801231(L<Integer Arithmetic> と L<Bitwise String Operators> も参照して下さい。)
11811232
11821233=begin original
11831234
11841235Note that "|" and "^" have lower priority than relational operators, so
11851236for example the brackets are essential in a test like
11861237
11871238=end original
11881239
11891240"|" と "^" は関係演算子より優先順位が低いので、例えば以下のような
11901241テストでは、かっこが重要です:
11911242
11921243 print "false\n" if (8 | 2) != 10;
11931244
11941245=head2 C-style Logical And
11951246X<&&> X<logical and> X<operator, logical, and>
11961247
11971248(C スタイルの論理積)
11981249
11991250=begin original
12001251
12011252Binary "&&" performs a short-circuit logical AND operation. That is,
12021253if the left operand is false, the right operand is not even evaluated.
12031254Scalar or list context propagates down to the right operand if it
12041255is evaluated.
12051256
12061257=end original
12071258
12081259二項演算子の "&&" は、短絡の論理積演算を行ないます。
12091260つまり、左被演算子が偽であれば、右被演算子は評価さえ
12101261行なわれないということです。
12111262評価される場合には、スカラーかリストかというコンテキストは、
12121263右被演算子にも及びます。
12131264
12141265=head2 C-style Logical Or
12151266X<||> X<operator, logical, or>
12161267
12171268(C スタイルの論理和)
12181269
12191270=begin original
12201271
12211272Binary "||" performs a short-circuit logical OR operation. That is,
12221273if the left operand is true, the right operand is not even evaluated.
12231274Scalar or list context propagates down to the right operand if it
12241275is evaluated.
12251276
12261277=end original
12271278
12281279二項演算子の "||" は、短絡の論理和演算を行ないます。
12291280つまり、左被演算子が真であれば、右被演算子は評価さえ
12301281行なわれないということです。
12311282評価される場合には、スカラーかリストかというコンテキストは、
12321283右被演算子にも及びます。
12331284
12341285=head2 C-style Logical Defined-Or
12351286X<//> X<operator, logical, defined-or>
12361287
12371288(C スタイルの定義性和)
12381289
12391290=begin original
12401291
12411292Although it has no direct equivalent in C, Perl's C<//> operator is related
12421293to its C-style or. In fact, it's exactly the same as C<||>, except that it
12431294tests the left hand side's definedness instead of its truth. Thus, C<$a // $b>
12441295is similar to C<defined($a) || $b> (except that it returns the value of C<$a>
1245rather than the value of C<defined($a)>) and is exactly equivalent to
1296rather than the value of C<defined($a)>) and yields the same result as
1246C<defined($a) ? $a : $b>. This is very useful for providing default values
1297C<defined($a) ? $a : $b> (except that the ternary-operator form can be
1247for variables. If you actually want to test if at least one of C<$a> and
1298used as a lvalue, while C<$a // $b> cannot). This is very useful for
1248C<$b> is defined, use C<defined($a // $b)>.
1299providing default values for variables. If you actually want to test if
1300at least one of C<$a> and C<$b> is defined, use C<defined($a // $b)>.
12491301
12501302=end original
12511303
12521304C では直接等価なものはありませんが、Perl の C<//> 演算子は C スタイル
12531305論理和に関連しています。
12541306実際、左辺の真偽ではなく定義されているかを判定することを除けば
12551307C<||> と同じです。
12561308したがって C<$a // $b> は C<defined($a) || $b> と似ていて (ただし、
12571309C<defined($a)> ではなく C<$a> の値を返します)、C<defined($a) ? $a : $b> と
1258完全に等価です
1310完全に等価です (例外は 3 項演算子形式は左辺値として使えますが、
1311C<$a // $b> は使えません)。
12591312これは、変数に対するデフォルト値を設定するのにとても有用です。
12601313実際に、C<$a> と C<$b> の少なくとも片方が定義されているかを判定したいなら、
12611314C<defined($a // $b)> を使ってください。
12621315
12631316=begin original
12641317
12651318The C<||>, C<//> and C<&&> operators return the last value evaluated
12661319(unlike C's C<||> and C<&&>, which return 0 or 1). Thus, a reasonably
12671320portable way to find out the home directory might be:
12681321
12691322=end original
12701323
12711324C<||>, C<//>, C<&&> 演算子は、(C のように 単に 0 や 1 を返すのではなく)
12721325最後に評価された値を返します。
12731326これにより、かなり一般的に使えるホームディレクトリを探す方法は:
12741327
1275 $home = $ENV{'HOME'} // $ENV{'LOGDIR'} //
1328 $home = $ENV{HOME}
1276 (getpwuid($<))[7] // die "You're homeless!\n";
1329 // $ENV{LOGDIR}
1330 // (getpwuid($<))[7]
1331 // die "You're homeless!\n";
12771332
12781333=begin original
12791334
12801335In particular, this means that you shouldn't use this
12811336for selecting between two aggregates for assignment:
12821337
12831338=end original
12841339
12851340特に、これは代入のために二つの集合を選択するためには
12861341使うべきではないことを意味します。
12871342
1343=begin original
1344
12881345 @a = @b || @c; # this is wrong
12891346 @a = scalar(@b) || @c; # really meant this
12901347 @a = @b ? @b : @c; # this works fine, though
12911348
1349=end original
1350
1351 @a = @b || @c; # これは間違い
1352 @a = scalar(@b) || @c; # 本当にしたいこと
1353 @a = @b ? @b : @c; # しかしこれも動作する
1354
12921355=begin original
12931356
12941357As more readable alternatives to C<&&> and C<||> when used for
12951358control flow, Perl provides the C<and> and C<or> operators (see below).
12961359The short-circuit behavior is identical. The precedence of "and"
12971360and "or" is much lower, however, so that you can safely use them after a
12981361list operator without the need for parentheses:
12991362
13001363=end original
13011364
13021365Perl では、フロー制御に使う場合の多少読みやすい C<&&> と C<||> の
13031366同義語として、C<and> 演算子と C<or> 演算子が用意されています (下記参照)。
13041367短絡の動作は全く同じです。
13051368しかし、"and" と "or" の優先順位はかなり低くしてあるので、引数に括弧を
13061369使っていないリスト演算子のあとに続けて使う場合にも、
13071370安心して使うことができます:
13081371
13091372 unlink "alpha", "beta", "gamma"
13101373 or gripe(), next LINE;
13111374
13121375=begin original
13131376
13141377With the C-style operators that would have been written like this:
13151378
13161379=end original
13171380
13181381C スタイルの演算子では以下のように書く必要があります。
13191382
13201383 unlink("alpha", "beta", "gamma")
13211384 || (gripe(), next LINE);
13221385
13231386=begin original
13241387
13251388Using "or" for assignment is unlikely to do what you want; see below.
13261389
13271390=end original
13281391
1329代入で "or" を使うと、したいことと違うことになります。
1392代入で "or" を使うと、したいことと違うことになります; 以下を参照して下さい
1330以下を参照して下さい。
13311393
13321394=head2 Range Operators
13331395X<operator, range> X<range> X<..> X<...>
13341396
13351397(範囲演算子)
13361398
13371399=begin original
13381400
13391401Binary ".." is the range operator, which is really two different
13401402operators depending on the context. In list context, it returns a
13411403list of values counting (up by ones) from the left value to the right
13421404value. If the left value is greater than the right value then it
13431405returns the empty list. The range operator is useful for writing
13441406C<foreach (1..10)> loops and for doing slice operations on arrays. In
13451407the current implementation, no temporary array is created when the
13461408range operator is used as the expression in C<foreach> loops, but older
13471409versions of Perl might burn a lot of memory when you write something
13481410like this:
13491411
13501412=end original
13511413
13521414二項演算子の ".." は範囲演算子で、使われるコンテキストによって
13531415異なる動作をする 2 つの演算子を合わせたものです。
13541416リストコンテキストでは、左の値から右の値まで (1 づつ昇順で) 数えあげた値から
13551417なるリストを返します。
13561418左側の値が右側の値より大きい場合は、空リストを返します。
13571419範囲演算子は、C<foreach (1..10)> のようなループを書くときや、
13581420配列のスライス演算を行なうときに便利です。
13591421現状の実装では、C<foreach> ループの式の中で範囲演算子を使っても
13601422一時配列は作りませんが、古い Perl は以下のようなことを書くと、
13611423大量のメモリを消費することになります:
13621424
13631425 for (1 .. 1_000_000) {
13641426 # code
13651427 }
13661428
13671429=begin original
13681430
1369The range operator also works on strings, using the magical auto-increment,
1431The range operator also works on strings, using the magical
1370see below.
1432auto-increment, see below.
13711433
13721434=end original
13731435
1374範囲演算子は、マジカル自動インクリメントを使うことで文字列でも動作します
1436範囲演算子は、マジカル自動インクリメントを使うことで文字列でも動作します;
13751437以下を参照してください。
13761438
13771439=begin original
13781440
13791441In scalar context, ".." returns a boolean value. The operator is
1380bistable, like a flip-flop, and emulates the line-range (comma) operator
1442bistable, like a flip-flop, and emulates the line-range (comma)
1381of B<sed>, B<awk>, and various editors. Each ".." operator maintains its
1443operator of B<sed>, B<awk>, and various editors. Each ".." operator
1382own boolean state. It is false as long as its left operand is false.
1444maintains its own boolean state, even across calls to a subroutine
1445that contains it. It is false as long as its left operand is false.
13831446Once the left operand is true, the range operator stays true until the
13841447right operand is true, I<AFTER> which the range operator becomes false
1385again. It doesn't become false till the next time the range operator is
1448again. It doesn't become false till the next time the range operator
1386evaluated. It can test the right operand and become false on the same
1449is evaluated. It can test the right operand and become false on the
1387evaluation it became true (as in B<awk>), but it still returns true once.
1450same evaluation it became true (as in B<awk>), but it still returns
1388If you don't want it to test the right operand till the next
1451true once. If you don't want it to test the right operand until the
1389evaluation, as in B<sed>, just use three dots ("...") instead of
1452next evaluation, as in B<sed>, just use three dots ("...") instead of
13901453two. In all other regards, "..." behaves just like ".." does.
13911454
13921455=end original
13931456
13941457スカラコンテキストで使われたときには、".." は真偽値を返します。
13951458この演算子は、フリップフロップのように 2 値安定で、
13961459B<sed> や B<awk> や多くのエディタでの行範囲 (コンマ) 演算子を
13971460エミュレートするものとなります。
1398各々の ".." 演算子それぞれに独立して自分の真偽状態管理ます。
1461各々の ".." 演算子は、例えそれを含むサブルーチンの呼び出
1462またいでも、それぞれに独立して自分の真偽状態を管理します。
13991463はじめは、左被演算子が偽である間、演算全体も偽となっています。
1400範囲演算子は、いったん左被演算子が真になると、右被演算子が真である間、
1464いったん左被演算子が真になると、範囲演算子は、右被演算子が真である間、
1401真を返すようになります。
1465真を返すようになります; 範囲演算子が再び偽になった I<後> です
1402右被演算子が偽にな演算子もを返すようになりま
1466次に範囲演算子が評価されまでは、偽とはなりません
1403(次に範囲演算子が評価されるまでは、偽とはなりません。
14041467(B<awk> でのように) 真となった、その評価の中で右被演算子をテストし、
14051468偽とすることができますが、1 度は真を返すことになります。
14061469B<sed> でのように、次に評価されるまで右被演算子をテストしたくなければ、
140714702 個のドットの代わりに 3 つのドット ("...") を使ってください。
14081471その他の点では、"..." は ".." と同様に振舞います.
14091472
14101473=begin original
14111474
14121475The right operand is not evaluated while the operator is in the
14131476"false" state, and the left operand is not evaluated while the
14141477operator is in the "true" state. The precedence is a little lower
14151478than || and &&. The value returned is either the empty string for
1416false, or a sequence number (beginning with 1) for true. The
1479false, or a sequence number (beginning with 1) for true. The sequence
1417sequence number is reset for each range encountered. The final
1480number is reset for each range encountered. The final sequence number
1418sequence number in a range has the string "E0" appended to it, which
1481in a range has the string "E0" appended to it, which doesn't affect
1419doesn't affect its numeric value, but gives you something to search
1482its numeric value, but gives you something to search for if you want
1420for if you want to exclude the endpoint. You can exclude the
1483to exclude the endpoint. You can exclude the beginning point by
1421beginning point by waiting for the sequence number to be greater
1484waiting for the sequence number to be greater than 1.
1422than 1.
14231485
14241486=end original
14251487
14261488右被演算子は、演算子の状態が「偽」である間は評価されることがなく、
14271489左被演算子は、演算子の状態が「真」である間は評価されることがありません。
14281490優先順位は、|| と && の少し下です。
14291491偽としては空文字列が返され、
14301492真としては (1 から始まる) 順に並んだ数値が返されます。
14311493この通し番号は、新たに範囲が始まるごとにリセットされます。
1432範囲の最後の数字には、文字列 "E0" が末尾につけられます
1494範囲の最後の数字には、文字列 "E0" が末尾につけられます; これは、数値としては
1433これは、数値としては何の影響もありませんが、範囲の終わりで何か特別なことを
1495何の影響もありませんが、範囲の終わりで何か特別なことをしたい場合に、
1434したい場合に、目印として使うことができます。
1496目印として使うことができます。
14351497範囲の始まりで何かしたい場合には、通し番号が 1 よりも大きくなるのを
14361498待っていればよいでしょう。
14371499
14381500=begin original
14391501
14401502If either operand of scalar ".." is a constant expression,
14411503that operand is considered true if it is equal (C<==>) to the current
14421504input line number (the C<$.> variable).
14431505
14441506=end original
14451507
14461508スカラの ".." の被演算子が定数表現であるときは、その被演算子は暗黙に、
14471509現在の入力行番号(変数 C<$.>) と等しい(C<==>) 場合に真となります。
14481510
14491511=begin original
14501512
14511513To be pedantic, the comparison is actually C<int(EXPR) == int(EXPR)>,
14521514but that is only an issue if you use a floating point expression; when
14531515implicitly using C<$.> as described in the previous paragraph, the
14541516comparison is C<int(EXPR) == int($.)> which is only an issue when C<$.>
14551517is set to a floating point value and you are not reading from a file.
14561518Furthermore, C<"span" .. "spat"> or C<2.18 .. 3.14> will not do what
14571519you want in scalar context because each of the operands are evaluated
14581520using their integer representation.
14591521
14601522=end original
14611523
14621524とても細かい話をすると、比較は実際には C<int(EXPR) == int(EXPR)> ですが、
14631525これは浮動小数点数を使うときにだけ問題になります; 前の段落で記述したように
14641526明示的に C<$.> を使ったとき、比較は C<int(EXPR) == int($.)> となり、
14651527C<$.> に浮動小数点数がセットされ、ファイルから読み込みを行わない場合にのみ
14661528問題になります。
14671529さらに、C<"span" .. "spat"> や C<2.18 .. 3.14> は、それぞれのオペランドが
14681530整数表現を使って評価されるため、スカラコンテキストでは望みどおりの結果に
14691531なりません。
14701532
14711533=begin original
14721534
14731535Examples:
14741536
14751537=end original
14761538
14771539例:
14781540
14791541=begin original
14801542
14811543As a scalar operator:
14821544
14831545=end original
14841546
14851547スカラ演算子として:
14861548
14871549 if (101 .. 200) { print; } # print 2nd hundred lines, short for
1488 # if ($. == 101 .. $. == 200) { print; }
1550 # if ($. == 101 .. $. == 200) { print; }
14891551
14901552 next LINE if (1 .. /^$/); # skip header lines, short for
14911553 # next LINE if ($. == 1 .. /^$/);
14921554 # (typically in a loop labeled LINE)
14931555
14941556 s/^/> / if (/^$/ .. eof()); # quote body
14951557
14961558 # parse mail messages
14971559 while (<>) {
14981560 $in_header = 1 .. /^$/;
14991561 $in_body = /^$/ .. eof;
15001562 if ($in_header) {
15011563 # do something
15021564 } else { # in body
15031565 # do something else
15041566 }
15051567 } continue {
15061568 close ARGV if eof; # reset $. each file
15071569 }
15081570
15091571=begin original
15101572
15111573Here's a simple example to illustrate the difference between
15121574the two range operators:
15131575
15141576=end original
15151577
15161578以下は二つの範囲演算子の違いを示す単純な例です:
15171579
15181580 @lines = (" - Foo",
15191581 "01 - Bar",
15201582 "1 - Baz",
15211583 " - Quux");
15221584
15231585 foreach (@lines) {
15241586 if (/0/ .. /1/) {
15251587 print "$_\n";
15261588 }
15271589 }
15281590
15291591=begin original
15301592
15311593This program will print only the line containing "Bar". If
15321594the range operator is changed to C<...>, it will also print the
15331595"Baz" line.
15341596
15351597=end original
15361598
15371599このプログラムは "Bar" を含む行だけを表示します。
15381600範囲演算子を C<...> に変更すると、"Baz" の行も表示します。
15391601
15401602=begin original
15411603
15421604And now some examples as a list operator:
15431605
15441606=end original
15451607
15461608これはリスト演算子の例です:
15471609
1610=begin original
1611
15481612 for (101 .. 200) { print; } # print $_ 100 times
15491613 @foo = @foo[0 .. $#foo]; # an expensive no-op
15501614 @foo = @foo[$#foo-4 .. $#foo]; # slice last 5 items
15511615
1616=end original
1617
1618 for (101 .. 200) { print; } # $_ を 100 回出力
1619 @foo = @foo[0 .. $#foo]; # 高価な no-op
1620 @foo = @foo[$#foo-4 .. $#foo]; # 末尾の 5 アイテムをスライス
1621
15521622=begin original
15531623
15541624The range operator (in list context) makes use of the magical
15551625auto-increment algorithm if the operands are strings. You
15561626can say
15571627
15581628=end original
15591629
15601630(リストコンテキストでの) 範囲演算子は、被演算子が文字列であるときには、
15611631マジカルインクリメントの機能を使います。
15621632以下のように書くと:
15631633
1564 @alphabet = ('A' .. 'Z');
1634 @alphabet = ("A" .. "Z");
15651635
15661636=begin original
15671637
15681638to get all normal letters of the English alphabet, or
15691639
15701640=end original
15711641
15721642英語の大文字すべてを得られますし:
15731643
1574 $hexdigit = (0 .. 9, 'a' .. 'f')[$num & 15];
1644 $hexdigit = (0 .. 9, "a" .. "f")[$num & 15];
15751645
15761646=begin original
15771647
15781648to get a hexadecimal digit, or
15791649
15801650=end original
15811651
15821652と書けば、16 進の数字が得られますし、
15831653
1584 @z2 = ('01' .. '31'); print $z2[$mday];
1654 @z2 = ("01" .. "31"); print $z2[$mday];
15851655
15861656=begin original
15871657
15881658to get dates with leading zeros.
15891659
15901660=end original
15911661
15921662とすれば、0 付きの日付が得られます。
15931663
15941664=begin original
15951665
15961666If the final value specified is not in the sequence that the magical
15971667increment would produce, the sequence goes until the next value would
15981668be longer than the final value specified.
15991669
16001670=end original
16011671
16021672マジカルインクリメントによって得られる値の中に指定した最終値に
16031673ちょうど一致するものが見つからないような場合には、
16041674マジカルインクリメントによって得られる次の値の文字列長が、
16051675最終値として指定した値のものより長くなるまでインクリメントが続けられます。
16061676
16071677=begin original
16081678
16091679If the initial value specified isn't part of a magical increment
1610sequence (that is, a non-empty string matching "/^[a-zA-Z]*[0-9]*\z/"),
1680sequence (that is, a non-empty string matching C</^[a-zA-Z]*[0-9]*\z/>),
16111681only the initial value will be returned. So the following will only
16121682return an alpha:
16131683
16141684=end original
16151685
16161686指定された初期値がマジカルインクリメント処理の一部でない場合
1617(つまり、"/^[a-zA-Z]*[0-9]*\z/" にマッチングする、空でない文字列の場合)、
1687(つまり、C</^[a-zA-Z]*[0-9]*\z/> にマッチングする、空でない文字列の場合)、
16181688初期値のみが返されます。
16191689従って、以下はαのみを返します:
16201690
1621 use charnames 'greek';
1691 use charnames "greek";
16221692 my @greek_small = ("\N{alpha}" .. "\N{omega}");
16231693
16241694=begin original
16251695
1626To get lower-case greek letters, use this instead:
1696To get the 25 traditional lowercase Greek letters, including both sigmas,
1697you could use this instead:
16271698
16281699=end original
16291700
1630小文字のギリシャ文字を得るためには、代わりに以下のようにしてください:
1701両方のシグマを含む、25 文字の伝統的な小文字のギリシャ文字を得るためには、
1702代わりに以下のようにしてください:
16311703
1632 my @greek_small = map { chr } ( ord("\N{alpha}") .. ord("\N{omega}") );
1704 use charnames "greek";
1705 my @greek_small = map { chr }
1706 ord "\N{alpha}" .. ord "\N{omega}";
16331707
16341708=begin original
16351709
1710However, because there are I<many> other lowercase Greek characters than
1711just those, to match lowercase Greek characters in a regular expression,
1712you would use the pattern C</(?:(?=\p{Greek})\p{Lower})+/>.
1713
1714=end original
1715
1716しかし、小文字のギリシャ文字はここに書いたものよりも I<たくさん> あるので、
1717正規表現で小文字のギリシャ文字にマッチングさせるためには、
1718C</(?:(?=\p{Greek})\p{Lower})+/> というパターンを使います。
1719
1720=begin original
1721
16361722Because each operand is evaluated in integer form, C<2.18 .. 3.14> will
16371723return two elements in list context.
16381724
16391725=end original
16401726
16411727それぞれのオペランドは整数の形で評価されるので、C<2.18 .. 3.14> は
16421728リストコンテキストでは二つの要素を返します。
16431729
1730=begin original
1731
16441732 @list = (2.18 .. 3.14); # same as @list = (2 .. 3);
16451733
1734=end original
1735
1736 @list = (2.18 .. 3.14); # @list = (2 .. 3); と同じ
1737
16461738=head2 Conditional Operator
16471739X<operator, conditional> X<operator, ternary> X<ternary> X<?:>
16481740
16491741(条件演算子)
16501742
16511743=begin original
16521744
16531745Ternary "?:" is the conditional operator, just as in C. It works much
16541746like an if-then-else. If the argument before the ? is true, the
16551747argument before the : is returned, otherwise the argument after the :
16561748is returned. For example:
16571749
16581750=end original
16591751
16601752三項演算子の "?:" は、C の場合と同じ条件演算子です。
16611753これは、if-then-else のように働きます。
16621754"?" の前の引数が真であれば ":" の前の引数が返されますが、
16631755真でなければ、":" の後の引数が返されます。
16641756例えば:
16651757
16661758 printf "I have %d dog%s.\n", $n,
1667 ($n == 1) ? '' : "s";
1759 ($n == 1) ? "" : "s";
16681760
16691761=begin original
16701762
16711763Scalar or list context propagates downward into the 2nd
16721764or 3rd argument, whichever is selected.
16731765
16741766=end original
16751767
16761768スカラコンテキストかリストコンテキストかという状況は、
16771769選択された 2 番目もしくは 3 番目の引数にまで伝わります。
16781770
1771=begin original
1772
16791773 $a = $ok ? $b : $c; # get a scalar
16801774 @a = $ok ? @b : @c; # get an array
16811775 $a = $ok ? @b : @c; # oops, that's just a count!
16821776
1777=end original
1778
1779 $a = $ok ? $b : $c; # スカラを取る
1780 @a = $ok ? @b : @c; # 配列を取る
1781 $a = $ok ? @b : @c; # うわ、これは単なる数です!
1782
16831783=begin original
16841784
16851785The operator may be assigned to if both the 2nd and 3rd arguments are
16861786legal lvalues (meaning that you can assign to them):
16871787
16881788=end original
16891789
169017902 番目と 3 番目の引数双方が左辺値 (代入可能ということ)であれば、
16911791この演算子に代入を行なうこともできます:
16921792
16931793 ($a_or_b ? $a : $b) = $c;
16941794
16951795=begin original
16961796
16971797Because this operator produces an assignable result, using assignments
16981798without parentheses will get you in trouble. For example, this:
16991799
17001800=end original
17011801
17021802この演算子は代入可能な結果を生み出すので、
17031803括弧なしで代入を行うとおかしくなるかもしれません。
17041804例えばこれは:
17051805
17061806 $a % 2 ? $a += 10 : $a += 2
17071807
17081808=begin original
17091809
17101810Really means this:
17111811
17121812=end original
17131813
17141814以下を意味し:
17151815
17161816 (($a % 2) ? ($a += 10) : $a) += 2
17171817
17181818=begin original
17191819
17201820Rather than this:
17211821
17221822=end original
17231823
17241824以下のようにはなりません:
17251825
17261826 ($a % 2) ? ($a += 10) : ($a += 2)
17271827
17281828=begin original
17291829
17301830That should probably be written more simply as:
17311831
17321832=end original
17331833
17341834恐らく以下のようにもっと単純に書くべきでしょう:
17351835
17361836 $a += ($a % 2) ? 10 : 2;
17371837
17381838=head2 Assignment Operators
17391839X<assignment> X<operator, assignment> X<=> X<**=> X<+=> X<*=> X<&=>
17401840X<<< <<= >>> X<&&=> X<-=> X</=> X<|=> X<<< >>= >>> X<||=> X<//=> X<.=>
17411841X<%=> X<^=> X<x=>
17421842
17431843(代入演算子)
17441844
17451845=begin original
17461846
17471847"=" is the ordinary assignment operator.
17481848
17491849=end original
17501850
17511851"=" は通常の代入演算子です。
17521852
17531853=begin original
17541854
17551855Assignment operators work as in C. That is,
17561856
17571857=end original
17581858
17591859代入演算子は C の場合と同様の働きをします。
17601860つまり、
17611861
17621862 $a += 2;
17631863
17641864=begin original
17651865
17661866is equivalent to
17671867
17681868=end original
17691869
17701870は以下と等価です:
17711871
17721872 $a = $a + 2;
17731873
17741874=begin original
17751875
17761876although without duplicating any side effects that dereferencing the lvalue
17771877might trigger, such as from tie(). Other assignment operators work similarly.
17781878The following are recognized:
17791879
17801880=end original
17811881
17821882しかし、tie() のようなもので起こる左辺値の被参照による
17831883副作用が 2 回起こることはありません。
17841884他の代入演算も同様に働きます。
17851885以下のものが認識されます:
17861886
17871887 **= += *= &= <<= &&=
17881888 -= /= |= >>= ||=
17891889 .= %= ^= //=
17901890 x=
17911891
17921892=begin original
17931893
17941894Although these are grouped by family, they all have the precedence
17951895of assignment.
17961896
17971897=end original
17981898
17991899グループ分けしてありますが、これらはいずれも代入演算子として
18001900同じ優先順位となっています。
18011901
18021902=begin original
18031903
18041904Unlike in C, the scalar assignment operator produces a valid lvalue.
18051905Modifying an assignment is equivalent to doing the assignment and
18061906then modifying the variable that was assigned to. This is useful
18071907for modifying a copy of something, like this:
18081908
18091909=end original
18101910
18111911C と違って、スカラ代入演算子は有効な左辺値を作り出します。
18121912代入を修正することは、代入を行なってから、その代入された変数を修正するのと
18131913同じことになります。
18141914これは、以下のように何かのコピーを変更したいときに便利です:
18151915
1816 ($tmp = $global) =~ tr [A-Z] [a-z];
1916 ($tmp = $global) =~ tr [0-9] [a-j];
18171917
18181918=begin original
18191919
18201920Likewise,
18211921
18221922=end original
18231923
18241924同様に、
18251925
18261926 ($a += 2) *= 3;
18271927
18281928=begin original
18291929
18301930is equivalent to
18311931
18321932=end original
18331933
18341934は以下と等価です:
18351935
18361936 $a += 2;
18371937 $a *= 3;
18381938
18391939=begin original
18401940
18411941Similarly, a list assignment in list context produces the list of
18421942lvalues assigned to, and a list assignment in scalar context returns
18431943the number of elements produced by the expression on the right hand
18441944side of the assignment.
18451945
18461946=end original
18471947
18481948同様に、リストコンテキストでのリストへの代入は代入可能な左辺値のリストとなり、
18491949スカラコンテキストでのリストへの代入は代入の右側の式で作成された
18501950要素の数を返します。
18511951
1952=head2 The Triple-Dot Operator
1953X<...> X<... operator> X<yada-yada operator> X<whatever operator>
1954X<triple-dot operator>
1955
1956(3 点演算子)
1957
1958=begin original
1959
1960The triple-dot operator, C<...>, sometimes called the "whatever operator", the
1961"yada-yada operator", or the "I<et cetera>" operator, is a placeholder for
1962code. Perl parses it without error, but when you try to execute a whatever,
1963it throws an exception with the text C<Unimplemented>:
1964
1965=end original
1966
19673 点演算子 C<...>、(「何でも演算子」、「ヤダヤダ演算子」、「I<エトセトラ>」
1968演算子と呼ばれることもあります)はコードのためのプレースホルダです。
1969Perl はこれをエラーを出すことなくパースしますが、これを
1970実行しようとすると、C<Unimplemented> の文章と共に例外を発生させます:
1971
1972 sub unimplemented { ... }
1973
1974 eval { unimplemented() };
1975 if ($@ eq "Unimplemented" ) {
1976 say "Oh look, an exception--whatever.";
1977 }
1978
1979=begin original
1980
1981You can only use the triple-dot operator to stand in for a complete statement.
1982These examples of the triple-dot work:
1983
1984=end original
1985
19863 点演算子は完全な文の代わりにのみ使えます。
1987以下の例の 3 点演算子は動作します:
1988
1989 { ... }
1990
1991 sub foo { ... }
1992
1993 ...;
1994
1995 eval { ... };
1996
1997 sub foo {
1998 my ($self) = shift;
1999 ...;
2000 }
2001
2002 do {
2003 my $variable;
2004 ...;
2005 say "Hurrah!";
2006 } while $cheering;
2007
2008=begin original
2009
2010The yada-yada--or whatever--cannot stand in for an expression that is
2011part of a larger statement since the C<...> is also the three-dot version
2012of the binary range operator (see L<Range Operators>). These examples of
2013the whatever operator are still syntax errors:
2014
2015=end original
2016
2017C<...> は 2 項範囲演算子(L<Range Operators> を参照してください)の 3 点版でも
2018あるので、ヤダヤダ(あるいは何でも)はより大きな文の一部の式としては使えません。
2019以下の例の何でも演算子は文法エラーになります:
2020
2021 print ...;
2022
2023 open(PASSWD, ">", "/dev/passwd") or ...;
2024
2025 if ($condition && ...) { say "Hello" }
2026
2027=begin original
2028
2029There are some cases where Perl can't immediately tell the difference
2030between an expression and a statement. For instance, the syntax for a
2031block and an anonymous hash reference constructor look the same unless
2032there's something in the braces that give Perl a hint. The whatever
2033is a syntax error if Perl doesn't guess that the C<{ ... }> is a
2034block. In that case, it doesn't think the C<...> is the whatever
2035because it's expecting an expression instead of a statement:
2036
2037=end original
2038
2039式と文との違いをすぐに説明できない場合があります。
2040例えば、ブロックと無名ハッシュリファレンスのコンストラクタは、
2041Perl にヒントを与える中かっこがなければ同じに見えます。
2042何でも演算子は Perl が C<{ ... }> をブロックと判断できなかった場合は
2043文法エラーとなります。
2044この場合、文ではなく式と推測するので、C<...> は何でも演算子とは
2045判断されません:
2046
2047=begin original
2048
2049 my @transformed = map { ... } @input; # syntax error
2050
2051=end original
2052
2053 my @transformed = map { ... } @input; # 文法エラー
2054
2055=begin original
2056
2057You can use a C<;> inside your block to denote that the C<{ ... }> is
2058a block and not a hash reference constructor. Now the whatever works:
2059
2060=end original
2061
2062C<{ ... }> がブロックであって、ハッシュリファレンスのコンストラクタでは
2063ないことを示すためにブロックの中で C<;> を使えます。
2064これで何でも演算子は動作します:
2065
2066=begin original
2067
2068 my @transformed = map {; ... } @input; # ; disambiguates
2069
2070=end original
2071
2072 my @transformed = map {; ... } @input; # ; 曖昧でない
2073
2074=begin original
2075
2076 my @transformed = map { ...; } @input; # ; disambiguates
2077
2078=end original
2079
2080 my @transformed = map { ...; } @input; # ; 曖昧でない
2081
18522082=head2 Comma Operator
18532083X<comma> X<operator, comma> X<,>
18542084
18552085(コンマ演算子)
18562086
18572087=begin original
18582088
18592089Binary "," is the comma operator. In scalar context it evaluates
18602090its left argument, throws that value away, then evaluates its right
18612091argument and returns that value. This is just like C's comma operator.
18622092
18632093=end original
18642094
18652095二項演算子の "," はコンマ演算子です。
18662096スカラコンテキストではその左引数を評価し、その値を捨てて、
18672097それから右引数を評価し、その値を返します。
18682098これはちょうど、C のコンマ演算子と同じです。
18692099
18702100=begin original
18712101
18722102In list context, it's just the list argument separator, and inserts
18732103both its arguments into the list. These arguments are also evaluated
18742104from left to right.
18752105
18762106=end original
18772107
18782108リストコンテキストでは、これは単にリスト引数の区切り文字で、
18792109双方の引数をそのリストに挿入する働きがあります。
18802110これらの引数も左から右に評価されます。
18812111
18822112=begin original
18832113
18842114The C<< => >> operator is a synonym for the comma except that it causes
18852115its left operand to be interpreted as a string if it begins with a letter
18862116or underscore and is composed only of letters, digits and underscores.
18872117This includes operands that might otherwise be interpreted as operators,
18882118constants, single number v-strings or function calls. If in doubt about
1889this behaviour, the left operand can be quoted explicitly.
2119this behavior, the left operand can be quoted explicitly.
18902120
18912121=end original
18922122
18932123C<< => >> 演算子はコンマ演算子の同義語ですが、
18942124もし左オペランドが文字か下線で始まっていて、かつ文字、数字、下線でのみ
18952125構成されている場合、これを文字列として扱うという効果もあります。
18962126これには他の場所では演算子、定数、v-文字列、関数呼び出しとして扱われる
18972127オペランドを含みます。
18982128この振る舞いについて迷うことがあるなら、左オペランドを明示的に
18992129クォートすることも出来ます。
19002130
19012131=begin original
19022132
19032133Otherwise, the C<< => >> operator behaves exactly as the comma operator
19042134or list argument separator, according to context.
19052135
19062136=end original
19072137
19082138さもなければ、C<< => >> 演算子はコンテキストによって、
19092139カンマ演算子かリスト引数の区切り文字と全く同様に振る舞います。
19102140
19112141=begin original
19122142
19132143For example:
19142144
19152145=end original
19162146
19172147例えば:
19182148
19192149 use constant FOO => "something";
19202150
19212151 my %h = ( FOO => 23 );
19222152
19232153=begin original
19242154
19252155is equivalent to:
19262156
19272157=end original
19282158
19292159は、以下と等価です:
19302160
19312161 my %h = ("FOO", 23);
19322162
19332163=begin original
19342164
19352165It is I<NOT>:
19362166
19372167=end original
19382168
19392169これは I<違います>:
19402170
19412171 my %h = ("something", 23);
19422172
19432173=begin original
19442174
19452175The C<< => >> operator is helpful in documenting the correspondence
19462176between keys and values in hashes, and other paired elements in lists.
19472177
19482178=end original
19492179
19502180C<< => >> 演算子は、ハッシュのキーと値や、その他のリスト中の組となる
19512181要素の関係を表現するのに便利です。
19522182
19532183 %hash = ( $key => $value );
19542184 login( $username => $password );
19552185
19562186=head2 List Operators (Rightward)
19572187X<operator, list, rightward> X<list operator>
19582188
19592189(リスト演算子 (右方向))
19602190
19612191=begin original
19622192
1963On the right side of a list operator, it has very low precedence,
2193On the right side of a list operator, the comma has very low precedence,
19642194such that it controls all comma-separated expressions found there.
19652195The only operators with lower precedence are the logical operators
19662196"and", "or", and "not", which may be used to evaluate calls to list
19672197operators without the need for extra parentheses:
19682198
19692199=end original
19702200
1971リスト演算子の右側のものにとって、リスト演算子はとても低い優先順位になります
2201リスト演算子の右側のものにとって、カンマはとても低い優先順位になります;
19722202これによってコンマで区切った式をリスト演算子の引数として
19732203置くことができます。
19742204これよりも優先順位が低いものは、論理演算子の "and", "or", "not" のみで、
19752205余分な括弧を付けないリスト演算子の呼び出しを評価するために使えます:
19762206
1977 open HANDLE, "filename"
2207 open HANDLE, "< $file"
1978 or die "Can't open: $!\n";
2208 or die "Can't open $file: $!\n";
19792209
19802210=begin original
19812211
19822212See also discussion of list operators in L<Terms and List Operators (Leftward)>.
19832213
19842214=end original
19852215
19862216L<Terms and List Operators (Leftward)> のリスト演算子の議論も参照して下さい。
19872217
19882218=head2 Logical Not
19892219X<operator, logical, not> X<not>
19902220
19912221(論理否定)
19922222
19932223=begin original
19942224
19952225Unary "not" returns the logical negation of the expression to its right.
19962226It's the equivalent of "!" except for the very low precedence.
19972227
19982228=end original
19992229
20002230単項演算子の "not" は右側に来る式の否定を返します。
20012231これは、優先順位がずっと低いことを除いては "!" と等価です。
20022232
20032233=head2 Logical And
20042234X<operator, logical, and> X<and>
20052235
20062236(論理積)
20072237
20082238=begin original
20092239
20102240Binary "and" returns the logical conjunction of the two surrounding
2011expressions. It's equivalent to && except for the very low
2241expressions. It's equivalent to C<&&> except for the very low
2012precedence. This means that it short-circuits: i.e., the right
2242precedence. This means that it short-circuits: the right
20132243expression is evaluated only if the left expression is true.
20142244
20152245=end original
20162246
20172247二項演算子の "and" は両側の式の論理積を返します。
2018これは、優先順位がずっと低いことを除けば && と等価です。
2248これは、優先順位がずっと低いことを除けば C<&&> と等価です。
20192249つまり、これも短絡演算を行ない、右側の式は左側の式が
20202250「真」であった場合にのみ評価されます。
20212251
20222252=head2 Logical or, Defined or, and Exclusive Or
20232253X<operator, logical, or> X<operator, logical, xor>
20242254X<operator, logical, defined or> X<operator, logical, exclusive or>
20252255X<or> X<xor>
20262256
20272257(論理和と定義性和と排他論理和)
20282258
20292259=begin original
20302260
20312261Binary "or" returns the logical disjunction of the two surrounding
2032expressions. It's equivalent to || except for the very low precedence.
2262expressions. It's equivalent to C<||> except for the very low precedence.
2033This makes it useful for control flow
2263This makes it useful for control flow:
20342264
20352265=end original
20362266
20372267二項演算子の "or" は両側の式の論理和を返します。
2038これは、優先順位がずっと低いことを除いて || と等価です。
2268これは、優先順位がずっと低いことを除いて C<||> と等価です。
20392269これはフローを制御するのに有用です:
20402270
20412271 print FH $data or die "Can't write to FH: $!";
20422272
20432273=begin original
20442274
2045This means that it short-circuits: i.e., the right expression is evaluated
2275This means that it short-circuits: the right expression is evaluated
2046only if the left expression is false. Due to its precedence, you should
2276only if the left expression is false. Due to its precedence, you must
2047probably avoid using this for assignment, only for control flow.
2277be careful to avoid using it as replacement for the C<||> operator.
2278It usually works out better for flow control than in assignments:
20482279
20492280=end original
20502281
20512282つまり、これも短絡演算を行ない、右側の式は左側の式が
20522283「偽」であった場合にのみ評価されます。
2053優先度の関係で、これは代入には使わず、フロー制御のみに使うべきです。
2284優先度の関係で、これを C<||> 演算子置き換えに使うのは慎重に
2285避けなければなりません。
2286これは普通代入よりも、フローの制御でうまく動作します:
20542287
2288=begin original
2289
20552290 $a = $b or $c; # bug: this is wrong
20562291 ($a = $b) or $c; # really means this
20572292 $a = $b || $c; # better written this way
20582293
2294=end original
2295
2296 $a = $b or $c; # バグ: これは間違い
2297 ($a = $b) or $c; # 本当にしたいこと
2298 $a = $b || $c; # こう書いた方がいい
2299
20592300=begin original
20602301
20612302However, when it's a list-context assignment and you're trying to use
2062"||" for control flow, you probably need "or" so that the assignment
2303C<||> for control flow, you probably need "or" so that the assignment
20632304takes higher precedence.
20642305
20652306=end original
20662307
2067しかし、代入がリストコンテキストの時に "||" をフロー制御に使おうとする場合、
2308しかし、代入がリストコンテキストの時に C<||> をフロー制御に使おうとする場合、
20682309代入により大きな優先順位を持たせるために "or" が必要かもしれません。
20692310
2311=begin original
2312
20702313 @info = stat($file) || die; # oops, scalar sense of stat!
20712314 @info = stat($file) or die; # better, now @info gets its due
20722315
2316=end original
2317
2318 @info = stat($file) || die; # うわ、stat がスカラの意味だ!
2319 @info = stat($file) or die; # よりよい; @info はその目的を果たす
2320
20732321=begin original
20742322
20752323Then again, you could always use parentheses.
20762324
20772325=end original
20782326
20792327もちろん、常に括弧をつけてもよいです。
20802328
20812329=begin original
20822330
20832331Binary "xor" returns the exclusive-OR of the two surrounding expressions.
2084It cannot short circuit, of course.
2332It cannot short-circuit (of course).
20852333
20862334=end original
20872335
20882336二項演算子の "xor" は両側の式の排他論理和を返します。
2089これはもちろん短絡ではありません。
2337これは (もちろん) 短絡でません。
20902338
20912339=head2 C Operators Missing From Perl
20922340X<operator, missing from perl> X<&> X<*>
20932341X<typecasting> X<(TYPE)>
20942342
20952343(Perl にない C の演算子)
20962344
20972345=begin original
20982346
20992347Here is what C has that Perl doesn't:
21002348
21012349=end original
21022350
21032351C にあって Perl に無いものは以下の通りです:
21042352
21052353=over 8
21062354
21072355=item unary &
21082356
21092357=begin original
21102358
21112359Address-of operator. (But see the "\" operator for taking a reference.)
21122360
21132361=end original
21142362
21152363アドレス演算子。
21162364("\" 演算子がリファレンスのために用いられます。)
21172365
21182366=item unary *
21192367
21202368=begin original
21212369
21222370Dereference-address operator. (Perl's prefix dereferencing
21232371operators are typed: $, @, %, and &.)
21242372
21252373=end original
21262374
21272375被アドレス参照演算子。
21282376(Perl の被参照プリフィクス演算子が型づけを行ないます: $, @, %, &。)
21292377
21302378=item (TYPE)
21312379
21322380=begin original
21332381
21342382Type-casting operator.
21352383
21362384=end original
21372385
21382386型のキャスト演算子。
21392387
21402388=back
21412389
21422390=head2 Quote and Quote-like Operators
21432391X<operator, quote> X<operator, quote-like> X<q> X<qq> X<qx> X<qw> X<m>
21442392X<qr> X<s> X<tr> X<'> X<''> X<"> X<""> X<//> X<`> X<``> X<<< << >>>
21452393X<escape sequence> X<escape>
21462394
21472395(クォートとクォート風の演算子)
21482396
21492397=begin original
21502398
21512399While we usually think of quotes as literal values, in Perl they
21522400function as operators, providing various kinds of interpolating and
21532401pattern matching capabilities. Perl provides customary quote characters
21542402for these behaviors, but also provides a way for you to choose your
21552403quote character for any of them. In the following table, a C<{}> represents
21562404any pair of delimiters you choose.
21572405
21582406=end original
21592407
21602408クォートはリテラル値であると考えるのが普通ですが、Perl において、
21612409クォートは演算子として働き、さまざまな展開やパターンマッチの機能を
21622410持っています。
21632411そのような動作をさせるのに、Perl は慣習的にクォート文字を使っていますが、
21642412どの種類のクォートも、自分でクォート文字を選べるようになっています。
21652413以下の表では、{} がその選んだ区切文字のペアを示しています。
21662414
21672415=begin original
21682416
21692417 Customary Generic Meaning Interpolates
21702418 '' q{} Literal no
21712419 "" qq{} Literal yes
21722420 `` qx{} Command yes*
21732421 qw{} Word list no
21742422 // m{} Pattern match yes*
21752423 qr{} Pattern yes*
21762424 s{}{} Substitution yes*
21772425 tr{}{} Transliteration no (but see below)
2426 y{}{} Transliteration no (but see below)
21782427 <<EOF here-doc yes*
21792428
21802429 * unless the delimiter is ''.
21812430
21822431=end original
21832432
21842433 通常記法 汎用記法 意味 展開
21852434 =================================================
21862435 '' q{} リテラル 不可
21872436 "" qq{} リテラル 可
21882437 `` qx{} コマンド 可 *
21892438 qw{} 単語リスト 不可
21902439 // m{} パターンマッチ 可 *
21912440 qr{} パターン 可 *
21922441 s{}{} 置換 可 *
21932442 tr{}{} 変換 不可 (但し以下を参照のこと)
2443 y{}{} 変換 不可 (但し以下を参照のこと)
21942444 <<EOF ヒアドキュメント 可 *
21952445
21962446 * '' がデリミタでない場合のみ
21972447
21982448=begin original
21992449
22002450Non-bracketing delimiters use the same character fore and aft, but the four
2201sorts of brackets (round, angle, square, curly) will all nest, which means
2451sorts of ASCII brackets (round, angle, square, curly) all nest, which means
22022452that
22032453
22042454=end original
22052455
22062456選んだ区切文字が括弧の類でない場合には、前後の文字として同一のものを
2207使いますが、4 つの括弧 ((), <>, [], {}) の場合にはネストできます
2457使いますが、4 つの ASCII のかっこ ((), <>, [], {}) の場合にはネストできます;
22082458つまり、以下のものは、
22092459
2210 q{foo{bar}baz}
2460 q{foo{bar}baz}
22112461
22122462=begin original
22132463
22142464is the same as
22152465
22162466=end original
22172467
22182468以下と同じです。
22192469
2220 'foo{bar}baz'
2470 'foo{bar}baz'
22212471
22222472=begin original
22232473
22242474Note, however, that this does not always work for quoting Perl code:
22252475
22262476=end original
22272477
22282478しかし、以下のコードはクォートされた Perl コードでは
22292479いつも正しく動くわけではないことに注意してください:
22302480
2231 $s = q{ if($a eq "}") ... }; # WRONG
2481 $s = q{ if($a eq "}") ... }; # WRONG
22322482
22332483=begin original
22342484
2235is a syntax error. The C<Text::Balanced> module (from CPAN, and
2485is a syntax error. The C<Text::Balanced> module (standard as of v5.8,
2236starting from Perl 5.8 part of the standard distribution) is able
2486and from CPAN before then) is able to do this properly.
2237to do this properly.
22382487
22392488=end original
22402489
22412490これは文法エラーとなります。
2242C<Text::Balanced> モジュール(CPAN から、または Perl 5.8 からは標準配布
2491C<Text::Balanced> モジュール(Perl 5.8 からは標準配布、それ以前は CPAN に
2243一部です)はこれを適切に行います。
2492あります)はこれを適切に行います。
22442493
22452494=begin original
22462495
22472496There can be whitespace between the operator and the quoting
22482497characters, except when C<#> is being used as the quoting character.
22492498C<q#foo#> is parsed as the string C<foo>, while C<q #foo#> is the
22502499operator C<q> followed by a comment. Its argument will be taken
22512500from the next line. This allows you to write:
22522501
22532502=end original
22542503
2255演算子とクォート文字の間に空白を置くことも出来ます
2504演算子とクォート文字の間に空白を置くことも出来ます; ただし、C<#> を
2256ただし、C<#> をクォート文字として使う場合は例外です。
2505クォート文字として使う場合は例外です。
22572506C<q#foo#> は文字列 C<foo> としてパースされますが、
22582507C<q #foo#> は C<q> 演算子の後にコメントがあるとみなされます。
22592508この引数は次の行から取られます。つまり、以下のように書けます:
22602509
2510=begin original
2511
22612512 s {foo} # Replace foo
22622513 {bar} # with bar.
22632514
2515=end original
2516
2517 s {foo} # foo を
2518 {bar} # bar で置き換える
2519
22642520=begin original
22652521
2266The following escape sequences are available in constructs that interpolate
2522The following escape sequences are available in constructs that interpolate,
2267and in transliterations.
2523and in transliterations:
2268X<\t> X<\n> X<\r> X<\f> X<\b> X<\a> X<\e> X<\x> X<\0> X<\c> X<\N>
2524X<\t> X<\n> X<\r> X<\f> X<\b> X<\a> X<\e> X<\x> X<\0> X<\c> X<\N> X<\N{}>
2525X<\o{}>
22692526
22702527=end original
22712528
2272以下のエスケープシーケンスが展開と文字変換の構文で利用可能です
2529以下のエスケープシーケンスが展開と文字変換の構文で利用可能です:
2273X<\t> X<\n> X<\r> X<\f> X<\b> X<\a> X<\e> X<\x> X<\0> X<\c> X<\N>
2530X<\t> X<\n> X<\r> X<\f> X<\b> X<\a> X<\e> X<\x> X<\0> X<\c> X<\N> X<\N{}>
2531X<\o{}>
22742532
22752533=begin original
22762534
2277 \t tab (HT, TAB)
2535 Sequence Note Description
2278 \n newline (NL)
2536 \t tab (HT, TAB)
2279 \r return (CR)
2537 \n newline (NL)
2280 \f form feed (FF)
2538 \r return (CR)
2281 \b backspace (BS)
2539 \f form feed (FF)
2282 \a alarm (bell) (BEL)
2540 \b backspace (BS)
2283 \e escape (ESC)
2541 \a alarm (bell) (BEL)
2284 \033 octal char (example: ESC)
2542 \e escape (ESC)
2285 \x1b hex char (example: ESC)
2543 \x{263A} [1,8] hex char (example: SMILEY)
2286 \x{263a} wide hex char (example: SMILEY)
2544 \x1b [2,8] restricted range hex char (example: ESC)
2287 \c[ control char (example: ESC)
2545 \N{name} [3] named Unicode character or character sequence
2288 \N{name} named Unicode character
2546 \N{U+263D} [4,8] Unicode character (example: FIRST QUARTER MOON)
2547 \c[ [5] control char (example: chr(27))
2548 \o{23072} [6,8] octal char (example: SMILEY)
2549 \033 [7,8] restricted range octal char (example: ESC)
22892550
22902551=end original
22912552
2292 \t タブ (HT, TAB)
2553 シーケンス 注意 説明
2293 \n 改行 (NL)
2554 \t タブ (HT, TAB)
2294 \r 復帰 (CR)
2555 \n 改行 (NL)
2295 \f 改ページ (FF)
2556 \r 復帰 (CR)
2296 \b バックスペース (BS)
2557 \f 改ページ (FF)
2297 \a アラーム (BEL)
2558 \b バックスペース (BS)
2298 \e エスケープ (ESC)
2559 \a アラーム (BEL)
2299 \033 8 進数で表した文字 (例: ESC)
2560 \e エスケープ (ESC)
2300 \x1b 16 進数で表した文字 (例: ESC)
2561 \x{263a} [1,8] 16 進数で表した文字 (例: SMILEY)
2301 \x{263a} 16 進数で表したワイド文字 (例: SMILEY)
2562 \x1b [2,8] 範囲制限された 16 進数で表した文字 (例: ESC)
2302 \c[ コントロール文字 (例: ESC)
2563 \N{name} [3] 名前つき Unicode 文字または文字シーケンス
2303 \N{name} 名前つき Unicode 文字
2564 \N{U+263D} [4,8] Unicode 文字 (例: FIRST QUARTER MOON)
2565 \c[ [5] 制御文字 (例: ESC)
2566 \o{23072} [6,8] 8 進数で表した文字 (例: SMILEY)
2567 \033 [7,8] 範囲制限された 8 進数で表した文字 (例: ESC)
23042568
2569=over 4
2570
2571=item [1]
2572
23052573=begin original
23062574
2307The character following C<\c> is mapped to some other character by
2575The result is the character specified by the hexadecimal number between
2308converting letters to upper case and then (on ASCII systems) by inverting
2576the braces. See L</[8]> below for details on which character.
2309the 7th bit (0x40). The most interesting range is from '@' to '_'
2310(0x40 through 0x5F), resulting in a control character from 0x00
2311through 0x1F. A '?' maps to the DEL character. On EBCDIC systems only
2312'@', the letters, '[', '\', ']', '^', '_' and '?' will work, resulting
2313in 0x00 through 0x1F and 0x7F.
23142577
23152578=end original
23162579
2317C<\c> に引き続く文字、英字は大文字に変換された後、(ASCII システムは)
2580結果中かっこで囲まれた 16 進数指定された文字です。
23187 番目ビット (0x40) を反転させることで別の文字にマッピングされます。
2581の文字にる詳細については以下の L</[8]> を参照してください
2319最も興味深い範囲は '@' から '_' (0x40 から 0x5F) で、結果として
2320コントロール文字 0x00 から 0x1F になります。
2321'?' は DEL 文字にマッピングされます。
2322EBCDIC システムでは '@', 英字, '[', '\', ']', '^', '_', '?' のみが
2323動作し、結果として 0x00 から 0x1F と 0x7F になります。
23242582
23252583=begin original
23262584
2327B<NOTE>: Unlike C and other languages, Perl has no \v escape sequence for
2585Only hexadecimal digits are valid between the braces. If an invalid
2328the vertical tab (VT - ASCII 11), but you may use C<\ck> or C<\x0b>.
2586character is encountered, a warning will be issued and the invalid
2587character and all subsequent characters (valid or invalid) within the
2588braces will be discarded.
23292589
23302590=end original
23312591
2592中かっこの中には 16 進数字のみが妥当です。
2593不正な文字に遭遇すると、警告が発生し、中かっこの内側の不正な文字と
2594それ以降の文字(妥当でも不正でも)は捨てられます。
2595
2596=begin original
2597
2598If there are no valid digits between the braces, the generated character is
2599the NULL character (C<\x{00}>). However, an explicit empty brace (C<\x{}>)
2600will not cause a warning (currently).
2601
2602=end original
2603
2604中かっこの中に妥当な文字がなければ、生成される文字は NULL 文字
2605(C<\x{00}>) です。
2606しかし、明示的な空の中かっこ (C<\x{}>) は(今のところ)警告を出しません。
2607
2608=item [2]
2609
2610=begin original
2611
2612The result is the character specified by the hexadecimal number in the range
26130x00 to 0xFF. See L</[8]> below for details on which character.
2614
2615=end original
2616
2617結果は 0x00 から 0xFF の範囲の 16 進数で指定された文字です。
2618その文字に関する詳細については以下の L</[8]> を参照してください。
2619
2620=begin original
2621
2622Only hexadecimal digits are valid following C<\x>. When C<\x> is followed
2623by fewer than two valid digits, any valid digits will be zero-padded. This
2624means that C<\x7> will be interpreted as C<\x07>, and a lone <\x> will be
2625interpreted as C<\x00>. Except at the end of a string, having fewer than
2626two valid digits will result in a warning. Note that although the warning
2627says the illegal character is ignored, it is only ignored as part of the
2628escape and will still be used as the subsequent character in the string.
2629For example:
2630
2631=end original
2632
2633C<\x> に引き続くのは 16 進数字のみが妥当です。
2634C<\x> に引き続く妥当な数字が 2 桁ない場合、妥当な数字はゼロで
2635パッディングされます。
2636これは、C<\x7> は C<\x07> と解釈され、単独の <\x> は C<\x00> と
2637解釈されるということです。
2638文字列の末尾を例外として、妥当な数字が 2 桁ない場合は警告が発生します。
2639警告は不正な文字が無視されると言うにも関わらず、エスケープの一部のみが無視され、
2640文字列中の引き続く文字は使われるままであることに注意してください。
2641例えば:
2642
2643 Original Result Warns?
2644 "\x7" "\x07" no
2645 "\x" "\x00" no
2646 "\x7q" "\x07q" yes
2647 "\xq" "\x00q" yes
2648
2649=item [3]
2650
2651=begin original
2652
2653The result is the Unicode character or character sequence given by I<name>.
2654See L<charnames>.
2655
2656=end original
2657
2658結果は I<name> で指定される Unicode 文字または文字の並びです。
2659L<charnames> を参照してください。
2660
2661=item [4]
2662
2663=begin original
2664
2665C<\N{U+I<hexadecimal number>}> means the Unicode character whose Unicode code
2666point is I<hexadecimal number>.
2667
2668=end original
2669
2670C<\N{U+I<hexadecimal number>}> は、Unicode 符号位置が I<hexadecimal number> の
2671Unicode 文字を意味します。
2672
2673=item [5]
2674
2675=begin original
2676
2677The character following C<\c> is mapped to some other character as shown in the
2678table:
2679
2680=end original
2681
2682C<\c> に引き続く文字は以下の表に示すように他の文字にマッピングされます:
2683
2684 Sequence Value
2685 \c@ chr(0)
2686 \cA chr(1)
2687 \ca chr(1)
2688 \cB chr(2)
2689 \cb chr(2)
2690 ...
2691 \cZ chr(26)
2692 \cz chr(26)
2693 \c[ chr(27)
2694 \c] chr(29)
2695 \c^ chr(30)
2696 \c? chr(127)
2697
2698=begin original
2699
2700Also, C<\c\I<X>> yields C< chr(28) . "I<X>"> for any I<X>, but cannot come at the
2701end of a string, because the backslash would be parsed as escaping the end
2702quote.
2703
2704=end original
2705
2706また、C<\c\I<X>> は任意の I<X> について C< chr(28) . "I<X>"> となりますが、
2707文字列の末尾には来ません; 逆スラッシュは末尾のクォートをエスケープするように
2708パースされるからです。
2709
2710=begin original
2711
2712On ASCII platforms, the resulting characters from the list above are the
2713complete set of ASCII controls. This isn't the case on EBCDIC platforms; see
2714L<perlebcdic/OPERATOR DIFFERENCES> for the complete list of what these
2715sequences mean on both ASCII and EBCDIC platforms.
2716
2717=end original
2718
2719ASCII プラットフォームでは、上述の一覧からの結果の文字は ASCII 制御文字の
2720完全な集合です。
2721これは EBCDIC プラットフォームには当てはまりません; これらの並びが
2722ASCII と EBCDIC プラットフォームで何を意味するかの完全な一覧は
2723L<perlebcdic/OPERATOR DIFFERENCES> を参照してください。
2724
2725=begin original
2726
2727Use of any other character following the "c" besides those listed above is
2728discouraged, and some are deprecated with the intention of removing
2729those in Perl 5.16. What happens for any of these
2730other characters currently though, is that the value is derived by inverting
2731the 7th bit (0x40).
2732
2733=end original
2734
2735"c" に引き続いて上述した以外の文字を使うことは非推奨であり、Perl 5.16 での
2736削除を意図した廃止予定です。
2737しかし、現在のところ他の文字を置いたときに起こることは、値が第 7 ビット
2738(0x40) を反転させたものになります。
2739
2740=begin original
2741
2742To get platform independent controls, you can use C<\N{...}>.
2743
2744=end original
2745
2746プラットフォーム非依存の制御文字を得るには、C<\N{...}> を使ってください。
2747
2748=item [6]
2749
2750=begin original
2751
2752The result is the character specified by the octal number between the braces.
2753See L</[8]> below for details on which character.
2754
2755=end original
2756
2757結果は中かっこで囲まれた 8 進数で指定された文字です。
2758その文字に関する詳細については以下の L</[8]> を参照してください。
2759
2760=begin original
2761
2762If a character that isn't an octal digit is encountered, a warning is raised,
2763and the value is based on the octal digits before it, discarding it and all
2764following characters up to the closing brace. It is a fatal error if there are
2765no octal digits at all.
2766
2767=end original
2768
27698 進数でない文字に遭遇すると、警告が発生し、値はそこまでの 8 進数字を
2770基として、それ以降閉じ中かっこまでの全ての文字を捨てます。
27718 進数字がまったくないと致命的エラーになります。
2772
2773=item [7]
2774
2775=begin original
2776
2777The result is the character specified by the three-digit octal number in the
2778range 000 to 777 (but best to not use above 077, see next paragraph). See
2779L</[8]> below for details on which character.
2780
2781=end original
2782
2783結果は範囲 000 から 777 までの 3 桁の 8 進数で指定される文字です
2784(しかし 077 より上は使わないのが最良です; 次の段落を参照してください)。
2785その文字に関する詳細については以下の L</[8]> を参照してください。
2786
2787=begin original
2788
2789Some contexts allow 2 or even 1 digit, but any usage without exactly
2790three digits, the first being a zero, may give unintended results. (For
2791example, see L<perlrebackslash/Octal escapes>.) Starting in Perl 5.14, you may
2792use C<\o{}> instead, which avoids all these problems. Otherwise, it is best to
2793use this construct only for ordinals C<\077> and below, remembering to pad to
2794the left with zeros to make three digits. For larger ordinals, either use
2795C<\o{}> , or convert to something else, such as to hex and use C<\x{}>
2796instead.
2797
2798=end original
2799
2800一部のコンテキストでは 2 桁や、1 桁ですらゆるされますが、正確に 3 桁かつ
2801先頭が 0、以外の使い方は意図していない結果をもたらすかもしれません。
2802(例えば、L<perlrebackslash/Octal escapes> を参照してください。)
2803Perl 5.14 から、代わりに C<\o{}> を使えます; これはこれらすべての問題を
2804避けられます。
2805さもなければ、この構文を値 C<\077> 以下でのみ使用するのが最良です;
28063 桁にするために左側にゼロをパッディングするのを忘れないでください。
2807より大きな値では、C<\o{}> を使うか、代わりに 16 進数にして C<\x{}> を
2808使うような、他のものに変換してください。
2809
2810=begin original
2811
2812Having fewer than 3 digits may lead to a misleading warning message that says
2813that what follows is ignored. For example, C<"\128"> in the ASCII character set
2814is equivalent to the two characters C<"\n8">, but the warning C<Illegal octal
2815digit '8' ignored> will be thrown. To avoid this warning, make sure to pad
2816your octal number with C<0>'s: C<"\0128">.
2817
2818=end original
2819
28203 桁より少ない場合は以後が無視されるという間違った警告メッセージを
2821引き起こすかもしれません。
2822例えば、ASCII 文字集合での C<"\128"> は 2 文字 C<"\n8"> と等価ですが、
2823C<Illegal octal digit '8' ignored> という警告が投げられます。
2824この警告を避けるには、8 進数を C<0> でパッディングしてください: C<"\0128">。
2825
2826=item [8]
2827
2828=begin original
2829
2830Several constructs above specify a character by a number. That number
2831gives the character's position in the character set encoding (indexed from 0).
2832This is called synonymously its ordinal, code position, or code point. Perl
2833works on platforms that have a native encoding currently of either ASCII/Latin1
2834or EBCDIC, each of which allow specification of 256 characters. In general, if
2835the number is 255 (0xFF, 0377) or below, Perl interprets this in the platform's
2836native encoding. If the number is 256 (0x100, 0400) or above, Perl interprets
2837it as a Unicode code point and the result is the corresponding Unicode
2838character. For example C<\x{50}> and C<\o{120}> both are the number 80 in
2839decimal, which is less than 256, so the number is interpreted in the native
2840character set encoding. In ASCII the character in the 80th position (indexed
2841from 0) is the letter "P", and in EBCDIC it is the ampersand symbol "&".
2842C<\x{100}> and C<\o{400}> are both 256 in decimal, so the number is interpreted
2843as a Unicode code point no matter what the native encoding is. The name of the
2844character in the 100th position (indexed by 0) in Unicode is
2845C<LATIN CAPITAL LETTER A WITH MACRON>.
2846
2847=end original
2848
2849上述のいくつかの構造は文字を数値で指定しています。
2850この値は文字集合エンコーディングで (0 から始めた) 文字の位置を指定します。
2851これは同意語として序数(ordinal)、コード位置(code position)、
2852符号位置(code point)と呼ばれます。
2853Perl は現在のところ、それぞれ 256 文字を定義している ASCII/Latin1 または
2854EBCDIC のどちらかのネイティブエンコーディングを持つプラットフォームで
2855動作します。
2856一般的に、数値が 255 (0xFF, 0377) 以下なら、Perl はこれをプラットフォームの
2857ネイティブエンコーディングと解釈します。
2858数値が 256 (0x100, 0400) 以上なら、Perl はこれを Unicode 符号位置と解釈し、
2859結果は対応する Unicode 文字となります。
2860例えば C<\x{50}> と C<\o{120}> はどちらも 10 進数では 80 で、これは 256 より
2861小さいので、数値はネイティブ文字集合エンコーディングとして解釈されます。
2862ASCII では (0 から始めて) 80 番目の位置の文字は "P" で、EBCDIC では
2863アンパサンド記号 "&" です。
2864C<\x{100}> と C<\o{400}> はどちらも 10 進数では 256 なので、数値は
2865ネイティブエンコーディングが何かに関わらず Unicode 符号位置として解釈されます。
2866Unicode での (0 から始めて) 100 番目の位置の文字の名前は
2867C<LATIN CAPITAL LETTER A WITH MACRON> です。
2868
2869=begin original
2870
2871There are a couple of exceptions to the above rule. C<\N{U+I<hex number>}> is
2872always interpreted as a Unicode code point, so that C<\N{U+0050}> is "P" even
2873on EBCDIC platforms. And if L<C<S<use encoding>>|encoding> is in effect, the
2874number is considered to be in that encoding, and is translated from that into
2875the platform's native encoding if there is a corresponding native character;
2876otherwise to Unicode.
2877
2878=end original
2879
2880上述の規則には二つの例外があります。
2881C<\N{U+I<hex number>}> は常に Unicode 符号位置として解釈されるので、
2882C<\N{U+0050}> は EBCDIC プラットフォームでも "P" です。
2883そして L<C<S<use encoding>>|encoding> が有効なら、数値はその
2884エンコーディングであると考えられ、対応するネイティブな文字があるなら
2885プラットフォームのネイティブなエンコーディングに変換されます; さもなければ
2886Unicode です。
2887
2888=back
2889
2890=begin original
2891
2892B<NOTE>: Unlike C and other languages, Perl has no C<\v> escape sequence for
2893the vertical tab (VT - ASCII 11), but you may use C<\ck> or C<\x0b>. (C<\v>
2894does have meaning in regular expression patterns in Perl, see L<perlre>.)
2895
2896=end original
2897
23322898B<注意>: C やその他の言語と違って、Perl は垂直タブ (VT - ASCII 11) のための
23332899\v エスケープシーケンスはありませんが、C<\ck> または C<\x0b> が使えます。
2900(C<\v> は Perl の正規表現パターンでは意味があります; L<perlre> を
2901参照してください。)
23342902
23352903=begin original
23362904
2337The following escape sequences are available in constructs that interpolate
2905The following escape sequences are available in constructs that interpolate,
23382906but not in transliterations.
23392907X<\l> X<\u> X<\L> X<\U> X<\E> X<\Q>
23402908
23412909=end original
23422910
23432911以下のエスケープシーケンスが展開と文字変換の構文で利用可能です。
23442912X<\l> X<\u> X<\L> X<\U> X<\E> X<\Q>
23452913
23462914=begin original
23472915
2348 \l lowercase next char
2916 \l lowercase next character only
2349 \u uppercase next char
2917 \u titlecase (not uppercase!) next character only
2350 \L lowercase till \E
2918 \L lowercase all characters till \E seen
2351 \U uppercase till \E
2919 \U uppercase all characters till \E seen
2352 \E end case modification
23532920 \Q quote non-word characters till \E
2921 \E end either case modification or quoted section
2922 (whichever was last seen)
23542923
23552924=end original
23562925
2357 \l 次の文字を小文字にする
2926 \l 次の文字だけを小文字にする
2358 \u 次の文字を大文字にする
2927 \u 次の文字だけタイトル文字(大文字ではありません!)にする
2359 \L \E まで小文字にする
2928 \L \E まで小文字にする
2360 \U \E まで大文字にする
2929 \U \E まで大文字にする
2361 \E 変更の終わり
2930 \Q \E まで非単語文字をクォートする
2362 \Q \E まで非単語文字クォートする
2931 \E文字小文字変換かクォート部分(どちらか最後に現れたもの)を
2932 終了させる
23632933
23642934=begin original
23652935
2936C<\L>, C<\U>, and C<\Q> can stack, in which case you need one
2937C<\E> for each. For example:
2938
2939=end original
2940
2941C<\L>, C<\U>, C<\Q> はスタックできます; この場合それぞれに対して C<\E> が
2942必要です。
2943例えば:
2944
2945 say "This \Qquoting \ubusiness \Uhere isn't quite\E done yet,\E is it?";
2946 This quoting\ Business\ HERE\ ISN\'T\ QUITE\ done\ yet\, is it?
2947
2948=begin original
2949
23662950If C<use locale> is in effect, the case map used by C<\l>, C<\L>,
2367C<\u> and C<\U> is taken from the current locale. See L<perllocale>.
2951C<\u>, and C<\U> is taken from the current locale. See L<perllocale>.
2368If Unicode (for example, C<\N{}> or wide hex characters of 0x100 or
2952If Unicode (for example, C<\N{}> or code points of 0x100 or
2369beyond) is being used, the case map used by C<\l>, C<\L>, C<\u> and
2953beyond) is being used, the case map used by C<\l>, C<\L>, C<\u>, and
2370C<\U> is as defined by Unicode. For documentation of C<\N{name}>,
2954C<\U> is as defined by Unicode. That means that case-mapping
2371see L<charnames>.
2955a single character can sometimes produce several characters.
23722956
23732957=end original
23742958
23752959C<use locale> が有効の場合、C<\l>, C<\L>, C<\u>, C<\U> で使われる
23762960大文字小文字テーブルは現在のロケールのものが使われます。
23772961L<perllocale> を参照して下さい。
2378(例えば、C<\N{}> や、0x100 以上のワイド 16 進文字を使った) Unicode が
2962(例えば、C<\N{}> や、0x100 以上の符号位置の) Unicode が
23792963使われている場合、C<\l>, C<\L>, C<\u>, C<\U> で使われる大文字小文字
23802964テーブルは Unicode で定義されているものになります。
2381C<\N{name}> ドキュメトに関して、L<charnames> 参照して下さい。
2965これは、単一文字の大文字小文字マッピ複数の文字生成することが
2966あるということです。
23822967
23832968=begin original
23842969
23852970All systems use the virtual C<"\n"> to represent a line terminator,
23862971called a "newline". There is no such thing as an unvarying, physical
23872972newline character. It is only an illusion that the operating system,
23882973device drivers, C libraries, and Perl all conspire to preserve. Not all
23892974systems read C<"\r"> as ASCII CR and C<"\n"> as ASCII LF. For example,
2390on a Mac, these are reversed, and on systems without line terminator,
2975on the ancient Macs (pre-MacOS X) of yesteryear, these used to be reversed,
2391printing C<"\n"> may emit no actual data. In general, use C<"\n"> when
2976and on systems without line terminator,
2977printing C<"\n"> might emit no actual data. In general, use C<"\n"> when
23922978you mean a "newline" for your system, but use the literal ASCII when you
23932979need an exact character. For example, most networking protocols expect
23942980and prefer a CR+LF (C<"\015\012"> or C<"\cM\cJ">) for line terminators,
23952981and although they often accept just C<"\012">, they seldom tolerate just
23962982C<"\015">. If you get in the habit of using C<"\n"> for networking,
23972983you may be burned some day.
23982984X<newline> X<line terminator> X<eol> X<end of line>
23992985X<\n> X<\r> X<\r\n>
24002986
24012987=end original
24022988
24032989全てのシステムでは "newline" と呼ばれる行端末子を表現するために
24042990仮想的な C<"\n"> が用いられます。
24052991普遍の、物理的な "newline" 文字と言うものはありません。
24062992オペレーティングシステム、デバイスドライバ、C ライブラリ、Perl が全て
24072993協力して保存しようとすると言うのは単なる幻想です。
24082994全てのシステムで C<"\r"> を ASCII CR として、また C<"\n"> を
24092995ASCII LF として読み込むわけではありません。
2410例えば Mac ではこれらは保存され、行端末子のないシステムでは
2996例えば昔の Mac (MacOS X 以前)ではこれらは保存され、
2997行端末子のないシステムでは、
24112998C<"\n"> を print しても実際のデータは何も出力しません。
24122999一般に、システムで "newline" を意味したいときには C<"\n"> を使いますが、
24133000正確な文字が必要な場合はリテラルな ASCII を使います。
24143001例えば、ほとんどのネットワークプロトコルでは行端末子として
24153002CR+LF (C<"\015\012"> または C<"\cM\cJ">) を予想し、また好みますが、
24163003しばしば C<"\012"> だけでも許容し、さらに時々は C<"\015"> だけでも認めます。
24173004もしネットワーク関係で C<"\n"> を使う習慣がついていると、
24183005いつか痛い目を見ることになるでしょう。
3006X<newline> X<line terminator> X<eol> X<end of line>
3007X<\n> X<\r> X<\r\n>
24193008
24203009=begin original
24213010
24223011For constructs that do interpolate, variables beginning with "C<$>"
24233012or "C<@>" are interpolated. Subscripted variables such as C<$a[3]> or
24243013C<< $href->{key}[0] >> are also interpolated, as are array and hash slices.
24253014But method calls such as C<< $obj->meth >> are not.
24263015
24273016=end original
24283017
24293018展開が行なわれる構文では、"C<$>" や "C<@>" で始まる変数が展開されます。
2430Subscripted variables such as C<$a[3]> or
3019C<$a[3]> や C<< $href->{key}[0] >> のような添え字付き変数もまた
2431C<< $href->{key}[0] >> もまた配列やハッシュのスライスのように展開されます。
3020配列やハッシュのスライスのように展開されます。
24323021しかし、C<< $obj->meth >> のようなメソッド呼び出しは展開されません。
24333022
24343023=begin original
24353024
24363025Interpolating an array or slice interpolates the elements in order,
24373026separated by the value of C<$">, so is equivalent to interpolating
2438C<join $", @array>. "Punctuation" arrays such as C<@*> are only
3027C<join $", @array>. "Punctuation" arrays such as C<@*> are usually
2439interpolated if the name is enclosed in braces C<@{*}>, but special
3028interpolated only if the name is enclosed in braces C<@{*}>, but the
2440arrays C<@_>, C<@+>, and C<@-> are interpolated, even without braces.
3029arrays C<@_>, C<@+>, and C<@-> are interpolated even without braces.
24413030
24423031=end original
24433032
24443033配列やスライスの展開は、要素を順番に、C<$"> の値で分割して展開されるので、
24453034C<join $", @array> の展開と等価です。
2446C<@*> のような「句読点」配列は名前が C<@{*}> のように中かっこで囲われている
3035C<@*> のような「句読点」配列は普通は名前が C<@{*}> のように中かっこで
2447場合にのみ展開されますが、特殊配列 C<@_>, C<@+>, C<@-> は中かっこなしでも
3036囲われている場合にのみ展開されますが、配列 C<@_>, C<@+>, C<@-> は
2448展開されます。
3037中かっこなしでも展開されます。
24493038
24503039=begin original
24513040
2452You cannot include a literal C<$> or C<@> within a C<\Q> sequence.
3041For double-quoted strings, the quoting from C<\Q> is applied after
2453An unescaped C<$> or C<@> interpolates the corresponding variable,
3042interpolation and escapes are processed.
2454while escaping will cause the literal string C<\$> to be inserted.
2455You'll need to write something like C<m/\Quser\E\@\Qhost/>.
24563043
24573044=end original
24583045
2459C<\Q> シーケンス中にリテラルな C<$> や C<@> を入れることできません。
3046ダブルクォートされた文字列では、C<\Q> からクォート文字変換と
2460エスケープされない C<$> や C<@> は対応する変数変換されます。
3047エスケープが処理された後適用されます。
2461一方、エスケープすると、リテラルな文字列 C<\$> が挿入されます。
3049 "abc\Qfoo\tbar$s\Exyz"
3050
3051=begin original
3052
3053is equivalent to
3054
3055=end original
3056
3057は以下と等価です:
3058
3059 "abc" . quotemeta("foo\tbar$s") . "xyz"
3060
3061=begin original
3062
3063For the pattern of regex operators (C<qr//>, C<m//> and C<s///>),
3064the quoting from C<\Q> is applied after interpolation is processed,
3065but before escapes are processed. This allows the pattern to match
3066literally (except for C<$> and C<@>). For example, the following matches:
3067
3068=end original
3069
3070正規表現演算子 (C<qr//>, C<m//> and C<s///>) のパターンでは、
3071C<\Q> によるクォートは変数展開が行われた後、エスケープが処理される前に
3072適用されます。
3073これによりパターンを (C<$> and C<@>) 以外はリテラルにマッチングすることが
3074出来ます。
3075例えば、以下はマッチングします:
3076
3077 '\s\t' =~ /\Q\s\t/
3078
3079=begin original
3080
3081Because C<$> or C<@> trigger interpolation, you'll need to use something
3082like C</\Quser\E\@\Qhost/> to match them literally.
3083
3084=end original
3085
3086C<$> や C<@> は変換を引き起こすので、リテラルにマッチングさせるためには
24623087C<m/\Quser\E\@\Qhost/> などという風に書く必要があります。
24633088
24643089=begin original
24653090
24663091Patterns are subject to an additional level of interpretation as a
24673092regular expression. This is done as a second pass, after variables are
24683093interpolated, so that regular expressions may be incorporated into the
24693094pattern from the variables. If this is not what you want, use C<\Q> to
24703095interpolate a variable literally.
24713096
24723097=end original
24733098
24743099パターンはさらに、正規表現として展開が行なわれます。
24753100これは、変数が展開された後の 2 回目のパスで行なわれるので、変数に
24763101正規表現を含めておき、パターンの中へ展開することができます。
24773102もし、そうしたくないのであれば、C<\Q> を使うと変数の内容を文字通りに
24783103展開することができます。
24793104
24803105=begin original
24813106
24823107Apart from the behavior described above, Perl does not expand
24833108multiple levels of interpolation. In particular, contrary to the
24843109expectations of shell programmers, back-quotes do I<NOT> interpolate
24853110within double quotes, nor do single quotes impede evaluation of
24863111variables when used within double quotes.
24873112
24883113=end original
24893114
24903115上記の振る舞いを除けば、Perl は 複数の段階を踏んで展開を行ないません。
24913116特に、シェルのプログラマの期待とは裏腹に、
24923117バッククォートはダブルクォートの中では展開されませんし、シングルクォートが
24933118ダブルクォートの中で使われても、変数の展開を妨げることは I<ありません>。
24943119
24953120=head2 Regexp Quote-Like Operators
24963121X<operator, regexp>
24973122
24983123(正規表現のクォート風の演算子)
24993124
25003125=begin original
25013126
25023127Here are the quote-like operators that apply to pattern
25033128matching and related activities.
25043129
25053130=end original
25063131
25073132以下はパターンマッチングと関連する行動に関するクォート風の演算子です。
25083133
25093134=over 8
25103135
2511=item qr/STRING/msixpo
3136=item qr/STRING/msixpodual
25123137X<qr> X</i> X</m> X</o> X</s> X</x> X</p>
25133138
25143139=begin original
25153140
25163141This operator quotes (and possibly compiles) its I<STRING> as a regular
25173142expression. I<STRING> is interpolated the same way as I<PATTERN>
25183143in C<m/PATTERN/>. If "'" is used as the delimiter, no interpolation
25193144is done. Returns a Perl value which may be used instead of the
2520corresponding C</STRING/msixpo> expression. The returned value is a
3145corresponding C</STRING/msixpodual> expression. The returned value is a
25213146normalized version of the original pattern. It magically differs from
25223147a string containing the same characters: C<ref(qr/x/)> returns "Regexp",
25233148even though dereferencing the result returns undef.
25243149
25253150=end original
25263151
25273152この演算子は I<STRING> を正規表現としてクォートします
25283153(そして可能ならコンパイルします)。
25293154I<STRING> は C<m/PATTERN/> 内の I<PATTERN> と同様に文字変換されます。
25303155"'" がデリミタとして使用された場合、文字変換は行われません。
2531対応する C</STRING/msixpo> 表現の代わりに使われた Perl の値を返します。
3156対応する C</STRING/msixpodual> 表現の代わりに使われた Perl の値を返します。
25323157返り値は元のパターンを正規化したものです。
25333158これは不思議なことに、同じ文字を含む文字列とは異なります:
25343159C<ref(qr/x/)> は、結果をデリファレンスすると未定義値を返すにも関わらず、
25353160"Regexp" を返します。
25363161
25373162=begin original
25383163
25393164For example,
25403165
25413166=end original
25423167
25433168例えば:
25443169
25453170 $rex = qr/my.STRING/is;
25463171 print $rex; # prints (?si-xm:my.STRING)
25473172 s/$rex/foo/;
25483173
25493174=begin original
25503175
25513176is equivalent to
25523177
25533178=end original
25543179
25553180は以下と等価です:
25563181
25573182 s/my.STRING/foo/is;
25583183
25593184=begin original
25603185
25613186The result may be used as a subpattern in a match:
25623187
25633188=end original
25643189
25653190結果はマッチのサブパターンとして使えます:
25663191
3192=begin original
3193
25673194 $re = qr/$pattern/;
25683195 $string =~ /foo${re}bar/; # can be interpolated in other patterns
25693196 $string =~ $re; # or used standalone
25703197 $string =~ /$re/; # or this way
25713198
3199=end original
3200
3201 $re = qr/$pattern/;
3202 $string =~ /foo${re}bar/; # 他のパターンに展開できる
3203 $string =~ $re; # または単独で使う
3204 $string =~ /$re/; # またはこのようにする
3205
25723206=begin original
25733207
2574Since Perl may compile the pattern at the moment of execution of qr()
3208Since Perl may compile the pattern at the moment of execution of the qr()
25753209operator, using qr() may have speed advantages in some situations,
25763210notably if the result of qr() is used standalone:
25773211
25783212=end original
25793213
25803214Perl は qr() 演算子を実行する瞬間にパターンをコンパイルするので、
2581qr() を使うことでいくつかの場面で速度的に有利になります
3215qr() を使うことでいくつかの場面で速度的に有利になります;
25823216特に qr() の結果が独立して使われる場合に有利になります。
25833217
25843218 sub match {
25853219 my $patterns = shift;
25863220 my @compiled = map qr/$_/i, @$patterns;
25873221 grep {
25883222 my $success = 0;
25893223 foreach my $pat (@compiled) {
25903224 $success = 1, last if /$pat/;
25913225 }
25923226 $success;
25933227 } @_;
25943228 }
25953229
25963230=begin original
25973231
25983232Precompilation of the pattern into an internal representation at
25993233the moment of qr() avoids a need to recompile the pattern every
26003234time a match C</$pat/> is attempted. (Perl has many other internal
26013235optimizations, but none would be triggered in the above example if
26023236we did not use qr() operator.)
26033237
26043238=end original
26053239
26063240qr() の時点でパターンを内部表現にプリコンパイルすることにより、C</$pat/> を
2607試みる毎に毎回パターンを再コンパイルするのを避けることができます
3241試みる毎に毎回パターンを再コンパイルするのを避けることができます
26083242(Perl はその他にも多くの内部最適化を行いますが、上の例で qr() 演算子を
2609使わなかった場合はどの最適化も行われません)
3243使わなかった場合はどの最適化も行われません。)
26103244
26113245=begin original
26123246
2613Options are:
3247Options (specified by the following modifiers) are:
26143248
26153249=end original
26163250
2617オプションは以下の通りです:
3251(以下の修飾子で指定される)オプションは以下の通りです:
26183252
26193253=begin original
26203254
26213255 m Treat string as multiple lines.
26223256 s Treat string as single line. (Make . match a newline)
26233257 i Do case-insensitive pattern matching.
26243258 x Use extended regular expressions.
26253259 p When matching preserve a copy of the matched string so
26263260 that ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} will be defined.
26273261 o Compile pattern only once.
3262 l Use the locale
3263 u Use Unicode rules
3264 a Use ASCII for \d, \s, \w; specifying two a's further restricts
3265 /i matching so that no ASCII character will match a non-ASCII
3266 one
3267 d Use Unicode or native charset, as in 5.12 and earlier
26283268
26293269=end original
26303270
2631 m 文字列を複数行として扱う
3271 m 文字列を複数行として扱う
2632 s 文字列を一行として扱う (. が 改行にマッチングするようにする)
3272 s 文字列を一行として扱う (. が 改行にマッチングするようにする)
2633 i パターンマッチにおいて大文字小文字を区別しない
3273 i パターンマッチにおいて大文字小文字を区別しない
2634 x 拡張正規表現を使う
3274 x 拡張正規表現を使う
26353275 p マッチング時にマッチングした文字列を保存するので、
2636 ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} が定義される
3276 ${^PREMATCH}, ${^MATCH}, ${^POSTMATCH} が定義される
2637 o 一度だけコンパイルする
3277 o 一度だけコンパイルする
3278 l ロケールを使う
3279 u Unicode の規則を使う
3280 a \d, \s, \w に ASCII を使う; a を二つ指定すると、/i で ASCII 文字が
3281 非 ASCII 文字にマッチングしないようにさらに制限する
3282 d 5.12 以降かどうかで、Unicode かネイティブな文字集合を使う
26383283
26393284=begin original
26403285
26413286If a precompiled pattern is embedded in a larger pattern then the effect
2642of 'msixp' will be propagated appropriately. The effect of the 'o'
3287of "msixpluad" will be propagated appropriately. The effect the "o"
26433288modifier has is not propagated, being restricted to those patterns
26443289explicitly using it.
26453290
26463291=end original
26473292
26483293プリコンパイルされたパターンがより大きいパターンに組み込まれている場合、
2649'msixp' の効果は適切に伝播します。
3294"msixpluad" の効果は適切に伝播します。
2650'o' 修飾子の効果は伝播せず、明示的に使われたパターンに制限されます。
3295"o" 修飾子の効果は伝播せず、明示的に使われたパターンに制限されます。
26513296
26523297=begin original
26533298
3299The last four modifiers listed above, added in Perl 5.14,
3300control the character set semantics.
3301
3302=end original
3303
3304上述のうち最後の四つの修飾子は Perl 5.14 で追加され、文字集合の意味論を
3305制御します。
3306
3307=begin original
3308
26543309See L<perlre> for additional information on valid syntax for STRING, and
2655for a detailed look at the semantics of regular expressions.
3310for a detailed look at the semantics of regular expressions. In
3311particular, all the modifiers execpt C</o> are further explained in
3312L<perlre/Modifiers>. C</o> is described in the next section.
26563313
26573314=end original
26583315
26593316STRING として有効な文法に関する追加の情報と、正規表現の意味論に関する
26603317詳細については、L<perlre> を参照してください。
3318特に、C</o> 以外の全ての修飾子については L<perlre/Modifiers> でさらに
3319説明されています。
3320C</o> は次の節に記述されています。
26613321
2662=item m/PATTERN/msixpogc
3322=item m/PATTERN/msixpodualgc
26633323X<m> X<operator, match>
26643324X<regexp, options> X<regexp> X<regex, options> X<regex>
26653325X</m> X</s> X</i> X</x> X</p> X</o> X</g> X</c>
26663326
2667=item /PATTERN/msixpogc
3327=item /PATTERN/msixpodualgc
26683328
26693329=begin original
26703330
26713331Searches a string for a pattern match, and in scalar context returns
26723332true if it succeeds, false if it fails. If no string is specified
26733333via the C<=~> or C<!~> operator, the $_ string is searched. (The
26743334string specified with C<=~> need not be an lvalue--it may be the
26753335result of an expression evaluation, but remember the C<=~> binds
2676rather tightly.) See also L<perlre>. See L<perllocale> for
3336rather tightly.) See also L<perlre>.
2677discussion of additional considerations that apply when C<use locale>
2678is in effect.
26793337
26803338=end original
26813339
26823340パターンマッチで文字列検索を行ない、スカラコンテキストでは成功したときは真、
26833341失敗したときは偽を返します。
26843342C<=~> 演算子か C<!~> 演算子で検索対象の文字列を示さなかったときには、
26853343C<$_> の文字列が検索対象となります。
2686(C<=~> で指定される文字列は、左辺値である必要はありません
3344(C<=~> で指定される文字列は、左辺値である必要はありません--
26873345式を評価した結果でもかまいませんが、C<=~> の優先順位がいくぶん高いことに
26883346注意してください。)
26893347L<perlre> も参照してください。
2690C<use locale> が有効の場合の議論については L<perllocale> を参照して下さい。
26913348
26923349=begin original
26933350
2694Options are as described in C<qr//>; in addition, the following match
3351Options are as described in C<qr//> above; in addition, the following match
26953352process modifiers are available:
26963353
26973354=end original
26983355
2699オプションは C<qr//> に記述されています; さらに、以下のマッチング処理
3356オプションは上述した C<qr//> に記述されています; さらに、以下の
2700修飾子が利用可能です:
3357マッチング処理修飾子が利用可能です:
27013358
27023359=begin original
27033360
2704 g Match globally, i.e., find all occurrences.
3361 g Match globally, i.e., find all occurrences.
2705 c Do not reset search position on a failed match when /g is in effect.
3362 c Do not reset search position on a failed match when /g is in effect.
27063363
27073364=end original
27083365
2709 g グローバルにマッチ、つまり、すべてを探し出す
3366 g グローバルにマッチング、つまり、すべてを探し出す
2710 c /g が有効なとき、マッチングに失敗しても検索位置をリセットしない
3367 c /g が有効なとき、マッチングに失敗しても検索位置をリセットしない
27113368
27123369=begin original
27133370
27143371If "/" is the delimiter then the initial C<m> is optional. With the C<m>
2715you can use any pair of non-alphanumeric, non-whitespace characters
3372you can use any pair of non-whitespace (ASCII) characters
27163373as delimiters. This is particularly useful for matching path names
27173374that contain "/", to avoid LTS (leaning toothpick syndrome). If "?" is
2718the delimiter, then the match-only-once rule of C<?PATTERN?> applies.
3375the delimiter, then a match-only-once rule applies,
3376described in C<m?PATTERN?> below.
27193377If "'" is the delimiter, no interpolation is performed on the PATTERN.
3378When using a character valid in an identifier, whitespace is required
3379after the C<m>.
27203380
27213381=end original
27223382
27233383区切文字が "/" のときには、最初の C<m> は付けても付けなくてもかまいません。
2724C<m> を付けるときには、英数字でも空白でもない、任意の文字のペアを
3384C<m> を付けるときには、(ASCII の)空白でもない、任意の文字のペアを
27253385区切文字として使うことができます。
27263386これは特に、"/" を含むパス名にパターンマッチングを行なうときに、
27273387LTS (傾斜楊枝症候群) を避けるために便利でしょう。
3388"?" がデリミタなら、後述する C<m?PATTERN?> にある「一度だけマッチング」
3389ルールが適用されます。
27283390"'" がデリミタの場合、PATTERN に対する展開は行われません。
3391識別子として有効な文字を使う場合、C<m> の後に空白が必要です。
27293392
27303393=begin original
27313394
2732PATTERN may contain variables, which will be interpolated (and the
3395PATTERN may contain variables, which will be interpolated
2733pattern recompiled) every time the pattern search is evaluated, except
3396every time the pattern search is evaluated, except
27343397for when the delimiter is a single quote. (Note that C<$(>, C<$)>, and
27353398C<$|> are not interpolated because they look like end-of-string tests.)
2736If you want such a pattern to be compiled only once, add a C</o> after
3399Perl will not recompile the pattern unless an interpolated
2737the trailing delimiter. This avoids expensive run-time recompilations,
3400variable that it contains changes. You can force Perl to skip the
2738and is useful when the value you are interpolating won't change over
3401test and never recompile by adding a C</o> (which stands for "once")
2739the life of the script. However, mentioning C</o> constitutes a promise
3402after the trailing delimiter.
2740that you won't change the variables in the pattern. If you change them,
3403Once upon a time, Perl would recompile regular expressions
2741Perl won't even notice. See also L<"qr/STRING/msixpo">.
3404unnecessarily, and this modifier was useful to tell it not to do so, in the
3405interests of speed. But now, the only reasons to use C</o> are either:
27423406
27433407=end original
27443408
27453409PATTERN には、変数が含まれていてもよく、パターンが評価されるごとに、
27463410(デリミタがシングルクォートでない限り)変数は展開され
27473411(パターンが再コンパイルされ) ます。
27483412(変数 C<$(>, C<$)>, C<$|> は文字列の終わりを調べるパターンであると
27493413解釈されるので、展開されません。)
2750パターンコンパイルされるのを 1 度だけにたい場合には、
3414Perl は展開された変数の値が変更されない限りパターンを再コンパイルしません。
2751終わりの区切文字の後に C</o> 修飾子付けます
3415デリミタ引き続いて C</o> ("once" 意味します) を追加することで、
2752これにより、実行時に再コンパイルが頻繁起こることが避けられ、展開
3416テストを飛ばして再コンパイルしないようることができま
2753値がスクリプトの実行中変化場合に有効なもとなります。
3417昔々、Perl は不必要正規表現を再コンパイルで、速度に関心が
2754しかし、C</o> を付けこと、パターの中の変数を変更しないことを
3418場合再コパイルしないようにするためにの修飾子は有用でした。
2755約束するものです
3419しかし今では、C</o> を使う理由は以下どちらかだけです:
2756変更したとしても、Perl がそれに気付くことはありません。
2757L<"qr/STRING/msixpo"> も参照して下さい。
27583420
3421=over
3422
3423=item 1
3424
3425=begin original
3426
3427The variables are thousands of characters long and you know that they
3428don't change, and you need to wring out the last little bit of speed by
3429having Perl skip testing for that. (There is a maintenance penalty for
3430doing this, as mentioning C</o> constitutes a promise that you won't
3431change the variables in the pattern. If you change them, Perl won't
3432even notice.)
3433
3434=end original
3435
3436変数が数千文字の長さで、これが変更されないことが分かっており、これに対する
3437テストを飛ばすことであともう少しだけ速度を稼ぐ必要がある。
3438(こうすることには保守上のペナルティがあります; なぜなら C</o> と言及することで
3439パターン内の変数を変更しないことを約束したことになるからです。
3440変更しても、Perl は気づきもしません。)
3441
3442=item 2
3443
3444=begin original
3445
3446you want the pattern to use the initial values of the variables
3447regardless of whether they change or not. (But there are saner ways
3448of accomplishing this than using C</o>.)
3449
3450=end original
3451
3452変数が変更されようが変更されまいが、変数の初期値を使ったパターンがほしい。
3453(しかしこれを達成するための、C</o> を使うよりもまともな方法があります。)
3454
3455=back
3456
27593457=item The empty pattern //
27603458
27613459(空パターン //)
27623460
27633461=begin original
27643462
27653463If the PATTERN evaluates to the empty string, the last
27663464I<successfully> matched regular expression is used instead. In this
2767case, only the C<g> and C<c> flags on the empty pattern is honoured -
3465case, only the C<g> and C<c> flags on the empty pattern are honored;
27683466the other flags are taken from the original pattern. If no match has
27693467previously succeeded, this will (silently) act instead as a genuine
27703468empty pattern (which will always match).
27713469
27723470=end original
27733471
27743472PATTERN を評価した結果が空文字列となった場合には、最後にマッチに
27753473I<成功した> 正規表現が、代わりに使われます。
2776この場合、空パターンに対して C<g> の C<c> フラグだけが有効です -
3474この場合、空パターンに対して C<g> の C<c> フラグだけが有効です;
27773475その他のフラグは元のパターンから取られます。
27783476以前に成功したマッチングがない場合、これは(暗黙に)真の空パターンとして
27793477動作します(つまり常にマッチングします)。
27803478
27813479=begin original
27823480
27833481Note that it's possible to confuse Perl into thinking C<//> (the empty
27843482regex) is really C<//> (the defined-or operator). Perl is usually pretty
27853483good about this, but some pathological cases might trigger this, such as
27863484C<$a///> (is that C<($a) / (//)> or C<$a // />?) and C<print $fh //>
27873485(C<print $fh(//> or C<print($fh //>?). In all of these examples, Perl
27883486will assume you meant defined-or. If you meant the empty regex, just
27893487use parentheses or spaces to disambiguate, or even prefix the empty
27903488regex with an C<m> (so C<//> becomes C<m//>).
27913489
27923490=end original
27933491
27943492Perl が C<//> (空正規表現) と C<//> (定義性和演算子) を混同する
27953493可能性があることに注意してください。
27963494Perl は普通これをかなりうまく処理しますが、C<$a///> (C<($a) / (//)>
27973495それとも C<$a // />?) や C<print $fh //> (C<print $fh(//> それとも
27983496C<print($fh //>?) のような病的な状況ではこれが起こりえます。
27993497これらの例の全てでは、Perl は定義性和を意味していると仮定します。
28003498もし空正規表現を意味したいなら、あいまいさをなくすために単に
28013499かっこや空白を使うか、空正規表現に接頭辞 C<m> を付けてください
28023500(つまり C<//> を C<m//> にします)。
28033501
28043502=item Matching in list context
28053503
28063504(リストコンテキストでのマッチング)
28073505
28083506=begin original
28093507
28103508If the C</g> option is not used, C<m//> in list context returns a
28113509list consisting of the subexpressions matched by the parentheses in the
28123510pattern, i.e., (C<$1>, C<$2>, C<$3>...). (Note that here C<$1> etc. are
28133511also set, and that this differs from Perl 4's behavior.) When there are
28143512no parentheses in the pattern, the return value is the list C<(1)> for
28153513success. With or without parentheses, an empty list is returned upon
28163514failure.
28173515
28183516=end original
28193517
28203518C</g>オプションが使われなかった場合、リストコンテキストでのC<m//>は
28213519パターンの中の括弧で括られた部分列にマッチしたもので構成されるリストを
2822返します。
3520返します; これは、(C<$1>, C<$2>, C<$3>, ...) ということです
2823れは(C<$1>, C<$2>, C<$3>, ...) ということです。
3521(の場合、C<$1> なども設定されます; この点で Perl 4 の動作違ってす。)
2824(この場合、C<$1> なども設定されます。
2825この点で Perl 4 の動作と違っています。)
28263522パターンに括弧がない場合は、返り値は成功時はリスト C<(1)> です。
28273523括弧のあるなしに関わらず、失敗時は空リストを返します。
28283524
28293525=begin original
28303526
28313527Examples:
28323528
28333529=end original
28343530
28353531例:
28363532
2837 open(TTY, '/dev/tty');
3533 open(TTY, "+>/dev/tty")
3534 || die "can't access /dev/tty: $!";
3535
28383536 <TTY> =~ /^y/i && foo(); # do foo if desired
28393537
28403538 if (/Version: *([0-9.]*)/) { $version = $1; }
28413539
28423540 next if m#^/usr/spool/uucp#;
28433541
28443542 # poor man's grep
28453543 $arg = shift;
28463544 while (<>) {
2847 print if /$arg/o; # compile only once
3545 print if /$arg/o; # compile only once (no longer needed!)
28483546 }
28493547
28503548 if (($F1, $F2, $Etc) = ($foo =~ /^(\S+)\s+(\S+)\s*(.*)/))
28513549
28523550=begin original
28533551
28543552This last example splits $foo into the first two words and the
28553553remainder of the line, and assigns those three fields to $F1, $F2, and
2856$Etc. The conditional is true if any variables were assigned, i.e., if
3554$Etc. The conditional is true if any variables were assigned; that is,
2857the pattern matched.
3555if the pattern matched.
28583556
28593557=end original
28603558
28613559最後の例は、$foo を最初の 2 つの単語と行の残りに分解し、
28623560$F1 と $F2 と $Etc に代入しています。
28633561変数に代入されれば、すなわちパターンがマッチすれば、
28643562if の条件が真となります。
28653563
28663564=begin original
28673565
28683566The C</g> modifier specifies global pattern matching--that is,
2869matching as many times as possible within the string. How it behaves
3567matching as many times as possible within the string. How it behaves
2870depends on the context. In list context, it returns a list of the
3568depends on the context. In list context, it returns a list of the
28713569substrings matched by any capturing parentheses in the regular
2872expression. If there are no parentheses, it returns a list of all
3570expression. If there are no parentheses, it returns a list of all
28733571the matched strings, as if there were parentheses around the whole
28743572pattern.
28753573
28763574=end original
28773575
28783576C</g> 修飾子は、グローバルなパターンマッチを指定するもので、
28793577文字列の中で可能な限りたくさんマッチを行ないます。
28803578この動作は、コンテキストに依存します。
28813579リストコンテキストでは、正規表現内の括弧付けされたものにマッチした
28823580部分文字列のリストが返されます。
28833581括弧がなければ、パターン全体を括弧で括っていたかのように、
28843582すべてのマッチした文字列のリストが返されます。
28853583
28863584=begin original
28873585
28883586In scalar context, each execution of C<m//g> finds the next match,
28893587returning true if it matches, and false if there is no further match.
2890The position after the last match can be read or set using the pos()
3588The position after the last match can be read or set using the C<pos()>
2891function; see L<perlfunc/pos>. A failed match normally resets the
3589function; see L<perlfunc/pos>. A failed match normally resets the
28923590search position to the beginning of the string, but you can avoid that
2893by adding the C</c> modifier (e.g. C<m//gc>). Modifying the target
3591by adding the C</c> modifier (e.g. C<m//gc>). Modifying the target
28943592string also resets the search position.
28953593
28963594=end original
28973595
2898スカラコンテキストでは、C<m//g> を実行する毎に次のマッチを探します
3596スカラコンテキストでは、C<m//g> を実行する毎に次のマッチを探します;
28993597マッチした場合は真を返し、もうマッチしなくなったら偽を返します。
2900最後のマッチの位置は pos() 関数で読み出しや設定ができます
3598最後のマッチの位置は C<pos()> 関数で読み出しや設定ができます;
29013599L<perlfunc/pos> を参照して下さい。
29023600マッチに失敗すると通常は検索位置を文字列の先頭にリセットしますが、
29033601C</c> 修飾子をつける(つまり C<m//gc>)ことでこれを防ぐことができます。
29043602ターゲットとなる文字列が変更された場合も検索位置はリセットされます。
29053603
29063604=item \G assertion
29073605
29083606(\G アサート)
29093607
29103608=begin original
29113609
29123610You can intermix C<m//g> matches with C<m/\G.../g>, where C<\G> is a
2913zero-width assertion that matches the exact position where the previous
3611zero-width assertion that matches the exact position where the
2914C<m//g>, if any, left off. Without the C</g> modifier, the C<\G> assertion
3612previous C<m//g>, if any, left off. Without the C</g> modifier, the
2915still anchors at pos(), but the match is of course only attempted once.
3613C<\G> assertion still anchors at C<pos()> as it was at the start of
2916Using C<\G> without C</g> on a target string that has not previously had a
3614the operation (see L<perlfunc/pos>), but the match is of course only
2917C</g> match applied to it is the same as using the C<\A> assertion to match
3615attempted once. Using C<\G> without C</g> on a target string that has
2918the beginning of the string. Note also that, currently, C<\G> is only
3616not previously had a C</g> match applied to it is the same as using
2919properly supported when anchored at the very beginning of the pattern.
3617the C<\A> assertion to match the beginning of the string. Note also
3618that, currently, C<\G> is only properly supported when anchored at the
3619very beginning of the pattern.
29203620
29213621=end original
29223622
2923C<m//g> マッチを C<m/\G.../g> と混ぜることもできます
3623C<m//g> マッチを C<m/\G.../g> と混ぜることもできます; C<\G> は前回の
2924C<\G> は前回の C<m//g> があればその同じ位置でマッチする
3624C<m//g> があればその同じ位置でマッチする
29253625ゼロ文字幅のアサートです。
2926C</g> 修飾子なしの場合、C<\G> アサートは pos() に固定しますが、
3626C</g> 修飾子なしの場合、C<\G> アサートは操作の最初としてC<pos()>
2927マッチはもちろん一度だけ試されます。
3627固定しますが、(L<perlfunc/pos> 参照) マッチはもちろん一度だけ試されます。
29283628以前に C</g> マッチを適用していないターゲット文字列に対して C</g> なしで
29293629C<\G> を使うと、文字列の先頭にマッチする C<\A> アサートを使うのと
29303630同じことになります。
29313631C<\G> は現在のところ、パターンのまさに先頭を示す場合にのみ正しく
29323632対応することにも注意してください。
29333633
29343634=begin original
29353635
29363636Examples:
29373637
29383638=end original
29393639
29403640例:
29413641
29423642 # list context
29433643 ($one,$five,$fifteen) = (`uptime` =~ /(\d+\.\d+)/g);
29443644
29453645 # scalar context
2946 $/ = "";
3646 local $/ = "";
2947 while (defined($paragraph = <>)) {
3647 while ($paragraph = <>) {
2948 while ($paragraph =~ /[a-z]['")]*[.!?]+['")]*\s/g) {
3648 while ($paragraph =~ /\p{Ll}['")]*[.!?]+['")]*\s/g) {
29493649 $sentences++;
29503650 }
29513651 }
2952 print "$sentences\n";
3652 say $sentences;
29533653
2954 # using m//gc with \G
3654=begin original
3655
3656Here's another way to check for sentences in a paragraph:
3657
3658=end original
3659
3660以下は段落内の文をチェックするためのもう一つの方法です:
3661
3662 my $sentence_rx = qr{
3663 (?: (?<= ^ ) | (?<= \s ) ) # after start-of-string or whitespace
3664 \p{Lu} # capital letter
3665 .*? # a bunch of anything
3666 (?<= \S ) # that ends in non-whitespace
3667 (?<! \b [DMS]r ) # but isn't a common abbreviation
3668 (?<! \b Mrs )
3669 (?<! \b Sra )
3670 (?<! \b St )
3671 [.?!] # followed by a sentence ender
3672 (?= $ | \s ) # in front of end-of-string or whitespace
3673 }sx;
3674 local $/ = "";
3675 while (my $paragraph = <>) {
3676 say "NEW PARAGRAPH";
3677 my $count = 0;
3678 while ($paragraph =~ /($sentence_rx)/g) {
3679 printf "\tgot sentence %d: <%s>\n", ++$count, $1;
3680 }
3681 }
3682
3683=begin original
3684
3685Here's how to use C<m//gc> with C<\G>:
3686
3687=end original
3688
3689以下は C<m//gc> を C<\G> で使う方法です:
3690
29553691 $_ = "ppooqppqq";
29563692 while ($i++ < 2) {
29573693 print "1: '";
29583694 print $1 while /(o)/gc; print "', pos=", pos, "\n";
29593695 print "2: '";
29603696 print $1 if /\G(q)/gc; print "', pos=", pos, "\n";
29613697 print "3: '";
29623698 print $1 while /(p)/gc; print "', pos=", pos, "\n";
29633699 }
29643700 print "Final: '$1', pos=",pos,"\n" if /\G(.)/;
29653701
29663702=begin original
29673703
29683704The last example should print:
29693705
29703706=end original
29713707
29723708最後のものは以下のものを表示するはずです:
29733709
29743710 1: 'oo', pos=4
29753711 2: 'q', pos=5
29763712 3: 'pp', pos=7
29773713 1: '', pos=7
29783714 2: 'q', pos=8
29793715 3: '', pos=8
29803716 Final: 'q', pos=8
29813717
29823718=begin original
29833719
29843720Notice that the final match matched C<q> instead of C<p>, which a match
29853721without the C<\G> anchor would have done. Also note that the final match
2986did not update C<pos> -- C<pos> is only updated on a C</g> match. If the
3722did not update C<pos>. C<pos> is only updated on a C</g> match. If the
2987final match did indeed match C<p>, it's a good bet that you're running an
3723final match did indeed match C<p>, it's a good bet that you're running a
2988older (pre-5.6.0) Perl.
3724very old (pre-5.6.0) version of Perl.
29893725
29903726=end original
29913727
29923728C<\G> なしでのマッチが行われたため、最後のマッチでは C<p> ではなく
29933729C<q> がマッチすることに注意してください。
29943730また、最後のマッチは C<pos> を更新しないことに注意してください。
29953731C<pos> は C</g> マッチでのみ更新されます。
29963732もし最後のマッチで C<p> にマッチした場合、かなりの確率で
2997古い (5.6.0 以前の) Perl で実行しているはずです。
3733とても古い (5.6.0 以前の) Perl で実行しているはずです。
29983734
29993735=begin original
30003736
30013737A useful idiom for C<lex>-like scanners is C</\G.../gc>. You can
30023738combine several regexps like this to process a string part-by-part,
30033739doing different actions depending on which regexp matched. Each
30043740regexp tries to match where the previous one leaves off.
30053741
30063742=end original
30073743
30083744C<lex> 風にスキャンするために便利な指定は C</\G.../gc> です。
30093745文字列を部分ごとに処理するためにいくつかの正規表現をつなげて、どの
30103746正規表現にマッチしたかによって異なる処理をすることができます。
30113747それぞれの正規表現は前の正規表現が飛ばした部分に対して
30123748マッチを試みます。
30133749
30143750 $_ = <<'EOL';
3015 $url = URI::URL->new( "http://www/" ); die if $url eq "xXx";
3751 $url = URI::URL->new( "http://example.com/" ); die if $url eq "xXx";
30163752 EOL
3017 LOOP:
3018 {
3019 print(" digits"), redo LOOP if /\G\d+\b[,.;]?\s*/gc;
3020 print(" lowercase"), redo LOOP if /\G[a-z]+\b[,.;]?\s*/gc;
3021 print(" UPPERCASE"), redo LOOP if /\G[A-Z]+\b[,.;]?\s*/gc;
3022 print(" Capitalized"), redo LOOP if /\G[A-Z][a-z]+\b[,.;]?\s*/gc;
3023 print(" MiXeD"), redo LOOP if /\G[A-Za-z]+\b[,.;]?\s*/gc;
3024 print(" alphanumeric"), redo LOOP if /\G[A-Za-z0-9]+\b[,.;]?\s*/gc;
3025 print(" line-noise"), redo LOOP if /\G[^A-Za-z0-9]+/gc;
3026 print ". That's all!\n";
3027 }
30283753
3754 LOOP: {
3755 print(" digits"), redo LOOP if /\G\d+\b[,.;]?\s*/gc;
3756 print(" lowercase"), redo LOOP if /\G\p{Ll}+\b[,.;]?\s*/gc;
3757 print(" UPPERCASE"), redo LOOP if /\G\p{Lu}+\b[,.;]?\s*/gc;
3758 print(" Capitalized"), redo LOOP if /\G\p{Lu}\p{Ll}+\b[,.;]?\s*/gc;
3759 print(" MiXeD"), redo LOOP if /\G\pL+\b[,.;]?\s*/gc;
3760 print(" alphanumeric"), redo LOOP if /\G[\p{Alpha}\pN]+\b[,.;]?\s*/gc;
3761 print(" line-noise"), redo LOOP if /\G\W+/gc;
3762 print ". That's all!\n";
3763 }
3764
30293765=begin original
30303766
30313767Here is the output (split into several lines):
30323768
30333769=end original
30343770
30353771出力は以下のようになります(何行かに分割しています):
30363772
3037 line-noise lowercase line-noise lowercase UPPERCASE line-noise
3773 line-noise lowercase line-noise UPPERCASE line-noise UPPERCASE
3038 UPPERCASE line-noise lowercase line-noise lowercase line-noise
3774 line-noise lowercase line-noise lowercase line-noise lowercase
3039 lowercase lowercase line-noise lowercase lowercase line-noise
3775 lowercase line-noise lowercase lowercase line-noise lowercase
3040 MiXeD line-noise. That's all!
3776 lowercase line-noise MiXeD line-noise. That's all!
30413777
3042=item ?PATTERN?
3778=item m?PATTERN?msixpodualgc
3043X<?>
3779X<?> X<operator, match-once>
30443780
3781=item ?PATTERN?msixpodualgc
3782
30453783=begin original
30463784
3047This is just like the C</pattern/> search, except that it matches only
3785This is just like the C<m/PATTERN/> search, except that it matches
3048once between calls to the reset() operator. This is a useful
3786only once between calls to the reset() operator. This is a useful
30493787optimization when you want to see only the first occurrence of
3050something in each file of a set of files, for instance. Only C<??>
3788something in each file of a set of files, for instance. Only C<m??>
30513789patterns local to the current package are reset.
30523790
30533791=end original
30543792
30553793これは、reset() 演算子を呼び出すごとに 1 度だけしか
3056マッチしないことを除いては C</pattern/> による検索と全く同じです。
3794マッチしないことを除いては C<m/pattern/> による検索と全く同じです。
30573795たとえば、ファイルの集まりの中で個々のファイルについて、あるものを
30583796探すとき、最初の 1 つだけの存在がわかれば良いのであれば、この機能を
30593797使って最適化をはかることができます。
3060現在のパッケージにローカルとなっている C<??> のパターンだけが
3798現在のパッケージにローカルとなっている C<m??> のパターンだけが
30613799リセットされます。
30623800
30633801 while (<>) {
3064 if (?^$?) {
3802 if (m?^$?) {
30653803 # blank line between header and body
30663804 }
30673805 } continue {
3068 reset if eof; # clear ?? status for next file
3806 reset if eof; # clear m?? status for next file
30693807 }
30703808
30713809=begin original
30723810
3073This usage is vaguely deprecated, which means it just might possibly
3811Another example switched the first "latin1" encoding it finds
3074be removed in some distant future version of Perl, perhaps somewhere
3812to "utf8" in a pod file:
3075around the year 2168.
30763813
30773814=end original
30783815
3079方法は、あまりお勧めしません。
3816は、pod ファイル中の最初の "latin1" エンコーディングを "utf8" に
3080Perl の遠い将来のバージョン(おそらく 2168 年頃)では削除されるかもしれせん。
3817切り替えす:
30813818
3082=item s/PATTERN/REPLACEMENT/msixpogce
3819 s//utf8/ if m? ^ =encoding \h+ \K latin1 ?x;
3820
3821=begin original
3822
3823The match-once behavior is controlled by the match delimiter being
3824C<?>; with any other delimiter this is the normal C<m//> operator.
3825
3826=end original
3827
3828一度だけマッチングという振る舞いはマッチングデリミタが C<?> かどうかで
3829制御されます: その他のデリミタの場合はこれは通常の C<m//> 演算子です。
3830
3831=begin original
3832
3833For historical reasons, the leading C<m> in C<m?PATTERN?> is optional,
3834but the resulting C<?PATTERN?> syntax is deprecated, will warn on
3835usage and might be removed from a future stable release of Perl (without
3836further notice!).
3837
3838=end original
3839
3840歴史的な理由により、C<m?PATTERN?> の先頭の C<m> は省略可能ですが、
3841その結果となる C<?PATTERN?> という文法は非推奨であり、使用すると警告が
3842出ます; また将来の Perl の安定版リリースでは (さらなる注意なしに!)
3843削除されるかもしれません。
3844
3845=item s/PATTERN/REPLACEMENT/msixpodualgcer
30833846X<substitute> X<substitution> X<replace> X<regexp, replace>
3084X<regexp, substitute> X</m> X</s> X</i> X</x> X</p> X</o> X</g> X</c> X</e>
3847X<regexp, substitute> X</m> X</s> X</i> X</x> X</p> X</o> X</g> X</c> X</e> X</r>
30853848
30863849=begin original
30873850
30883851Searches a string for a pattern, and if found, replaces that pattern
30893852with the replacement text and returns the number of substitutions
30903853made. Otherwise it returns false (specifically, the empty string).
30913854
30923855=end original
30933856
30943857文字列中でパターンを検索し、もし見つかれば、置換テキストで置き換え、
30953858置換した数を返します。
30963859見つからなければ、偽 (具体的には、空文字列) を返します。
30973860
30983861=begin original
30993862
3863If the C</r> (non-destructive) option is used then it runs the
3864substitution on a copy of the string and instead of returning the
3865number of substitutions, it returns the copy whether or not a
3866substitution occurred. The original string is never changed when
3867C</r> is used. The copy will always be a plain string, even if the
3868input is an object or a tied variable.
3869
3870=end original
3871
3872C</r> (非破壊) オプションが使われると、文字列のコピーに対して置換が行われ、
3873置換された数ではなく、置換が行われたかどうかにかかわらずこのコピーが返されます。
3874C</r> が使われた場合、元の文字列は決して変更されません。
3875コピーは、たとえ入力がオブジェクトや tie された変数でも、常に
3876プレーンな文字列です。
3877
3878=begin original
3879
31003880If no string is specified via the C<=~> or C<!~> operator, the C<$_>
3101variable is searched and modified. (The string specified with C<=~> must
3881variable is searched and modified. Unless the C</r> option is used,
3102be scalar variable, an array element, a hash element, or an assignment
3882the string specified must be a scalar variable, an array element, a
3103to one of those, i.e., an lvalue.)
3883hash element, or an assignment to one of those; that is, some sort of
3884scalar lvalue.
31043885
31053886=end original
31063887
31073888C<=~> 演算子や C<!~> 演算子によって文字列が指定されていなければ、
31083889変数 C<$_> が検索され、修正されます。
3109(C<=~> 指定される文字列は、スカラ変数、配列要素、ハッシュ要素
3890C</r> 指定されていない限り
3110は、これらへの代入式といった左辺値でなければなりません。)
3891C<=~> で指定され文字列は、スカラ変数、配列要素、ハッシュ要素、
3892あるいは、これらへの代入式といったある種の
3893スカラ左辺値でなければなりません。
31113894
31123895=begin original
31133896
31143897If the delimiter chosen is a single quote, no interpolation is
31153898done on either the PATTERN or the REPLACEMENT. Otherwise, if the
31163899PATTERN contains a $ that looks like a variable rather than an
31173900end-of-string test, the variable will be interpolated into the pattern
31183901at run-time. If you want the pattern compiled only once the first time
31193902the variable is interpolated, use the C</o> option. If the pattern
31203903evaluates to the empty string, the last successfully executed regular
31213904expression is used instead. See L<perlre> for further explanation on these.
3122See L<perllocale> for discussion of additional considerations that apply
3123when C<use locale> is in effect.
31243905
31253906=end original
31263907
3127あとで述べますが、区切り文字はスラッシュとは限りません。
31283908シングルクォートを区切り文字として使った場合には、
31293909PATTERN にも REPLACEMENT にも変数の展開を行ないません。
31303910それ以外の場合、文字列の最後を表わすものには見えない $ が
31313911PATTERN に含まれると、実行時に変数がパターン内に展開されます。
31323912最初に変数が展開されるときにだけパターンのコンパイルを行ないたいときには、
31333913C</o> オプションを使ってください。
31343914パターンの評価結果が空文字列になった場合には、最後に成功した正規表現が
31353915代わりに使われます。
31363916これについてさらに詳しくは、L<perlre> を参照してください。
3137C<use locale> が有効の場合の議論については L<perllocale> を参照して下さい。
31383917
31393918=begin original
31403919
31413920Options are as with m// with the addition of the following replacement
31423921specific options:
31433922
31443923=end original
31453924
31463925オプションは、m// のものに加えて、以下の置換固有のものがあります:
31473926
31483927=begin original
31493928
31503929 e Evaluate the right side as an expression.
3151 ee Evaluate the right side as a string then eval the result
3930 ee Evaluate the right side as a string then eval the result.
3931 r Return substitution and leave the original string untouched.
31523932
31533933=end original
31543934
3155 e 式の右側の評価を行なう
3935 e 式の右側の評価を行なう
3156 ee 右側を文字列として評価して、その結果を評価する
3936 ee 右側を文字列として評価して、その結果を評価する
3937 r 置換した結果を返し、もとの文字列はそのままにする。
31573938
31583939=begin original
31593940
3160Any non-alphanumeric, non-whitespace delimiter may replace the
3941Any non-whitespace delimiter may replace the slashes. Add space after
3161slashes. If single quotes are used, no interpretation is done on the
3942the C<s> when using a character allowed in identifiers. If single quotes
3162replacement string (the C</e> modifier overrides this, however). Unlike
3943are used, no interpretation is done on the replacement string (the C</e>
3163Perl 4, Perl 5 treats backticks as normal delimiters; the replacement
3944modifier overrides this, however). Unlike Perl 4, Perl 5 treats backticks
3164text is not evaluated as a command. If the
3945as normal delimiters; the replacement text is not evaluated as a command.
3165PATTERN is delimited by bracketing quotes, the REPLACEMENT has its own
3946If the PATTERN is delimited by bracketing quotes, the REPLACEMENT has
3166pair of quotes, which may or may not be bracketing quotes, e.g.,
3947its own pair of quotes, which may or may not be bracketing quotes, e.g.,
31673948C<s(foo)(bar)> or C<< s<foo>/bar/ >>. A C</e> will cause the
31683949replacement portion to be treated as a full-fledged Perl expression
31693950and evaluated right then and there. It is, however, syntax checked at
31703951compile-time. A second C<e> modifier will cause the replacement portion
31713952to be C<eval>ed before being run as a Perl expression.
31723953
31733954=end original
31743955
3175英数字、空白ではない任意の区切り文字で、スラッシュを置き換えられます。
3956空白ではない任意の区切り文字で、スラッシュを置き換えられます。
3957識別子として許されている文字を使うときには C<s> の後に空白を
3958追加してください。
31763959先に述べたように、シングルクォートを使うと置換文字列での展開は
31773960されません (C</e>修飾子を使えば可能です)。
3178Perl 4 と違って、 Perl 5 はバッククォートを通常のデリミタとして扱います
3961Perl 4 と違って、 Perl 5 はバッククォートを通常のデリミタとして扱います;
31793962置換テキストはコマンドとして評価されません。
31803963PATTERN を括弧類で括った場合には、REPLACEMENT 用にもう一組の区切り文字を
3181用意します
3964用意します; これは、括弧類であっても、なくてもかまいません;
3182これは、括弧類であっても、なくてもかまいません; C<s(foo)(bar)> や
3965C<s(foo)(bar)> や C<< s<foo>/bar/ >>。
3183C<< s<foo>/bar/ >>。
31843966C</e> は置換文字列を完全な Perl の式として扱い、その場所で直ちに解釈します。
31853967しかし、これはコンパイル時に構文チェックされます。
31863968二番目の C<e> 修飾子を指定すると、置換部分がまず Perl の式として
31873969C<eval> されます。
31883970
31893971=begin original
31903972
31913973Examples:
31923974
31933975=end original
31943976
31953977例:
31963978
31973979 s/\bgreen\b/mauve/g; # don't change wintergreen
31983980
31993981 $path =~ s|/usr/bin|/usr/local/bin|;
32003982
32013983 s/Login: $foo/Login: $bar/; # run-time pattern
32023984
32033985 ($foo = $bar) =~ s/this/that/; # copy first, then change
3986 ($foo = "$bar") =~ s/this/that/; # convert to string, copy, then change
3987 $foo = $bar =~ s/this/that/r; # Same as above using /r
3988 $foo = $bar =~ s/this/that/r
3989 =~ s/that/the other/r; # Chained substitutes using /r
3990 @foo = map { s/this/that/r } @bar # /r is very useful in maps
32043991
32053992 $count = ($paragraph =~ s/Mister\b/Mr./g); # get change-count
32063993
32073994 $_ = 'abc123xyz';
32083995 s/\d+/$&*2/e; # yields 'abc246xyz'
32093996 s/\d+/sprintf("%5d",$&)/e; # yields 'abc 246xyz'
32103997 s/\w/$& x 2/eg; # yields 'aabbcc 224466xxyyzz'
32113998
32123999 s/%(.)/$percent{$1}/g; # change percent escapes; no /e
32134000 s/%(.)/$percent{$1} || $&/ge; # expr now, so /e
32144001 s/^=(\w+)/pod($1)/ge; # use function call
32154002
4003 $_ = 'abc123xyz';
4004 $a = s/abc/def/r; # $a is 'def123xyz' and
4005 # $_ remains 'abc123xyz'.
4006
32164007 # expand variables in $_, but dynamics only, using
32174008 # symbolic dereferencing
32184009 s/\$(\w+)/${$1}/g;
32194010
32204011 # Add one to the value of any numbers in the string
32214012 s/(\d+)/1 + $1/eg;
32224013
4014 # Titlecase words in the last 30 characters only
4015 substr($str, -30) =~ s/\b(\p{Alpha}+)\b/\u\L$1/g;
4016
32234017 # This will expand any embedded scalar variable
32244018 # (including lexicals) in $_ : First $1 is interpolated
32254019 # to the variable name, and then evaluated
32264020 s/(\$\w+)/$1/eeg;
32274021
32284022 # Delete (most) C comments.
32294023 $program =~ s {
32304024 /\* # Match the opening delimiter.
32314025 .*? # Match a minimal number of characters.
32324026 \*/ # Match the closing delimiter.
32334027 } []gsx;
32344028
32354029 s/^\s*(.*?)\s*$/$1/; # trim whitespace in $_, expensively
32364030
32374031 for ($variable) { # trim whitespace in $variable, cheap
32384032 s/^\s+//;
32394033 s/\s+$//;
32404034 }
32414035
32424036 s/([^ ]*) *([^ ]*)/$2 $1/; # reverse 1st two fields
32434037
32444038=begin original
32454039
32464040Note the use of $ instead of \ in the last example. Unlike
32474041B<sed>, we use the \<I<digit>> form in only the left hand side.
32484042Anywhere else it's $<I<digit>>.
32494043
32504044=end original
32514045
32524046最後の例で \ の代わりに $ を使っているのに注意してください。
32534047B<sed> と違って、\<I<数字>> の形式はパターンの方でのみ使用できます。
32544048その他の場所では、$<I<数字>> を使います。
32554049
32564050=begin original
32574051
32584052Occasionally, you can't use just a C</g> to get all the changes
32594053to occur that you might want. Here are two common cases:
32604054
32614055=end original
32624056
32634057ときには、C</g> を付けるだけでは、あなたが望んでいるような形で
32644058すべてを変更することができないことがあります。
32654059良くある例を 2 つ示します:
32664060
32674061 # put commas in the right places in an integer
32684062 1 while s/(\d)(\d\d\d)(?!\d)/$1,$2/g;
32694063
32704064 # expand tabs to 8-column spacing
32714065 1 while s/\t+/' ' x (length($&)*8 - length($`)%8)/e;
32724066
4067=begin original
4068
4069C<s///le> is treated as a substitution followed by the C<le> operator, not
4070the C</le> flags. This may change in a future version of Perl. It
4071produces a warning if warnings are enabled. To disambiguate, use a space
4072or change the order of the flags:
4073
4074=end original
4075
4076C<s///le> は C</le> フラグではなく、置換に引き続く C<le> 演算子として扱われます。
4077これは将来のバージョンの Perl では変更されるかもしれません。
4078警告が有効の場合は警告が出力されます。
4079曖昧さをなくすために、空白を使うかフラグの順番を変えてください:
4080
4081 s/foo/bar/ le 5; # "le" infix operator
4082 s/foo/bar/el; # "e" and "l" flags
4083
32734084=back
32744085
32754086=head2 Quote-Like Operators
32764087X<operator, quote-like>
32774088
32784089(クォート風演算子)
32794090
32804091=over 4
32814092
32824093=item q/STRING/
32834094X<q> X<quote, single> X<'> X<''>
32844095
32854096=item 'STRING'
32864097
32874098=begin original
32884099
32894100A single-quoted, literal string. A backslash represents a backslash
32904101unless followed by the delimiter or another backslash, in which case
32914102the delimiter or backslash is interpolated.
32924103
32934104=end original
32944105
32954106シングルクォートされた、リテラル文字列です。
32964107バックスラッシュは、後ろに続くものが区切文字か、別のバックスラッシュで
3297ある場合を除いて単なるバックスラッシュです
4108ある場合を除いて単なるバックスラッシュです;
32984109区切文字やバックスラッシュが続く場合には、その区切文字自身もしくは
32994110バックスラッシュそのものが展開されます。
33004111
33014112 $foo = q!I said, "You said, 'She said it.'"!;
33024113 $bar = q('This is it.');
33034114 $baz = '\n'; # a two-character string
33044115
33054116=item qq/STRING/
33064117X<qq> X<quote, double> X<"> X<"">
33074118
33084119=item "STRING"
33094120
33104121=begin original
33114122
33124123A double-quoted, interpolated string.
33134124
33144125=end original
33154126
33164127ダブルクォートされた、リテラル文字列です。
33174128
33184129 $_ .= qq
33194130 (*** The previous line contains the naughty word "$1".\n)
33204131 if /\b(tcl|java|python)\b/i; # :-)
33214132 $baz = "\n"; # a one-character string
33224133
33234134=item qx/STRING/
33244135X<qx> X<`> X<``> X<backtick>
33254136
33264137=item `STRING`
33274138
33284139=begin original
33294140
33304141A string which is (possibly) interpolated and then executed as a
33314142system command with C</bin/sh> or its equivalent. Shell wildcards,
33324143pipes, and redirections will be honored. The collected standard
33334144output of the command is returned; standard error is unaffected. In
33344145scalar context, it comes back as a single (potentially multi-line)
33354146string, or undef if the command failed. In list context, returns a
33364147list of lines (however you've defined lines with $/ or
33374148$INPUT_RECORD_SEPARATOR), or an empty list if the command failed.
33384149
33394150=end original
33404151
33414152展開され、C</bin/sh> またはそれと等価なものでシステムのコマンドとして
33424153実行される(であろう)文字列です。
33434154シェルのワイルドカード、パイプ、リダイレクトが有効です。
3344そのコマンドの、標準出力を集めたものが返されます
4155そのコマンドの、標準出力を集めたものが返されます; 標準エラーは影響を
3345標準エラーは影響を与えません。
4156与えません。
33464157スカラコンテキストでは、(複数行を含むかもしれない)
33471 つの文字列が戻ってきます。
41581 つの文字列が戻ってきます; コマンドが失敗したときは未定義値を返します
3348コマンドが失敗したときは未定義値を返します。
33494159リストコンテキストでは、($/ もしくは $INPUT_RECORD_SEPARATOR を
3350どのように設定していても) 行のリストを返します
4160どのように設定していても) 行のリストを返します; コマンドが失敗したときは
3351コマンドが失敗したときは空リストを返します。
4161空リストを返します。
33524162
33534163=begin original
33544164
33554165Because backticks do not affect standard error, use shell file descriptor
33564166syntax (assuming the shell supports this) if you care to address this.
33574167To capture a command's STDERR and STDOUT together:
33584168
33594169=end original
33604170
33614171バッククォートは標準エラーには影響を与えないので、標準エラーを
33624172使いたい場合は(シェルが対応しているものとして)シェルのファイル記述子の
33634173文法を使ってください。
33644174コマンドの STDERR と STDOUT を共に取得したい場合は:
33654175
33664176 $output = `cmd 2>&1`;
33674177
33684178=begin original
33694179
33704180To capture a command's STDOUT but discard its STDERR:
33714181
33724182=end original
33734183
33744184コマンドの STDOUT は取得するが STDERR は捨てる場合は:
33754185
33764186 $output = `cmd 2>/dev/null`;
33774187
33784188=begin original
33794189
33804190To capture a command's STDERR but discard its STDOUT (ordering is
33814191important here):
33824192
33834193=end original
33844194
33854195コマンドの STDERR は取得するが STDOUT は捨てる場合は
33864196(ここでは順序が重要です):
33874197
33884198 $output = `cmd 2>&1 1>/dev/null`;
33894199
33904200=begin original
33914201
33924202To exchange a command's STDOUT and STDERR in order to capture the STDERR
33934203but leave its STDOUT to come out the old STDERR:
33944204
33954205=end original
33964206
33974207STDERR を取得するが、STDOUT は古い STDERR のために残しておくために
33984208STDOUT と STDERR を交換するには:
33994209
34004210 $output = `cmd 3>&1 1>&2 2>&3 3>&-`;
34014211
34024212=begin original
34034213
34044214To read both a command's STDOUT and its STDERR separately, it's easiest
34054215to redirect them separately to files, and then read from those files
34064216when the program is done:
34074217
34084218=end original
34094219
34104220コマンドの STDOUT と STDERR の両方を別々に読み込みたい場合、
34114221一番簡単な方法は別々のファイルにリダイレクトし、
34124222プログラムが終了してからそのファイルを読むことです:
34134223
34144224 system("program args 1>program.stdout 2>program.stderr");
34154225
34164226=begin original
34174227
34184228The STDIN filehandle used by the command is inherited from Perl's STDIN.
34194229For example:
34204230
34214231=end original
34224232
34234233コマンドによって使われる STDIN ファイルハンドルは Perl の STDIN を
34244234継承します。
34254235例えば:
34264236
3427 open BLAM, "blam" || die "Can't open: $!";
4237 open(SPLAT, "stuff") || die "can't open stuff: $!";
3428 open STDIN, "<&BLAM";
4238 open(STDIN, "<&SPLAT") || die "can't dupe SPLAT: $!";
3429 print `sort`;
4239 print STDOUT `sort`;
34304240
34314241=begin original
34324242
3433will print the sorted contents of the file "blam".
4243will print the sorted contents of the file named F<"stuff">.
34344244
34354245=end original
34364246
3437ファイル "blam" の内容をソートして表示します。
4247F<"stuff"> という名前のファイルの内容をソートして表示します。
34384248
34394249=begin original
34404250
34414251Using single-quote as a delimiter protects the command from Perl's
34424252double-quote interpolation, passing it on to the shell instead:
34434253
34444254=end original
34454255
34464256シングルクォートをデリミタとして使うと Perl のダブルクォート展開から
34474257保護され、そのままシェルに渡されます:
34484258
34494259 $perl_info = qx(ps $$); # that's Perl's $$
34504260 $shell_info = qx'ps $$'; # that's the new shell's $$
34514261
34524262=begin original
34534263
34544264How that string gets evaluated is entirely subject to the command
34554265interpreter on your system. On most platforms, you will have to protect
34564266shell metacharacters if you want them treated literally. This is in
34574267practice difficult to do, as it's unclear how to escape which characters.
34584268See L<perlsec> for a clean and safe example of a manual fork() and exec()
34594269to emulate backticks safely.
34604270
34614271=end original
34624272
34634273この文字列がどのように評価されるかは完全にシステムのコマンドインタプリタに
34644274依存します。
34654275ほとんどのプラットフォームでは、シェルのメタ文字をリテラルに
34664276扱ってほしい場合はそれを守る必要があります。
34674277文字をエスケープする方法が明確ではないので、これは理論的には難しいことです。
34684278逆クォートを安全にエミュレートするために手動で fork() と exec() を
34694279行うためのきれいで安全な例については L<perlsec> を参照してください。
34704280
34714281=begin original
34724282
34734283On some platforms (notably DOS-like ones), the shell may not be
34744284capable of dealing with multiline commands, so putting newlines in
34754285the string may not get you what you want. You may be able to evaluate
34764286multiple commands in a single line by separating them with the command
34774287separator character, if your shell supports that (e.g. C<;> on many Unix
34784288shells; C<&> on the Windows NT C<cmd> shell).
34794289
34804290=end original
34814291
34824292(特に DOS 風の)プラットフォームには、シェルが複数行のコマンドを扱うことが
34834293できないものがあるので、文字列に改行を入れるとあなたの望まない結果に
34844294なる場合があります。
34854295シェルが対応していれば、コマンド分割文字で分割することで
348642961 行に複数のコマンドを入れて解釈させることができます
34874297(この文字は、多くの Unix シェルでは C<;>、Windows NT C<cmd> シェルでは
34884298C<&> です)。
34894299
34904300=begin original
34914301
34924302Beginning with v5.6.0, Perl will attempt to flush all files opened for
34934303output before starting the child process, but this may not be supported
34944304on some platforms (see L<perlport>). To be safe, you may need to set
34954305C<$|> ($AUTOFLUSH in English) or call the C<autoflush()> method of
34964306C<IO::Handle> on any open handles.
34974307
34984308=end original
34994309
35004310v5.6.0 以降、Perl は子プロセスの実行前に書き込み用に開いている全ての
35014311ファイルをフラッシュしようとしますが、これに対応していない
35024312プラットフォームもあります(L<perlport> を参照してください)。
35034313安全のためには、C<$|> (English モジュールでは $AUTOFLUSH)をセットするか、
35044314開いている全てのハンドルに対して C<IO::Handle> の C<autoflush()> メソッドを
35054315呼び出す必要があります。
35064316
35074317=begin original
35084318
35094319Beware that some command shells may place restrictions on the length
35104320of the command line. You must ensure your strings don't exceed this
35114321limit after any necessary interpolations. See the platform-specific
35124322release notes for more details about your particular environment.
35134323
35144324=end original
35154325
35164326コマンド行の長さに制限があるコマンドシェルがあることに注意してください。
35174327全ての必要な変換が行われた後、コマンド文字列がこの制限を越えないことを
35184328保障する必要があります。
35194329特定の環境に関するさらなる詳細についてはプラットフォーム固有の
35204330リリースノートを参照してください。
35214331
35224332=begin original
35234333
35244334Using this operator can lead to programs that are difficult to port,
35254335because the shell commands called vary between systems, and may in
35264336fact not be present at all. As one example, the C<type> command under
35274337the POSIX shell is very different from the C<type> command under DOS.
35284338That doesn't mean you should go out of your way to avoid backticks
35294339when they're the right way to get something done. Perl was made to be
35304340a glue language, and one of the things it glues together is commands.
35314341Just understand what you're getting yourself into.
35324342
35334343=end original
35344344
3535この演算子を使うと、プログラムの移殖が困難になります
4345この演算子を使うと、プログラムの移殖が困難になります; 呼び出されるシェル
3536呼び出されるシェルコマンドはシステムによって異なり、実際全く
4346コマンドはシステムによって異なり、実際全く存在しないこともあるからです。
3537存在しないこともあるからです。
35384347一つの例としては、POSIX シェルの C<type> コマンドは DOS の C<type> コマンドと
35394348大きく異なっています。
35404349これは、何かを為すために正しい方法として逆クォートを使うことを
35414350避けるべきであることを意味しません。
35424351Perl は接着剤のような言語として作られ、接着されるべきものの一つは
35434352コマンドです。
35444353単にあなたが何をしようとしているかを理解しておいてください。
35454354
35464355=begin original
35474356
35484357See L</"I/O Operators"> for more discussion.
35494358
35504359=end original
35514360
35524361さらなる議論については L</"I/O Operators"> を参照して下さい。
35534362
35544363=item qw/STRING/
35554364X<qw> X<quote, list> X<quote, words>
35564365
35574366=begin original
35584367
35594368Evaluates to a list of the words extracted out of STRING, using embedded
35604369whitespace as the word delimiters. It can be understood as being roughly
35614370equivalent to:
35624371
35634372=end original
35644373
35654374埋め込まれた空白を区切文字として、STRING から抜き出した単語のリストを
35664375評価します。
35674376これは、以下の式と大体同じと考えられます:
35684377
3569 split(' ', q/STRING/);
4378 split(" ", q/STRING/);
35704379
35714380=begin original
35724381
35734382the differences being that it generates a real list at compile time, and
35744383in scalar context it returns the last element in the list. So
35754384this expression:
35764385
35774386=end original
35784387
35794388違いは、実際のリストをコンパイル時に生成し、スカラコンテキストではリストの
35804389最後の要素を返すことです。
35814390従って、以下の表現は:
35824391
35834392 qw(foo bar baz)
35844393
35854394=begin original
35864395
35874396is semantically equivalent to the list:
35884397
35894398=end original
35904399
35914400以下のリストと文法的に等価です。
35924401
3593 'foo', 'bar', 'baz'
4402 "foo", "bar", "baz"
35944403
35954404=begin original
35964405
35974406Some frequently seen examples:
35984407
35994408=end original
36004409
36014410よく行なわれる例としては以下のものです:
36024411
36034412 use POSIX qw( setlocale localeconv )
36044413 @EXPORT = qw( foo bar baz );
36054414
36064415=begin original
36074416
36084417A common mistake is to try to separate the words with comma or to
36094418put comments into a multi-line C<qw>-string. For this reason, the
36104419C<use warnings> pragma and the B<-w> switch (that is, the C<$^W> variable)
36114420produces warnings if the STRING contains the "," or the "#" character.
36124421
36134422=end original
36144423
36154424よくある間違いは、単語をカンマで区切ったり、複数行の C<qw> 文字列の中に
36164425コメントを書いたりすることです。
36174426このために、C<usr warnings> プラグマと B<-w> スイッチ
36184427(つまり、C<$^W> 変数) は STRING に "," や "#" の文字が入っていると
36194428警告を出します。
36204429
4430=item tr/SEARCHLIST/REPLACEMENTLIST/cdsr
3622=item tr/SEARCHLIST/REPLACEMENTLIST/cds
36234431X<tr> X<y> X<transliterate> X</c> X</d> X</s>
36244432
3625=item y/SEARCHLIST/REPLACEMENTLIST/cds
4433=item y/SEARCHLIST/REPLACEMENTLIST/cdsr
36264434
36274435=begin original
36284436
36294437Transliterates all occurrences of the characters found in the search list
36304438with the corresponding character in the replacement list. It returns
36314439the number of characters replaced or deleted. If no string is
3632specified via the =~ or !~ operator, the $_ string is transliterated. (The
4440specified via the C<=~> or C<!~> operator, the $_ string is transliterated.
3633string specified with =~ must be a scalar variable, an array element, a
3634hash element, or an assignment to one of those, i.e., an lvalue.)
36354441
36364442=end original
36374443
36384444検索リスト (SEARCHLIST) に含まれる文字を、対応する置換リスト
36394445(REPLACEMENTLIST) の文字に変換します。
36404446置換または削除が行なわれた、文字数を返します。
3641=~ 演算子や =! 演算子で文字列が指定されていなければ、$_ の文字列が
4447C<=~> 演算子や C<!~> 演算子で文字列が指定されていなければ、$_ の文字列が
36424448変換されます。
3643(=~ で指定される文字列は、スカラ変数、配列要素、ハッシュ要素、
3644あるいはこれらへの代入式といった左辺値でなければなりません。)
36454449
36464450=begin original
36474451
4452If the C</r> (non-destructive) option is present, a new copy of the string
4453is made and its characters transliterated, and this copy is returned no
4454matter whether it was modified or not: the original string is always
4455left unchanged. The new copy is always a plain string, even if the input
4456string is an object or a tied variable.
4457
4458=end original
4459
4460C</r> (非破壊) オプションがあると、文字列の新しいコピーが作られてその
4461文字が変換され、変更されたかどうかに関わらずこのコピーが返されます:
4462元の文字列は常に無変更で残されます。
4463新しいコピーは、たとえ入力がオブジェクトや tie された変数でも、常に
4464プレーンな文字列です。
4465
4466=begin original
4467
4468Unless the C</r> option is used, the string specified with C<=~> must be a
4469scalar variable, an array element, a hash element, or an assignment to one
4470of those; in other words, an lvalue.
4471
4472=end original
4473
4474C</r> オプションが使われない限り、C<=~> で指定される文字列は、スカラ変数、
4475配列要素、ハッシュ要素、あるいはこれらへの代入式といった左辺値で
4476なければなりません。
4477
4478=begin original
4479
36484480A character range may be specified with a hyphen, so C<tr/A-J/0-9/>
36494481does the same replacement as C<tr/ACEGIBDFHJ/0246813579/>.
36504482For B<sed> devotees, C<y> is provided as a synonym for C<tr>. If the
36514483SEARCHLIST is delimited by bracketing quotes, the REPLACEMENTLIST has
3652its own pair of quotes, which may or may not be bracketing quotes,
4484its own pair of quotes, which may or may not be bracketing quotes;
3653e.g., C<tr[A-Z][a-z]> or C<tr(+\-*/)/ABCD/>.
4485for example, C<tr[aeiouy][yuoiea]> or C<tr(+\-*/)/ABCD/>.
36544486
36554487=end original
36564488
3657文字の範囲はハイフンを使って指定できます
4489文字の範囲はハイフンを使って指定できます; C<tr/A-J/0-9/> は
3658C<tr/A-J/0-9/> は C<tr/ACEGIBDFHJ/0246813579/> と同じ置換を行います。
4490C<tr/ACEGIBDFHJ/0246813579/> と同じ置換を行います。
36594491B<sed> の信仰者のために C<y> が C<tr> の同義語として提供されています。
3660SEARCHLIST を括弧類で括った場合には、
4492SEARCHLIST を括弧類で括った場合には、REPLACEMENTLIST 用に、もう一組の区切り
3661REPLACEMENTLIST 用に、もう一組の区切り文字を用意します
4493文字を用意します; これは、括弧類であっても、なくてもかまいません;
3662これは括弧類あっても、なくてもかまいません
4494例えばC<tr[aeiouy][yuoiea]> や C<tr(+\-*/)/ABCD/>
3663例: C<tr[A-Z][a-z]> や C<tr(+\-*/)/ABCD/>。
36644495
36654496=begin original
36664497
3667Note that C<tr> does B<not> do regular expression character classes
4498Note that C<tr> does B<not> do regular expression character classes such as
3668such as C<\d> or C<[:lower:]>. The C<tr> operator is not equivalent to
4499C<\d> or C<\pL>. The C<tr> operator is not equivalent to the tr(1)
3669the tr(1) utility. If you want to map strings between lower/upper
4500utility. If you want to map strings between lower/upper cases, see
3670cases, see L<perlfunc/lc> and L<perlfunc/uc>, and in general consider
4501L<perlfunc/lc> and L<perlfunc/uc>, and in general consider using the C<s>
3671using the C<s> operator if you need regular expressions.
4502operator if you need regular expressions. The C<\U>, C<\u>, C<\L>, and
4503C<\l> string-interpolation escapes on the right side of a substitution
4504operator will perform correct case-mappings, but C<tr[a-z][A-Z]> will not
4505(except sometimes on legacy 7-bit data).
36724506
36734507=end original
36744508
3675C<tr> は C<\d> や C<[:lower:]> といった正規表現文字クラスを
4509C<tr> は C<\d> や C<\pL> といった正規表現文字クラスを
36764510B<使わない> ことに注意してください。
36774511C<tr> 演算子は tr(1) ユーティリティと等価ではありません。
36784512文字列の大文字小文字をマップしたい場合は、
3679L<perlfunc/lc> と L<perlfunc/uc> を参照して下さい
4513L<perlfunc/lc> と L<perlfunc/uc> を参照して下さい; また正規表現が必要な
3680また正規表現が必要な場合には一般的に C<s> 演算子を使うことを
4514場合には一般的に C<s> 演算子を使うことを考慮してみてください。
3681考慮してみてください。
4515置換演算子の右側での C<\U>, C<\u>, C<\L>, C<\l> の文字変換エスケープは
4516正しい大文字小文字マッピングを実行しますが、C<tr[a-z][A-Z]> は
4517(レガシーな 7 ビットデータを除いて) 動作しません。
36824518
36834519=begin original
36844520
36854521Note also that the whole range idea is rather unportable between
36864522character sets--and even within character sets they may cause results
36874523you probably didn't expect. A sound principle is to use only ranges
36884524that begin from and end at either alphabets of equal case (a-e, A-E),
36894525or digits (0-4). Anything else is unsafe. If in doubt, spell out the
36904526character sets in full.
36914527
36924528=end original
36934529
36944530範囲指定という考え方は文字セットが異なる場合はやや移植性に欠けることにも
36954531注意してください -- そして同じ文字セットでも恐らく期待しているのとは違う
36964532結果を引き起こすこともあります。
36974533健全な原則としては、範囲の最初と最後をどちらもアルファベット
36984534(大文字小文字も同じ)(a-e, A-E)にするか、どちらも数字にする(0-4)ことです。
36994535それ以外は全て安全ではありません。
37004536疑わしいときは、文字セットを完全に書き出してください。
37014537
37024538=begin original
37034539
37044540Options:
37054541
37064542=end original
37074543
37084544オプションは以下の通りです:
37094545
37104546=begin original
37114547
37124548 c Complement the SEARCHLIST.
37134549 d Delete found but unreplaced characters.
37144550 s Squash duplicate replaced characters.
4551 r Return the modified string and leave the original string
4552 untouched.
37154553
37164554=end original
37174555
3718 c SEARCHLIST を補集合にする
4556 c SEARCHLIST を補集合にする
3719 d 見つかったが置換されなかった文字を削除する
4557 d 見つかったが置換されなかった文字を削除する
3720 s 置換された文字が重なったときに圧縮する
4558 s 置換された文字が重なったときに圧縮する
4559 r 修正した結果を返し、もとの文字列はそのままにする。
37214560
37224561=begin original
37234562
37244563If the C</c> modifier is specified, the SEARCHLIST character set
37254564is complemented. If the C</d> modifier is specified, any characters
37264565specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.
37274566(Note that this is slightly more flexible than the behavior of some
37284567B<tr> programs, which delete anything they find in the SEARCHLIST,
37294568period.) If the C</s> modifier is specified, sequences of characters
37304569that were transliterated to the same character are squashed down
37314570to a single instance of the character.
37324571
37334572=end original
37344573
37354574C</c> 修飾子が指定されると、SEARCHLIST には補集合が指定されたものと
37364575解釈されます。
37374576C</d> 修飾子が指定されると、SEARCHLIST に指定されて、
37384577REPLACEMENTLIST に対応するものがない文字が削除されます。
37394578(これは、SEARCHLIST で見つかったものを削除する、ただそれだけの、ある種の
37404579B<tr> プログラムの動作よりと比べれば、いく分柔軟なものになっています。)
37414580C</s> 修飾子が指定されると、同じ文字に文字変換された文字の並びを、
3742その文字 1 文字だけに圧縮します。 
4581その文字 1 文字だけに圧縮します。
37434582
37444583=begin original
37454584
37464585If the C</d> modifier is used, the REPLACEMENTLIST is always interpreted
37474586exactly as specified. Otherwise, if the REPLACEMENTLIST is shorter
37484587than the SEARCHLIST, the final character is replicated till it is long
37494588enough. If the REPLACEMENTLIST is empty, the SEARCHLIST is replicated.
37504589This latter is useful for counting characters in a class or for
37514590squashing character sequences in a class.
37524591
37534592=end original
37544593
37554594C</d> 修飾子が使われると、REPLACEMENTLIST は、常に指定された通りに
37564595解釈されます。
37574596C</d> が指定されない場合で、REPLACEMENTLIST が SEARCHLIST よりも短いと、
37584597同じ長さになるまで、REPLACEMENTLIST の最後の文字が
37594598繰り返されているものとして扱われます。
37604599REPLACEMENTLIST が空文字列でのときには、SEARCHLIST と同じになります。
37614600後者は、ある文字クラスに含まれる文字数を数えるときや、
37624601ある文字クラスの文字の並びを圧縮するようなときに便利です。
37634602
37644603=begin original
37654604
37664605Examples:
37674606
37684607=end original
37694608
37704609例:
37714610
3772 $ARGV[1] =~ tr/A-Z/a-z/; # canonicalize to lower case
4611 $ARGV[1] =~ tr/A-Z/a-z/; # canonicalize to lower case ASCII
37734612
37744613 $cnt = tr/*/*/; # count the stars in $_
37754614
37764615 $cnt = $sky =~ tr/*/*/; # count the stars in $sky
37774616
37784617 $cnt = tr/0-9//; # count the digits in $_
37794618
37804619 tr/a-zA-Z//s; # bookkeeper -> bokeper
37814620
37824621 ($HOST = $host) =~ tr/a-z/A-Z/;
4622 $HOST = $host =~ tr/a-z/A-Z/r; # same thing
37834623
4624 $HOST = $host =~ tr/a-z/A-Z/r # chained with s///r
4625 =~ s/:/ -p/r;
4626
37844627 tr/a-zA-Z/ /cs; # change non-alphas to single space
37854628
4629 @stripped = map tr/a-zA-Z/ /csr, @original;
4630 # /r with map
4631
37864632 tr [\200-\377]
3787 [\000-\177]; # delete 8th bit
4633 [\000-\177]; # wickedly delete 8th bit
37884634
37894635=begin original
37904636
37914637If multiple transliterations are given for a character, only the
37924638first one is used:
37934639
37944640=end original
37954641
37964642複数の文字変換が一つの文字について指定されると、最初のものだけが使われます。
37974643
37984644 tr/AAA/XYZ/
37994645
38004646=begin original
38014647
38024648will transliterate any A to X.
38034649
38044650=end original
38054651
38064652は A を X に変換します。
38074653
38084654=begin original
38094655
38104656Because the transliteration table is built at compile time, neither
38114657the SEARCHLIST nor the REPLACEMENTLIST are subjected to double quote
38124658interpolation. That means that if you want to use variables, you
38134659must use an eval():
38144660
38154661=end original
38164662
38174663変換テーブルはコンパイル時に作られるので、SEARCHLIST も
38184664REPLACEMENTLIST もダブルクォート展開の対象とはなりません。
38194665変数を使いたい場合には、eval() を使わなければならないということです:
38204666
38214667 eval "tr/$oldlist/$newlist/";
38224668 die $@ if $@;
38234669
38244670 eval "tr/$oldlist/$newlist/, 1" or die $@;
38254671
38264672=item <<EOF
38274673X<here-doc> X<heredoc> X<here-document> X<<< << >>>
38284674
38294675=begin original
38304676
38314677A line-oriented form of quoting is based on the shell "here-document"
38324678syntax. Following a C<< << >> you specify a string to terminate
38334679the quoted material, and all lines following the current line down to
38344680the terminating string are the value of the item.
38354681
38364682=end original
38374683
38384684クォートの行指向形式は、シェルの「ヒアドキュメント」構文を基にしています。
38394685C<< << >> に引き続いて、クォートされるテキストを終了させる文字列を指定でき、
38404686現在の行の次の行から終端文字列までの全ての行がその項目の値となります。
38414687
38424688=begin original
38434689
38444690The terminating string may be either an identifier (a word), or some
38454691quoted text. An unquoted identifier works like double quotes.
38464692There may not be a space between the C<< << >> and the identifier,
38474693unless the identifier is explicitly quoted. (If you put a space it
38484694will be treated as a null identifier, which is valid, and matches the
38494695first empty line.) The terminating string must appear by itself
38504696(unquoted and with no surrounding whitespace) on the terminating line.
38514697
38524698=end original
38534699
38544700終端文字列には、識別子(単語) かクォートされたテキストが使えます。
38554701クォートされていない識別子は、ダブルクォートのように扱われます。
38564702識別子がクォートされていない場合は、C<< << >> と識別子の間に
38574703空白を入れてはいけません。
38584704(もし空白を入れると、空識別子として扱われます; これは有効で、
38594705最初の空行にマッチするようになります。)
38604706終端文字列は終端行に単体で(クォートされず、前後にも空白なしで)
38614707現れなければなりません。
38624708
38634709=begin original
38644710
38654711If the terminating string is quoted, the type of quotes used determine
38664712the treatment of the text.
38674713
38684714=end original
38694715
38704716終端文字列がクォートされている場合には、そのクォートの種類によって、
38714717クォートされるテキストの扱い決められます。
38724718
38734719=over 4
38744720
38754721=item Double Quotes
38764722
38774723=begin original
38784724
38794725Double quotes indicate that the text will be interpolated using exactly
38804726the same rules as normal double quoted strings.
38814727
38824728=end original
38834729
38844730ダブルクォートは、通常のダブルクォートされた文字列と全く同じ規則を使って
38854731変数展開されることを示します。
38864732
38874733 print <<EOF;
38884734 The price is $Price.
38894735 EOF
38904736
38914737 print << "EOF"; # same as above
38924738 The price is $Price.
38934739 EOF
38944740
4741
38954742=item Single Quotes
38964743
38974744=begin original
38984745
38994746Single quotes indicate the text is to be treated literally with no
39004747interpolation of its content. This is similar to single quoted
39014748strings except that backslashes have no special meaning, with C<\\>
39024749being treated as two backslashes and not one as they would in every
39034750other quoting construct.
39044751
39054752=end original
39064753
39074754シングルクォートは、内容が展開されずにリテラルに扱われることを
39084755意味します。
39094756これはシングルクォート文字列と似ていますが、バックスラッシュは
39104757特別な意味を持たず、他の全てのクォート構造違って、C<\\> は
39114758二つのバックスラッシュとして扱われることが違います。
39124759
39134760=begin original
39144761
4762Just as in the shell, a backslashed bareword following the C<<< << >>>
4763means the same thing as a single-quoted string does:
4764
4765=end original
4766
4767シェルでの場合と同様、C<<< << >>> に引き続いてバックスラッシュ付きの
4768裸の単語があると、シングルクォートされた文字列と同じこととなります:
4769
4770 $cost = <<'VISTA'; # hasta la ...
4771 That'll be $10 please, ma'am.
4772 VISTA
4773
4774 $cost = <<\VISTA; # Same thing!
4775 That'll be $10 please, ma'am.
4776 VISTA
4777
4778=begin original
4779
39154780This is the only form of quoting in perl where there is no need
39164781to worry about escaping content, something that code generators
39174782can and do make good use of.
39184783
39194784=end original
39204785
39214786これは、perl において、内容のエスケープについて心配する必要のない
39224787唯一の形で、コードジェネレータがうまく使えるものです。
39234788
39244789=item Backticks
39254790
39264791=begin original
39274792
39284793The content of the here doc is treated just as it would be if the
39294794string were embedded in backticks. Thus the content is interpolated
39304795as though it were double quoted and then executed via the shell, with
39314796the results of the execution returned.
39324797
39334798=end original
39344799
3935ドキュメントのの内容は、文字列がバッククォートで
4800ドキュメントのの内容は、文字列がバッククォートで
39364801埋め込まれているかのように扱われます。
39374802したがって、その内容、はダブルクォートされているかのように変数展開され、
39384803その後シェル経由で実行され、実行された結果になります。
39394804
39404805 print << `EOC`; # execute command and get results
39414806 echo hi there
39424807 EOC
39434808
39444809=back
39454810
39464811=begin original
39474812
39484813It is possible to stack multiple here-docs in a row:
39494814
39504815=end original
39514816
3952複数のヒドキュメントを連続してスタックすることも可能です:
4817複数のヒドキュメントを連続してスタックすることも可能です:
39534818
39544819 print <<"foo", <<"bar"; # you can stack them
39554820 I said foo.
39564821 foo
39574822 I said bar.
39584823 bar
39594824
39604825 myfunc(<< "THIS", 23, <<'THAT');
39614826 Here's a line
39624827 or two.
39634828 THIS
39644829 and here's another.
39654830 THAT
39664831
39674832=begin original
39684833
39694834Just don't forget that you have to put a semicolon on the end
39704835to finish the statement, as Perl doesn't know you're not going to
39714836try to do this:
39724837
39734838=end original
39744839
39754840以下のようなことをしたいのではないということが Perl にはわからないので、
39764841文を終わらせるためには末尾にセミコロンをつけなければならないことを
39774842忘れないで下さい:
39784843
39794844 print <<ABC
39804845 179231
39814846 ABC
39824847 + 20;
39834848
39844849=begin original
39854850
39864851If you want to remove the line terminator from your here-docs,
39874852use C<chomp()>.
39884853
39894854=end original
39904855
3991ドキュメントから行終端子を除去したい場合は、C<chomp()> を使ってください。
4856ドキュメントから行終端子を除去したい場合は、C<chomp()> を使ってください。
39924857
39934858 chomp($string = <<'END');
39944859 This is a string.
39954860 END
39964861
39974862=begin original
39984863
39994864If you want your here-docs to be indented with the rest of the code,
40004865you'll need to remove leading whitespace from each line manually:
40014866
40024867=end original
40034868
40044869ヒアドキュメントをソースのほかの部分からインデントしたい場合、
40054870各行の先頭の空白は手動で取り除く必要があります:
40064871
40074872 ($quote = <<'FINIS') =~ s/^\s+//gm;
40084873 The Road goes ever on and on,
40094874 down from the door where it began.
40104875 FINIS
40114876
40124877=begin original
40134878
40144879If you use a here-doc within a delimited construct, such as in C<s///eg>,
40154880the quoted material must come on the lines following the final delimiter.
40164881So instead of
40174882
40184883=end original
40194884
40204885C<s///eg> のようなデリミタ構造の中でヒアドキュメントを使う場合、
40214886クォートされたものは最後のデリミタに引き続くものとして来なければなりません。
40224887従って、以下のようではなく:
40234888
40244889 s/this/<<E . 'that'
40254890 the other
40264891 E
40274892 . 'more '/eg;
40284893
40294894=begin original
40304895
40314896you have to write
40324897
40334898=end original
40344899
40354900以下のように書かなければなりません:
40364901
40374902 s/this/<<E . 'that'
40384903 . 'more '/eg;
40394904 the other
40404905 E
40414906
40424907=begin original
40434908
40444909If the terminating identifier is on the last line of the program, you
40454910must be sure there is a newline after it; otherwise, Perl will give the
40464911warning B<Can't find string terminator "END" anywhere before EOF...>.
40474912
40484913=end original
40494914
40504915プログラムの最後の行に終端識別子がある場合、その後には
40514916改行がなければなりません; さもなければ、Perl は
40524917B<Can't find string terminator "END" anywhere before EOF...> という
40534918警告を出します。
40544919
40554920=begin original
40564921
4057Additionally, the quoting rules for the end of string identifier are not
4922Additionally, quoting rules for the end-of-string identifier are
4058related to Perl's quoting rules -- C<q()>, C<qq()>, and the like are not
4923unrelated to Perl's quoting rules. C<q()>, C<qq()>, and the like are not
40594924supported in place of C<''> and C<"">, and the only interpolation is for
40604925backslashing the quoting character:
40614926
40624927=end original
40634928
40644929さらに、文字列終端識別子に対するクォートルールは Perl のクォートルールとは
4065関係がありません -- C<q()>, C<qq()> および同種のものは C<''> や C<""> の
4930関係がありません
4931C<q()>, C<qq()> および同種のものは C<''> や C<""> の
40664932代わりのなるものには対応しておらず、文字をクォートするための
40674933バックスラッシュだけが展開されます:
40684934
40694935 print << "abc\"def";
40704936 testing...
40714937 abc"def
40724938
40734939=begin original
40744940
40754941Finally, quoted strings cannot span multiple lines. The general rule is
40764942that the identifier must be a string literal. Stick with that, and you
40774943should be safe.
40784944
40794945=end original
40804946
40814947最後に、クォートされた文字列は複数行にかかることはありません。
40824948識別子に関する一般的なルールは、文字列リテラルでなければならいことです。
40834949これに従っていれば、安全のはずです。
40844950
40854951=back
40864952
40874953=head2 Gory details of parsing quoted constructs
40884954X<quote, gory details>
40894955
40904956(クォートされた構造のパースに関する詳細)
40914957
40924958=begin original
40934959
40944960When presented with something that might have several different
40954961interpretations, Perl uses the B<DWIM> (that's "Do What I Mean")
40964962principle to pick the most probable interpretation. This strategy
40974963is so successful that Perl programmers often do not suspect the
40984964ambivalence of what they write. But from time to time, Perl's
40994965notions differ substantially from what the author honestly meant.
41004966
41014967=end original
41024968
41034969何か複数の解釈が可能な表現があった場合、Perl は最も確からしい解釈を
41044970選択するために B<DWIM> ("Do What I Mean")原則を使います。
41054971この戦略は非常に成功したので、Perl プログラマはしばしば
41064972自分が書いたものの矛盾を疑いません。
41074973しかし時間がたつにつれて、Perl の概念は作者が本当に意味していたものから
41084974かなり変わりました。
41094975
41104976=begin original
41114977
41124978This section hopes to clarify how Perl handles quoted constructs.
41134979Although the most common reason to learn this is to unravel labyrinthine
41144980regular expressions, because the initial steps of parsing are the
41154981same for all quoting operators, they are all discussed together.
41164982
41174983=end original
41184984
41194985この章では Perl がどのようにクォートされた構造を扱うかを
41204986明確にしようと思います。
41214987これを学ぼうとする最もよくある理由は正規表現の迷宮をほぐすためですが、
41224988パースの初期ステップは全てのクォート演算子で同じなので、全て同時に扱います。
41234989
41244990=begin original
41254991
41264992The most important Perl parsing rule is the first one discussed
41274993below: when processing a quoted construct, Perl first finds the end
41284994of that construct, then interprets its contents. If you understand
41294995this rule, you may skip the rest of this section on the first
41304996reading. The other rules are likely to contradict the user's
41314997expectations much less frequently than this first one.
41324998
41334999=end original
41345000
41355001Perl のパースに関するルールで最も重要なものは以下で述べているうち
4136最初のものです
5002最初のものです: つまり、クォートされた構造を処理するときは、Perl はまずその
4137つまり、クォートされた構造を処理するときはPerl はまずの構造の
5003構造の最後探して、それから中身を解釈します。
4138最後を探して、それから中身を解釈します。
41395004このルールがわかれば、とりあえずはこの章の残りは読み飛ばしてもかまいません。
41405005その他のルールは最初のルールに比べてユーザーの予想に反する頻度は
41415006はるかに少ないです。
41425007
41435008=begin original
41445009
41455010Some passes discussed below are performed concurrently, but because
41465011their results are the same, we consider them individually. For different
41475012quoting constructs, Perl performs different numbers of passes, from
41485013one to four, but these passes are always performed in the same order.
41495014
41505015=end original
41515016
41525017以下で議論するパスには同時に実行されるものもありますが、
41535018結果は同じことなので、別々に考えることにします。
41545019クォート構造の種類によって、Perl が実行するパスの数は
415550201 から 4 まで異なりますが、これらのパスは常に同じ順番で実行されます。
41565021
41575022=over 4
41585023
41595024=item Finding the end
41605025
41615026(最後を探す)
41625027
41635028=begin original
41645029
41655030The first pass is finding the end of the quoted construct, where
41665031the information about the delimiters is used in parsing.
41675032During this search, text between the starting and ending delimiters
41685033is copied to a safe location. The text copied gets delimiter-independent.
41695034
41705035=end original
41715036
41725037最初のパスは、クォート構造の末尾を探して、パース中に使うデリミタの情報が
41735038どこかを探すものです。
41745039検索中に、開始デリミタと終了デリミタの間のテキストは安全な場所に
41755040コピーされます。
41765041コピーされたテキストはデリミタに依存しません。
41775042
41785043=begin original
41795044
41805045If the construct is a here-doc, the ending delimiter is a line
41815046that has a terminating string as the content. Therefore C<<<EOF> is
41825047terminated by C<EOF> immediately followed by C<"\n"> and starting
41835048from the first column of the terminating line.
41845049When searching for the terminating line of a here-doc, nothing
41855050is skipped. In other words, lines after the here-doc syntax
41865051are compared with the terminating string line by line.
41875052
41885053=end original
41895054
4190構造がヒドキュメントの場合、終了デリミタは内容として終端文字列を持つ
5055構造がヒドキュメントの場合、終了デリミタは内容として終端文字列を持つ
41915056行です。
41925057従って、C<<<EOF> は、C<"\n"> の直後の、終端行の最初の列から始まる C<EOF> で
41935058終端します。
4194ドキュメントの終端行を探すとき、読み飛ばされるものはありません。
5059ドキュメントの終端行を探すとき、読み飛ばされるものはありません。
4195言い換えると、ヒドキュメント文法以降の行は、1 行毎に終端文字列と
5060言い換えると、ヒドキュメント文法以降の行は、1 行毎に終端文字列と
41965061比較されます。
41975062
41985063=begin original
41995064
42005065For the constructs except here-docs, single characters are used as starting
42015066and ending delimiters. If the starting delimiter is an opening punctuation
42025067(that is C<(>, C<[>, C<{>, or C<< < >>), the ending delimiter is the
42035068corresponding closing punctuation (that is C<)>, C<]>, C<}>, or C<< > >>).
42045069If the starting delimiter is an unpaired character like C</> or a closing
42055070punctuation, the ending delimiter is same as the starting delimiter.
42065071Therefore a C</> terminates a C<qq//> construct, while a C<]> terminates
42075072C<qq[]> and C<qq]]> constructs.
42085073
42095074=end original
42105075
4211ドキュメント以外の構造では、1 文字が開始デリミタと終了デリミタとして
5076ドキュメント以外の構造では、1 文字が開始デリミタと終了デリミタとして
42125077使われます。
42135078開始デリミタが組の開き文字(C<(>, C<[>, C<{>, C<< < >> のいずれか)の場合、
42145079終了デリミタは対応する組の閉じ文字(つまり C<)>, C<]>, C<}>, C<< > >>) です。
42155080開始デリミタが C</> 組になる文字や、組の閉じ文字の場合、終了デリミタは
42165081開始デリミタと同じです。
42175082従って C</> は C<qq//> 構造を終端し、一方 C<]> は C<qq[]> と C<qq]]> 構造を
42185083終端します。
42195084
42205085=begin original
42215086
42225087When searching for single-character delimiters, escaped delimiters
42235088and C<\\> are skipped. For example, while searching for terminating C</>,
42245089combinations of C<\\> and C<\/> are skipped. If the delimiters are
42255090bracketing, nested pairs are also skipped. For example, while searching
42265091for closing C<]> paired with the opening C<[>, combinations of C<\\>, C<\]>,
42275092and C<\[> are all skipped, and nested C<[> and C<]> are skipped as well.
42285093However, when backslashes are used as the delimiters (like C<qq\\> and
42295094C<tr\\\>), nothing is skipped.
42305095During the search for the end, backslashes that escape delimiters
42315096are removed (exactly speaking, they are not copied to the safe location).
42325097
42335098=end original
42345099
423551001 文字のデリミタを探す場合、エスケープされたデリミタと C<\\> は
42365101読み飛ばします。
42375102例えば、C</> を探しているときには、C<\\> と C<\/> の組み合わせを
42385103読み飛ばします。
42395104デリミタがかっこでくくられている場合は、ネストした組も読み飛ばされます。
42405105例えば、開きの C<[> と組になる閉じの C<]> を探しているときには、
42415106C<\\>, C<\]>, C<\[> の組み合わせをは全て読み飛ばし、
42425107さらにネストした C<[>, C<]> も読み飛ばします。
42435108しかし、(C<qq\\> や C<tr\\\> のように)バックスラッシュがデリミタとして
42445109使われた場合、何も読み飛ばしません。
42455110末尾の検索中、デリミタをエスケープするバックスラッシュは除去されます
42465111(述べたとおりに正確に、安全な場所にコピーはされません)。
42475112
42485113=begin original
42495114
42505115For constructs with three-part delimiters (C<s///>, C<y///>, and
42515116C<tr///>), the search is repeated once more.
42525117If the first delimiter is not an opening punctuation, three delimiters must
42535118be same such as C<s!!!> and C<tr)))>, in which case the second delimiter
42545119terminates the left part and starts the right part at once.
4255If the left part is delimited by bracketing punctuations (that is C<()>,
5120If the left part is delimited by bracketing punctuation (that is C<()>,
42565121C<[]>, C<{}>, or C<< <> >>), the right part needs another pair of
4257delimiters such as C<s(){}> and C<tr[]//>. In these cases, whitespaces
5122delimiters such as C<s(){}> and C<tr[]//>. In these cases, whitespace
42585123and comments are allowed between both parts, though the comment must follow
4259at least one whitespace; otherwise a character expected as the start of
5124at least one whitespace character; otherwise a character expected as the
4260the comment may be regarded as the starting delimiter of the right part.
5125start of the comment may be regarded as the starting delimiter of the right part.
42615126
42625127=end original
42635128
426451293 つのデリミタからなる構造 (C<s///>, C<y///>, C<tr///>) の場合、
42655130検索はもう一度繰り返されます。
42665131最初のデリミタが開きかっこでない場合、C<s!!!> and C<tr)))> のように
426751323 つのデリミタは同じでなければなりません;
42685133この場合、2 番目のデリミタが左側の終端と右側の開始を同時に行います。
42695134左側のデリミタがかっこを構成するもの (これは C<()>,
42705135C<[]>, C<{}>, C<< <> >> のいずれか) の場合、右側も
42715136C<s(){}> や C<tr[]//> のようなデリミタである必要があります。
42725137これらの場合、右側と左側の間には空白やコメントを置けますが、
4273コメントは少なくとも一つの空白の後である必要があります;
5138コメントは少なくとも一つの空白文字の後である必要があります;
42745139さもなければコメントの開始文字が右側の開始デリミタとして扱われてしまいます。
42755140
42765141=begin original
42775142
42785143During this search no attention is paid to the semantics of the construct.
42795144Thus:
42805145
42815146=end original
42825147
42835148検索する間、構造の文脈は考慮しません。
42845149従って:
42855150
42865151 "$hash{"$foo/$bar"}"
42875152
42885153=begin original
42895154
42905155or:
42915156
42925157=end original
42935158
42945159または:
42955160
42965161 m/
42975162 bar # NOT a comment, this slash / terminated m//!
42985163 /x
42995164
43005165=begin original
43015166
43025167do not form legal quoted expressions. The quoted part ends on the
43035168first C<"> and C</>, and the rest happens to be a syntax error.
43045169Because the slash that terminated C<m//> was followed by a C<SPACE>,
43055170the example above is not C<m//x>, but rather C<m//> with no C</x>
43065171modifier. So the embedded C<#> is interpreted as a literal C<#>.
43075172
43085173=end original
43095174
43105175は正しいクォート表現ではありません。
43115176クォートは最初の C<"> や C</> で終わりとなり、残りの部分は文法エラーと
43125177なります。
43135178C<m//> を終わらせているスラッシュの次に来ているのが C<空白> なので、
43145179上の例では C<m//x> ではなく、C</x> なしの C<m//> となります。
43155180従って、中にある C<#> はリテラルな C<#> として扱われます。
43165181
43175182=begin original
43185183
43195184Also no attention is paid to C<\c\> (multichar control char syntax) during
43205185this search. Thus the second C<\> in C<qq/\c\/> is interpreted as a part
43215186of C<\/>, and the following C</> is not recognized as a delimiter.
43225187Instead, use C<\034> or C<\x1c> at the end of quoted constructs.
43235188
43245189=end original
43255190
43265191この検索の間、C<\c\> (マルチバイト文字制御文法)に注意は払われません。
43275192従って、C<qq/\c\/> の 2 番目の C<\> は C<\/> の一部として扱われ、
43285193引き続く C</> はデリミタとして認識されません。
43295194代わりに、クォート構造の末尾に C<\034> か C<\x1c> を使ってください。
43305195
43315196=item Interpolation
43325197X<interpolation>
43335198
43345199(展開)
43355200
43365201=begin original
43375202
43385203The next step is interpolation in the text obtained, which is now
43395204delimiter-independent. There are multiple cases.
43405205
43415206=end original
43425207
43435208次のステップは、得られた(デリミタに依存しない)テキストに対する展開です。
43445209複数のケースがあります。
43455210
43465211=over 4
43475212
43485213=item C<<<'EOF'>
43495214
43505215=begin original
43515216
43525217No interpolation is performed.
43535218Note that the combination C<\\> is left intact, since escaped delimiters
43545219are not available for here-docs.
43555220
43565221=end original
43575222
43585223展開は行われません。
43595224C<\\> の組み合わせはそのままであることに注意してください;
4360ドキュメントではデリミタのエスケープはできないからです。
5225ドキュメントではデリミタのエスケープはできないからです。
43615226
43625227=item C<m''>, the pattern of C<s'''>
43635228
43645229=begin original
43655230
43665231No interpolation is performed at this stage.
43675232Any backslashed sequences including C<\\> are treated at the stage
43685233to L</"parsing regular expressions">.
43695234
43705235=end original
43715236
43725237このステージでは展開は行われません。
43735238C<\\> を含む、バックスラッシュ付きのシーケンスは
43745239L</"parsing regular expressions"> で扱われます。
43755240
43765241=item C<''>, C<q//>, C<tr'''>, C<y'''>, the replacement of C<s'''>
43775242
43785243=begin original
43795244
43805245The only interpolation is removal of C<\> from pairs of C<\\>.
43815246Therefore C<-> in C<tr'''> and C<y'''> is treated literally
43825247as a hyphen and no character range is available.
43835248C<\1> in the replacement of C<s'''> does not work as C<$1>.
43845249
43855250=end original
43865251
43875252C<\\> の組における C<\> の削除のみが行われます。
43885253従って、C<tr'''> や C<y'''> の中にある C<-> は文字通りハイフンとして扱われ、
43895254文字範囲は使えません。
43905255C<s'''> の置換文字列での C<\1> は C<$1> としては動作しません。
43915256
43925257=item C<tr///>, C<y///>
43935258
43945259=begin original
43955260
43965261No variable interpolation occurs. String modifying combinations for
43975262case and quoting such as C<\Q>, C<\U>, and C<\E> are not recognized.
43985263The other escape sequences such as C<\200> and C<\t> and backslashed
43995264characters such as C<\\> and C<\-> are converted to appropriate literals.
44005265The character C<-> is treated specially and therefore C<\-> is treated
44015266as a literal C<->.
44025267
44035268=end original
44045269
44055270変数展開は行われません。
44065271C<\Q>, C<\U>, C<\E> のような、大文字小文字やクォートに関する、文字列を
44075272変更するような組み合わせは認識されません。
44085273C<\200> や C<\t> のようなその他のエスケープシーケンスや、
44095274C<\\> や C<\-> のようなバックスラッシュ付きの文字は、適切なリテラルに
44105275変換されます。
44115276文字 C<-> は特別扱いされるので、C<\-> はリテラルな C<-> として扱われます。
44125277
44135278=item C<"">, C<``>, C<qq//>, C<qx//>, C<< <file*glob> >>, C<<<"EOF">
44145279
44155280=begin original
44165281
44175282C<\Q>, C<\U>, C<\u>, C<\L>, C<\l> (possibly paired with C<\E>) are
44185283converted to corresponding Perl constructs. Thus, C<"$foo\Qbaz$bar">
44195284is converted to C<$foo . (quotemeta("baz" . $bar))> internally.
44205285The other escape sequences such as C<\200> and C<\t> and backslashed
44215286characters such as C<\\> and C<\-> are replaced with appropriate
44225287expansions.
44235288
44245289=end original
44255290
44265291C<\Q>, C<\U>, C<\u>, C<\L>, C<\l> (おそらくは C<\E> との組)は
44275292対応する Perl 構造に変換されます。
44285293従って、C<"$foo\Qbaz$bar"> は内部的に
44295294C<$foo . (quotemeta("baz" . $bar))> に変換されます。
44305295C<\200> や C<\t> のような、その他のエスケープシーケンスや、C<\\> や
44315296C<\-> のような、バックスラッシュがつけられた文字は適切な拡張に
44325297置換されます。
44335298
44345299=begin original
44355300
44365301Let it be stressed that I<whatever falls between C<\Q> and C<\E>>
44375302is interpolated in the usual way. Something like C<"\Q\\E"> has
44385303no C<\E> inside. instead, it has C<\Q>, C<\\>, and C<E>, so the
44395304result is the same as for C<"\\\\E">. As a general rule, backslashes
44405305between C<\Q> and C<\E> may lead to counterintuitive results. So,
44415306C<"\Q\t\E"> is converted to C<quotemeta("\t")>, which is the same
44425307as C<"\\\t"> (since TAB is not alphanumeric). Note also that:
44435308
44445309=end original
44455310
44465311I<C<\Q> と C<\E> の間にある全てのもの> が通常の方法で展開されます。
4447C<"\Q\\E"> のようなものは内部にあるのは C<\E> ではなく、
5312C<"\Q\\E"> のようなものは内部にあるのは C<\E> ではありません。
44485313C<\Q>, C<\\>, C<E> であるので、結果は C<"\\\\E"> と同じになります。
44495314一般的なルールとして、C<\Q> と C<\E> の間にあるバックスラッシュは
44505315直感に反した結果になります。
44515316それで、C<"\Q\t\E"> は C<quotemeta("\t")> に変換され、これは(TAB は
44525317英数字ではないので C<"\\\t"> と同じです。
44535318以下のようなことにも注意してください:
44545319
44555320 $str = '\t';
44565321 return "\Q$str";
44575322
44585323=begin original
44595324
44605325may be closer to the conjectural I<intention> of the writer of C<"\Q\t\E">.
44615326
44625327=end original
44635328
44645329これは C<"\Q\t\E"> を書いた人の憶測上の I<意図> により近いです。
44655330
44665331=begin original
44675332
44685333Interpolated scalars and arrays are converted internally to the C<join> and
44695334C<.> catenation operations. Thus, C<"$foo XXX '@arr'"> becomes:
44705335
44715336=end original
44725337
44735338展開されたスカラと配列は内部で C<join> と C<.> の結合操作に変換されます。
44745339従って、C<"$foo XXX '@arr'"> は以下のようになります:
44755340
44765341 $foo . " XXX '" . (join $", @arr) . "'";
44775342
44785343=begin original
44795344
44805345All operations above are performed simultaneously, left to right.
44815346
44825347=end original
44835348
44845349上記の全ての操作は、左から右に同時に行われます。
44855350
44865351=begin original
44875352
44885353Because the result of C<"\Q STRING \E"> has all metacharacters
44895354quoted, there is no way to insert a literal C<$> or C<@> inside a
44905355C<\Q\E> pair. If protected by C<\>, C<$> will be quoted to became
44915356C<"\\\$">; if not, it is interpreted as the start of an interpolated
44925357scalar.
44935358
44945359=end original
44955360
44965361C<"\Q STRING \E"> の結果は全てのメタ文字がクォートされているので、
44975362C<\Q\E> の組の内側にリテラルの C<$> や C<@> を挿入する方法はありません。
44985363C<\> によって守られている場合、C<$> はクォートされて C<"\\\$"> と
4499なります
5364なります; そうでない場合、これは展開されるスカラ変数の開始として
4500そうでない場合、これは展開されるスカラ変数の開始として解釈されます。
5365解釈されます。
45015366
45025367=begin original
45035368
45045369Note also that the interpolation code needs to make a decision on
45055370where the interpolated scalar ends. For instance, whether
45065371C<< "a $b -> {c}" >> really means:
45075372
45085373=end original
45095374
45105375展開コードは、展開するスカラ変数がどこで終わるかを決定する必要が
45115376あることにも注意してください。
45125377例えば、C<< "a $b -> {c}" >> が実際には以下のどちらかになります:
45135378
45145379 "a " . $b . " -> {c}";
45155380
45165381=begin original
45175382
45185383or:
45195384
45205385=end original
45215386
45225387または:
45235388
45245389 "a " . $b -> {c};
45255390
45265391=begin original
45275392
45285393Most of the time, the longest possible text that does not include
45295394spaces between components and which contains matching braces or
45305395brackets. because the outcome may be determined by voting based
45315396on heuristic estimators, the result is not strictly predictable.
45325397Fortunately, it's usually correct for ambiguous cases.
45335398
45345399=end original
45355400
45365401ほとんどの場合、要素と、マッチする中かっこや大かっこの間に空白を含まない、
45375402最も長いテキストになります。
45385403出力は発見的な推定器をよる投票によって決定されるので、結果は厳密には
45395404予測できません。
45405405幸い、紛らわしい場合でも普通は正しいです。
45415406
45425407=item the replacement of C<s///>
45435408
45445409=begin original
45455410
45465411Processing of C<\Q>, C<\U>, C<\u>, C<\L>, C<\l>, and interpolation
45475412happens as with C<qq//> constructs.
45485413
45495414=end original
45505415
45515416C<\Q>, C<\U>, C<\u>, C<\L>, C<\l> の処理と展開が C<qq//> 構造と
45525417同じように起こります。
45535418
45545419=begin original
45555420
45565421It is at this step that C<\1> is begrudgingly converted to C<$1> in
45575422the replacement text of C<s///>, in order to correct the incorrigible
45585423I<sed> hackers who haven't picked up the saner idiom yet. A warning
45595424is emitted if the C<use warnings> pragma or the B<-w> command-line flag
45605425(that is, the C<$^W> variable) was set.
45615426
45625427=end original
45635428
45645429このステップでは、より健全な文法をまだ導入していない、手に負えない I<sed>
45655430ハッカーのために、C<s///> の置換テキストの中にある C<\1> を、しぶしぶながら
45665431C<$1> に変換します。
45675432C<use warnings> プラグマやコマンドラインオプション B<-w> (これは C<$^W>
45685433変数です) がセットされていると警告が生成されます。
45695434
45705435=item C<RE> in C<?RE?>, C</RE/>, C<m/RE/>, C<s/RE/foo/>,
45715436
45725437=begin original
45735438
45745439Processing of C<\Q>, C<\U>, C<\u>, C<\L>, C<\l>, C<\E>,
45755440and interpolation happens (almost) as with C<qq//> constructs.
45765441
45775442=end original
45785443
45795444C<\Q>, C<\U>, C<\u>, C<\L>, C<\l> C<\E> の処理と展開が C<qq//> 構造と
45805445(ほとんど)同じように起こります。
45815446
45825447=begin original
45835448
5449Processing of C<\N{...}> is also done here, and compiled into an intermediate
5450form for the regex compiler. (This is because, as mentioned below, the regex
5451compilation may be done at execution time, and C<\N{...}> is a compile-time
5452construct.)
5453
5454=end original
5455
5456C<\N{...}> の処理もここで行われ、正規表現コンパイラのための中間形式に
5457コンパイルされます。
5458(これは、後述するように、正規表現のコンパイルは実行時に行われ、
5459C<\N{...}> はコンパイル時の構文だからです。)
5460
5461=begin original
5462
45845463However any other combinations of C<\> followed by a character
45855464are not substituted but only skipped, in order to parse them
45865465as regular expressions at the following step.
45875466As C<\c> is skipped at this step, C<@> of C<\c@> in RE is possibly
45885467treated as an array symbol (for example C<@foo>),
45895468even though the same text in C<qq//> gives interpolation of C<\c@>.
45905469
45915470=end original
45925471
45935472しかし、その他の、C<\> の後に文字が続く組み合わせは置換されず、単に
45945473読み飛ばされます; これは以下のステップで正規表現としてパースするためです。
45955474ここでは C<\c> は読み飛ばされるので、正規表現中の C<\c@> の C<@> は
45965475配列のシンボル(例えば C<@foo>) と扱われる可能性があります;
45975476一方 C<qq//> 内の同じテキストは C<\c@> と展開されます。
45985477
45995478=begin original
46005479
46015480Moreover, inside C<(?{BLOCK})>, C<(?# comment )>, and
46025481a C<#>-comment in a C<//x>-regular expression, no processing is
46035482performed whatsoever. This is the first step at which the presence
46045483of the C<//x> modifier is relevant.
46055484
46065485=end original
46075486
46085487さらに、C<(?{BLOCK})>, C<(?# comment )>, C<//x> 正規表現での C<#> の
46095488コメントの中では、どのような処理も行われません。
46105489これは C<//x> 修飾子が影響を与える最初のステップです。
46115490
46125491=begin original
46135492
46145493Interpolation in patterns has several quirks: C<$|>, C<$(>, C<$)>, C<@+>
46155494and C<@-> are not interpolated, and constructs C<$var[SOMETHING]> are
46165495voted (by several different estimators) to be either an array element
46175496or C<$var> followed by an RE alternative. This is where the notation
46185497C<${arr[$bar]}> comes handy: C</${arr[0-9]}/> is interpreted as
46195498array element C<-9>, not as a regular expression from the variable
46205499C<$arr> followed by a digit, which would be the interpretation of
46215500C</$arr[0-9]/>. Since voting among different estimators may occur,
46225501the result is not predictable.
46235502
46245503=end original
46255504
46265505パターン内の展開ではいくつか特殊な動作をします:
46275506C<$|>, C<$(>, C<$)>, C<@+>, C<@-> は展開されず、
46285507C<$var[SOMETHING]> は(いくつかの異なる推定器によって)配列の要素か
46295508C<$var> の後に正規表現が続いているのかが投票されます。
46305509これは C<${arr[$bar]}> が便利になるところです: C</${arr[0-9]}/> は
46315510配列要素 C<-9> として解釈され、C</$arr[0-9]/> の場合のように C<$arr> の後に
46325511数値が続いているような正規表現としては解釈されません。
46335512異なった推定器によって投票されることがあるので、結果は予測できません。
46345513
46355514=begin original
46365515
46375516The lack of processing of C<\\> creates specific restrictions on
46385517the post-processed text. If the delimiter is C</>, one cannot get
46395518the combination C<\/> into the result of this step. C</> will
46405519finish the regular expression, C<\/> will be stripped to C</> on
46415520the previous step, and C<\\/> will be left as is. Because C</> is
46425521equivalent to C<\/> inside a regular expression, this does not
46435522matter unless the delimiter happens to be character special to the
46445523RE engine, such as in C<s*foo*bar*>, C<m[foo]>, or C<?foo?>; or an
46455524alphanumeric char, as in:
46465525
46475526=end original
46485527
46495528C<\\> を処理しないことにより、後処理したテキストに特定の制限があります。
46505529デリミタが C</> の場合、このステップの結果として C<\/> を得ることは
46515530できません。
46525531C</> は正規表現を終わらせ、C<\/> は前のステップで C</> に展開され、
46535532C<\\/> はそのまま残されます。
46545533C</> は正規表現の中では C<\/> と等価なので、これはたまたまデリミタが
46555534正規検索エンジンにとって特別な文字の場合、つまり C<s*foo*bar*>,
46565535C<m[foo]>, C<?foo?> のような場合、あるいは以下のように英数字でなければ、
46575536問題にはなりません:
46585537
46595538 m m ^ a \s* b mmx;
46605539
46615540=begin original
46625541
46635542In the RE above, which is intentionally obfuscated for illustration, the
46645543delimiter is C<m>, the modifier is C<mx>, and after delimiter-removal the
46655544RE is the same as for C<m/ ^ a \s* b /mx>. There's more than one
46665545reason you're encouraged to restrict your delimiters to non-alphanumeric,
46675546non-whitespace choices.
46685547
46695548=end original
46705549
46715550上記の正規表現では、説明のために意図的にわかりにくくしていますが、
46725551デリミタは C<m> で、修飾子は C<mx> で、デリミタを取り除いた後の
46735552正規表現は C<m/ ^ a \s* b /mx> と同じです。
46745553デリミタを英数字や空白でないものに制限するべきである理由は複数あります。
46755554
46765555=back
46775556
46785557=begin original
46795558
46805559This step is the last one for all constructs except regular expressions,
46815560which are processed further.
46825561
46835562=end original
46845563
4685これは正規表現以外の全ての構造にとって最後のステップです
5564これは正規表現以外の全ての構造にとって最後のステップです; 正規表現は
4686正規表現はさらに処理が続きます。
5565さらに処理が続きます。
46875566
46885567=item parsing regular expressions
46895568X<regexp, parse>
46905569
46915570(正規表現のパース)
46925571
46935572=begin original
46945573
46955574Previous steps were performed during the compilation of Perl code,
4696but this one happens at run time--although it may be optimized to
5575but this one happens at run time, although it may be optimized to
46975576be calculated at compile time if appropriate. After preprocessing
46985577described above, and possibly after evaluation if concatenation,
46995578joining, casing translation, or metaquoting are involved, the
47005579resulting I<string> is passed to the RE engine for compilation.
47015580
47025581=end original
47035582
47045583以前のステップは Perl コードのコンパイル中に実行されますが、
4705これは実行時に起こります -- しかし、もし適切ならコンパイル時に
5584これは実行時に起こります、もし適切ならコンパイル時に
47065585計算できるように最適化されることもあります。
47075586上記の前処理の後、そして必要なら連結、結合、大文字小文字変換、
47085587メタクォート化が行われた後、結果の I<文字列> がコンパイルのために
47095588正規表現エンジンに渡されます。
47105589
47115590=begin original
47125591
47135592Whatever happens in the RE engine might be better discussed in L<perlre>,
47145593but for the sake of continuity, we shall do so here.
47155594
47165595=end original
47175596
47185597正規表現エンジンで起こることについては L<perlre> で議論した方が
47195598よいでしょうが、継続性のために、ここでそれを行います。
47205599
47215600=begin original
47225601
47235602This is another step where the presence of the C<//x> modifier is
47245603relevant. The RE engine scans the string from left to right and
47255604converts it to a finite automaton.
47265605
47275606=end original
47285607
47295608これも C<//x> 修飾子の存在が関連するステップの一つです。
47305609正規表現エンジンは文字列を左から右にスキャンして、有限状態オートマトンに
47315610変換します。
47325611
47335612=begin original
47345613
47355614Backslashed characters are either replaced with corresponding
47365615literal strings (as with C<\{>), or else they generate special nodes
47375616in the finite automaton (as with C<\b>). Characters special to the
47385617RE engine (such as C<|>) generate corresponding nodes or groups of
47395618nodes. C<(?#...)> comments are ignored. All the rest is either
47405619converted to literal strings to match, or else is ignored (as is
47415620whitespace and C<#>-style comments if C<//x> is present).
47425621
47435622=end original
47445623
47455624バックスラッシュ付きの文字は(C<\{> のように)対応するリテラル文字列に
47465625置換されるか、あるいは(C<\b> のように)有限状態オートマトンの特別な
47475626ノードを生成します。
47485627(C<|> のような)正規表現エンジンにとって特別な文字は対応するノードか
47495628ノードのグループを生成します。
5629C<(?#...)> コメントは無視されます。
47505630残りの全てはマッチするリテラル文字列に変換されるか、そうでなければ
47515631(C<//x> が指定された時の空白と C<#> スタイルのコメントと同様に)
47525632無視されます。
47535633
47545634=begin original
47555635
47565636Parsing of the bracketed character class construct, C<[...]>, is
47575637rather different than the rule used for the rest of the pattern.
47585638The terminator of this construct is found using the same rules as
47595639for finding the terminator of a C<{}>-delimited construct, the only
47605640exception being that C<]> immediately following C<[> is treated as
47615641though preceded by a backslash. Similarly, the terminator of
47625642C<(?{...})> is found using the same rules as for finding the
47635643terminator of a C<{}>-delimited construct.
47645644
47655645=end original
47665646
47675647文字クラス構造 C<[...]> のパースは他のパターンとはルールが異なります。
47685648この構造の終端は C<{}> でデリミタされた構造の終端を検索するのと同じルールで
47695649検索されます; 唯一の例外は、C<[> の直後の C<]> はバックスラッシュが
47705650先行しているものとして扱われます。
47715651同様に、C<(?{...})> の終端は C<{}> でデリミタされた構造の終端を
47725652検索されるのと同じルールで検索されます。
47735653
47745654=begin original
47755655
47765656It is possible to inspect both the string given to RE engine and the
47775657resulting finite automaton. See the arguments C<debug>/C<debugcolor>
47785658in the C<use L<re>> pragma, as well as Perl's B<-Dr> command-line
47795659switch documented in L<perlrun/"Command Switches">.
47805660
47815661=end original
47825662
47835663正規表現に与えられる文字列と、結果としての有限状態オートマトンの両方を
47845664検査できます。
47855665C<use L<re>> プラグマの C<debug>/C<debugcolor> 引数と、
47865666L<perlrun/"Command Switches"> に記述されている B<-Dr> コマンドライン
47875667オプションを参照してください。
47885668
47895669=item Optimization of regular expressions
47905670X<regexp, optimization>
47915671
5672(正規表現の最適化)
5673
47925674=begin original
47935675
47945676This step is listed for completeness only. Since it does not change
47955677semantics, details of this step are not documented and are subject
47965678to change without notice. This step is performed over the finite
47975679automaton that was generated during the previous pass.
47985680
47995681=end original
48005682
48015683このステップは完全性のためだけにリストされています。
48025684これは意味論的には変化がないので、このステップの詳細は文書化されておらず、
48035685将来予告なしに変更されることがあります。
48045686このステップはここまでの処理で生成された有限オートマトンに対して
48055687適用されます。
48065688
48075689=begin original
48085690
48095691It is at this stage that C<split()> silently optimizes C</^/> to
48105692mean C</^/m>.
48115693
48125694=end original
48135695
48145696C<split()> で C</^/> を暗黙に C</^/m> に最適化するのもこのステップです。
48155697
48165698=back
48175699
48185700=head2 I/O Operators
48195701X<operator, i/o> X<operator, io> X<io> X<while> X<filehandle>
48205702X<< <> >> X<@ARGV>
48215703
48225704(I/O 演算子)
48235705
48245706=begin original
48255707
48265708There are several I/O operators you should know about.
48275709
48285710=end original
48295711
48305712知っておいた方がよい I/O 演算子もいくつかあります。
48315713
48325714=begin original
48335715
48345716A string enclosed by backticks (grave accents) first undergoes
48355717double-quote interpolation. It is then interpreted as an external
48365718command, and the output of that command is the value of the
48375719backtick string, like in a shell. In scalar context, a single string
48385720consisting of all output is returned. In list context, a list of
48395721values is returned, one per line of output. (You can set C<$/> to use
48405722a different line terminator.) The command is executed each time the
48415723pseudo-literal is evaluated. The status value of the command is
48425724returned in C<$?> (see L<perlvar> for the interpretation of C<$?>).
48435725Unlike in B<csh>, no translation is done on the return data--newlines
48445726remain newlines. Unlike in any of the shells, single quotes do not
48455727hide variable names in the command from interpretation. To pass a
48465728literal dollar-sign through to the shell you need to hide it with a
48475729backslash. The generalized form of backticks is C<qx//>. (Because
48485730backticks always undergo shell expansion as well, see L<perlsec> for
48495731security concerns.)
48505732X<qx> X<`> X<``> X<backtick> X<glob>
48515733
48525734=end original
48535735
48545736バッククォートで括られた文字列は、まず、ダブルクォート補完のように
48555737変数の展開が行なわれます。
48565738その後、シェルでの場合と同じように、外部コマンドとして解釈され、
48575739そのコマンドの出力がこのバッククォート文字列の値となります。
48585740スカラーコンテキストでは、出力すべてを含む一個の文字列が返されます。
48595741リストコンテキストでは、出力の 1 行 1 行が個々の要素となるリストが返されます。
48605742(C<$/> を設定すれば、行の終わりを示す文字を変えることができます。)
48615743コマンドは、この擬似リテラルが評価されるごとに実行されます。
48625744コマンドのステータス値は C<$?> に返されます (C<$?> の解釈については、
48635745L<perlvar> を参照してください)。
48645746B<csh> での場合とは違って、結果のデータに対する変換は行なわれず、
48655747改行は改行のままです。
48665748どのシェルとも違って、シングルクォートがコマンド中の変数名を
48675749解釈させないようにすることはありません。
48685750シェルにリテラルなドル記号を渡すには、バックスラッシュで
48695751エスケープしなければなりません。
48705752バッククォートの一般形は、C<qx//> です。
48715753(バッククォートは常にシェル展開されます。
48725754セキュリティに関しては L<perlsec> を参照して下さい)
48735755
48745756=begin original
48755757
48765758In scalar context, evaluating a filehandle in angle brackets yields
48775759the next line from that file (the newline, if any, included), or
48785760C<undef> at end-of-file or on error. When C<$/> is set to C<undef>
48795761(sometimes known as file-slurp mode) and the file is empty, it
48805762returns C<''> the first time, followed by C<undef> subsequently.
48815763
48825764=end original
48835765
48845766スカラーコンテキストで山括弧の中のファイルハンドルを評価すると、
48855767そのファイルから、次の行を読み込むことになります
4886(改行があればそれも含まれます)
5768(改行があればそれも含まれます); ファイルの最後またはエラーの場合は
4887ファイルの最後またはエラーの場合は C<undef> を返します。
5769C<undef> を返します。
48885770C<$/> が C<undef> に設定されている場合(ファイル吸い込みモードと呼ばれます)
48895771でファイルが空の場合、
48905772最初は C<''> を返し、次は C<undef> を返します。
48915773
48925774=begin original
48935775
48945776Ordinarily you must assign the returned value to a variable, but
48955777there is one situation where an automatic assignment happens. If
48965778and only if the input symbol is the only thing inside the conditional
48975779of a C<while> statement (even if disguised as a C<for(;;)> loop),
48985780the value is automatically assigned to the global variable $_,
48995781destroying whatever was there previously. (This may seem like an
49005782odd thing to you, but you'll use the construct in almost every Perl
49015783script you write.) The $_ variable is not implicitly localized.
49025784You'll have to put a C<local $_;> before the loop if you want that
49035785to happen.
49045786
49055787=end original
49065788
49075789通常は、返された値を変数に代入しなければなりませんが、自動的に
49085790代入される場合が 1 つだけあります。
49095791この入力シンボルが、while 文(C<for(;;)> の形になっていたとしても)の条件式中に
4910単独で現れた場合だけは、その値が自動的にグローバル変数 $_ に代入されます
5792単独で現れた場合だけは、その値が自動的にグローバル変数 $_ に代入されます;
49115793以前の値は破壊されます。
49125794(これは、奇妙に思えるかもしれませんが、ほとんどすべての Perl スクリプトで
49135795これが必要になることでしょう。)
49145796$_ 変数は暗黙にはローカル化されません。
49155797そうしたい場合はループの前に C<local $_;> と書く必要があります。
49165798
49175799=begin original
49185800
49195801The following lines are equivalent:
49205802
49215803=end original
49225804
49235805以下のものは、お互いに同値なものです:
49245806
49255807 while (defined($_ = <STDIN>)) { print; }
49265808 while ($_ = <STDIN>) { print; }
49275809 while (<STDIN>) { print; }
49285810 for (;<STDIN>;) { print; }
49295811 print while defined($_ = <STDIN>);
49305812 print while ($_ = <STDIN>);
49315813 print while <STDIN>;
49325814
49335815=begin original
49345816
49355817This also behaves similarly, but avoids $_ :
49365818
49375819=end original
49385820
49395821以下は同様の振る舞いをしますが、$_ を使いません:
49405822
49415823 while (my $line = <STDIN>) { print $line }
49425824
49435825=begin original
49445826
49455827In these loop constructs, the assigned value (whether assignment
49465828is automatic or explicit) is then tested to see whether it is
49475829defined. The defined test avoids problems where line has a string
49485830value that would be treated as false by Perl, for example a "" or
49495831a "0" with no trailing newline. If you really mean for such values
49505832to terminate the loop, they should be tested for explicitly:
49515833
49525834=end original
49535835
49545836これらのループ構造の中で、代入された値は (代入が自動か明示的かに関わりなく)
49555837定義されているかどうかを見るためにテストされます。
49565838定義テストは、行が Perl にとって偽となる文字列値を持っているかどうかの
4957問題を避けます例えば newline のついていない "" や "0" です。
5839問題を避けます; 例えば newline のついていない "" や "0" です。
49585840もし本当にこのような値でループを終了させたいときは、
49595841以下のように明示的にテストするべきです:
49605842
49615843 while (($_ = <STDIN>) ne '0') { ... }
49625844 while (<STDIN>) { last unless $_; ... }
49635845
49645846=begin original
49655847
4966In other boolean contexts, C<< <I<filehandle>> >> without an
5848In other boolean contexts, C<< <filehandle> >> without an
4967explicit C<defined> test or comparison elicit a warning if the
5849explicit C<defined> test or comparison elicits a warning if the
49685850C<use warnings> pragma or the B<-w>
49695851command-line switch (the C<$^W> variable) is in effect.
49705852
49715853=end original
49725854
49735855その他の真偽値コンテキストでは、明示的な C<defined> や比較なしに
4974C<< <I<filehandle>> >> を使うと、C<use warnings> プラグマや
5856C<< <filehandle> >> を使うと、C<use warnings> プラグマや
49755857B<-w> コマンドラインスイッチ (C<$^W> 変数) が有効なときには、
49765858警告を発生させます。
49775859
49785860=begin original
49795861
49805862The filehandles STDIN, STDOUT, and STDERR are predefined. (The
49815863filehandles C<stdin>, C<stdout>, and C<stderr> will also work except
49825864in packages, where they would be interpreted as local identifiers
49835865rather than global.) Additional filehandles may be created with
49845866the open() function, amongst others. See L<perlopentut> and
49855867L<perlfunc/open> for details on this.
49865868X<stdin> X<stdout> X<sterr>
49875869
49885870=end original
49895871
49905872STDIN、STDOUT、STDERR というファイルハンドルは、あらかじめ定義されています。
49915873(C<stdin>、C<stdout>、C<stderr> というファイルハンドルも、
49925874ローカルな名前でこれらのグローバルな名前が見えなくなっている
49935875パッケージを除けば、使用することができます。)
49945876その他のファイルハンドルは、open() 関数などで作ることができます。
49955877これに関する詳細については L<perlopentut> と L<perlfunc/open> を
49965878参照して下さい。
49975879X<stdin> X<stdout> X<sterr>
49985880
49995881=begin original
50005882
50015883If a <FILEHANDLE> is used in a context that is looking for
50025884a list, a list comprising all input lines is returned, one line per
50035885list element. It's easy to grow to a rather large data space this
50045886way, so use with care.
50055887
50065888=end original
50075889
50085890<FILEHANDLE> がリストを必要とするコンテキストで用いられると、
500958911 要素に 1 行の入力行すべてからなるリストが返されます。
50105892これを使うと簡単にかなり大きなデータになってしまいますので、
50115893注意を要します。
50125894
50135895=begin original
50145896
50155897<FILEHANDLE> may also be spelled C<readline(*FILEHANDLE)>.
50165898See L<perlfunc/readline>.
50175899
50185900=end original
50195901
50205902<FILEHANDLE> は C<readline(*FILEHANDLE)> とも書けます。
50215903L<perlfunc/readline> を参照して下さい。
50225904
50235905=begin original
50245906
50255907The null filehandle <> is special: it can be used to emulate the
50265908behavior of B<sed> and B<awk>. Input from <> comes either from
50275909standard input, or from each file listed on the command line. Here's
50285910how it works: the first time <> is evaluated, the @ARGV array is
50295911checked, and if it is empty, C<$ARGV[0]> is set to "-", which when opened
50305912gives you standard input. The @ARGV array is then processed as a list
50315913of filenames. The loop
50325914
50335915=end original
50345916
50355917ヌルファイルハンドル <> は特別で、B<sed> や B<awk> の動作を
50365918エミュレートするために使われます。
50375919<> からの入力は、標準入力からか、コマンドライン上に並べられた個々の
50385920ファイルから行なわれます。
5039動作の概要は、以下のようになります
5921動作の概要は、以下のようになります: 最初に <> が評価されると、配列
5040最初に <> が評価されると、配列 @ARGV が調べられ、空であれば、
5922@ARGV が調べられ、空であれば、C<$ARGV[0]> に "-"を設定します。
5041C<$ARGV[0]> に "-"を設定します。
50425923これは、open されるとき標準入力となります。
50435924その後、配列 @ARGV がファイル名のリストとして処理されます。
50445925
50455926 while (<>) {
50465927 ... # code for each line
50475928 }
50485929
50495930=begin original
50505931
50515932is equivalent to the following Perl-like pseudo code:
50525933
50535934=end original
50545935
50555936は以下ののような Perl の擬似コードと等価です:
50565937
50575938 unshift(@ARGV, '-') unless @ARGV;
50585939 while ($ARGV = shift) {
50595940 open(ARGV, $ARGV);
50605941 while (<ARGV>) {
50615942 ... # code for each line
50625943 }
50635944 }
50645945
50655946=begin original
50665947
50675948except that it isn't so cumbersome to say, and will actually work.
50685949It really does shift the @ARGV array and put the current filename
50695950into the $ARGV variable. It also uses filehandle I<ARGV>
5070internally--<> is just a synonym for <ARGV>, which
5951internally. <> is just a synonym for <ARGV>, which
50715952is magical. (The pseudo code above doesn't work because it treats
50725953<ARGV> as non-magical.)
50735954
50745955=end original
50755956
50765957但し、わずらわしく書かなくても、動作します。
50775958実際に @ARGV を shift しますし、その時点のファイル名を変数 $ARGV に
50785959入れています。
5079また、内部的にファイルハンドル ARGV を使っていて、<> はマジカルな
5960また、内部的にファイルハンドル ARGV を使っています。
5080<ARGV> の同義語となっています。
5961<> は <ARGV> の同義語で、マジカルです。
50815962(上記の擬似コードは、<ARGV> を通常のものとして扱っているので、
50825963うまく動作しません。)
50835964
50845965=begin original
50855966
50865967Since the null filehandle uses the two argument form of L<perlfunc/open>
50875968it interprets special characters, so if you have a script like this:
50885969
50895970=end original
50905971
50915972空ファイルハンドルは 2 引数の L<perlfunc/open> を使った特別な文字列なので、
50925973もし以下のようなスクリプトを書いて:
50935974
50945975 while (<>) {
50955976 print;
50965977 }
50975978
50985979=begin original
50995980
51005981and call it with C<perl dangerous.pl 'rm -rfv *|'>, it actually opens a
51015982pipe, executes the C<rm> command and reads C<rm>'s output from that pipe.
51025983If you want all items in C<@ARGV> to be interpreted as file names, you
51035984can use the module C<ARGV::readonly> from CPAN.
51045985
51055986=end original
51065987
51075988これを C<perl dangerous.pl 'rm -rfv *|'> として呼び出すと、実際には
51085989パイプを開き、C<rm> コマンドを実行して、 C<rm> の出力をパイプから読みます。
51095990もし C<@ARGV> の全ての要素をファイル名として解釈させたいなら、
51105991CPAN にある C<ARGV::readonly> モジュールが使えます。
51115992
51125993=begin original
51135994
51145995You can modify @ARGV before the first <> as long as the array ends up
51155996containing the list of filenames you really want. Line numbers (C<$.>)
51165997continue as though the input were one big happy file. See the example
51175998in L<perlfunc/eof> for how to reset line numbers on each file.
51185999
51196000=end original
51206001
51216002最終的に、@ARGV に扱いたいと思っているファイル名が含まれるのであれば、
51226003最初に <> を評価する前に @ARGV を変更することも可能です。
51236004行番号 (C<$.>) は、入力ファイルがあたかも 1 つの大きなファイルで
51246005あるかのように、続けてカウントされます。
51256006個々のファイルごとにリセットする方法は、L<perlfunc/eof> の例を
51266007参照してください。
51276008
51286009=begin original
51296010
51306011If you want to set @ARGV to your own list of files, go right ahead.
51316012This sets @ARGV to all plain text files if no @ARGV was given:
51326013
51336014=end original
51346015
51356016最初から @ARGV に自分でファイルのリストを設定してもかまいません。
51366017以下は @ARGV が与えられなかったときに全てのテキストファイルを
51376018@ARGV に設定します。
51386019
51396020 @ARGV = grep { -f && -T } glob('*') unless @ARGV;
51406021
51416022=begin original
51426023
51436024You can even set them to pipe commands. For example, this automatically
51446025filters compressed arguments through B<gzip>:
51456026
51466027=end original
51476028
51486029ここにパイプコマンドを置くことも出来ます。
51496030例えば、以下は圧縮された引数を自動的に B<gzip> のフィルタに通します:
51506031
51516032 @ARGV = map { /\.(gz|Z)$/ ? "gzip -dc < $_ |" : $_ } @ARGV;
51526033
51536034=begin original
51546035
51556036If you want to pass switches into your script, you can use one of the
51566037Getopts modules or put a loop on the front like this:
51576038
51586039=end original
51596040
51606041スクリプトにスイッチを渡したいのであれば、Getopts モジュールを
51616042使うこともできますし、実際の処理の前にのようなループを置くこともできます。
51626043
51636044 while ($_ = $ARGV[0], /^-/) {
51646045 shift;
51656046 last if /^--$/;
51666047 if (/^-D(.*)/) { $debug = $1 }
51676048 if (/^-v/) { $verbose++ }
51686049 # ... # other switches
51696050 }
51706051
51716052 while (<>) {
51726053 # ... # code for each line
51736054 }
51746055
51756056=begin original
51766057
51776058The <> symbol will return C<undef> for end-of-file only once.
51786059If you call it again after this, it will assume you are processing another
51796060@ARGV list, and if you haven't set @ARGV, will read input from STDIN.
51806061
51816062=end original
51826063
51836064シンボル <> がファイルの最後で C<undef> を返すのは一度きりです。
51846065そのあとでもう一度呼び出すと、新たに別の @ARGV を処理するものとみなされ、
51856066その時に @ARGV を設定しなおしていないと、STDIN からの入力を
51866067読み込むことになります。
51876068
51886069=begin original
51896070
51906071If what the angle brackets contain is a simple scalar variable (e.g.,
51916072<$foo>), then that variable contains the name of the
51926073filehandle to input from, or its typeglob, or a reference to the
51936074same. For example:
51946075
51956076=end original
51966077
51976078山括弧の中の文字列が (<$foo> のような) 単純スカラ変数であれば、
51986079その変数が入力を行なうファイルハンドルの名前そのもの、名前への型グロブ、
51996080名前へのリファレンスのいずれかを示しているとみなされます。
6081例えば:
52006082
52016083 $fh = \*STDIN;
52026084 $line = <$fh>;
52036085
52046086=begin original
52056087
52066088If what's within the angle brackets is neither a filehandle nor a simple
52076089scalar variable containing a filehandle name, typeglob, or typeglob
52086090reference, it is interpreted as a filename pattern to be globbed, and
52096091either a list of filenames or the next filename in the list is returned,
52106092depending on context. This distinction is determined on syntactic
52116093grounds alone. That means C<< <$x> >> is always a readline() from
52126094an indirect handle, but C<< <$hash{key}> >> is always a glob().
52136095That's because $x is a simple scalar variable, but C<$hash{key}> is
52146096not--it's a hash element. Even C<< <$x > >> (note the extra space)
52156097is treated as C<glob("$x ")>, not C<readline($x)>.
52166098
52176099=end original
52186100
52196101山括弧の中の文字列がファイルハンドルでもファイルハンドル名、型グロブ、
52206102型グロブリファレンスのいずれかが入った単純スカラ変数でもなければ、
52216103グロブを行なうファイル名のパターンと解釈され、コンテキストによって
52226104ファイル名のリストか、そのリストの次のファイル名が返されます。
52236105この区別は単に構文的に行われます。
52246106C<< <$x> >> は常に間接ハンドルから readline() しますが、
52256107C<< <$hash{key}> >> は常に glob() します。
52266108$x は単純スカラー変数ですが、C<$hash{key}> は違う(ハッシュ要素)からです。
52276109C<< <$x > >> (余分な空白に注意) ですら C<readline($x)> ではなく
52286110C<glob("$x ")> として扱われます。
52296111
52306112=begin original
52316113
52326114One level of double-quote interpretation is done first, but you can't
52336115say C<< <$foo> >> because that's an indirect filehandle as explained
52346116in the previous paragraph. (In older versions of Perl, programmers
52356117would insert curly brackets to force interpretation as a filename glob:
52366118C<< <${foo}> >>. These days, it's considered cleaner to call the
52376119internal function directly as C<glob($foo)>, which is probably the right
52386120way to have done it in the first place.) For example:
52396121
52406122=end original
52416123
52426124まず、1 段階だけダブルクォート展開が行なわれますが、前の段落に書いた
52436125間接ファイルハンドルと同じになる、C<< <$foo> >> のようには書けません。
52446126(Perl の古いバージョンでは、ファイル名グロブと解釈させるために
52456127C<< <${foo}> >> のように中括弧を入れていました。
5246最近ではより明確にするために、C<glob($foo)> と内部関数を
6128最近ではより明確にするために、C<glob($foo)> と内部関数を呼ぶことも
5247呼ぶこともできます。
6129できます; おそらく、まず、こちらの方で試すのが正解でしょう)
5248おそらく、まず、こちらの方で試すのが正解でしょう。)
6130例えば:
5249例:
52506131
52516132 while (<*.c>) {
52526133 chmod 0644, $_;
52536134 }
52546135
52556136=begin original
52566137
52576138is roughly equivalent to:
52586139
52596140=end original
52606141
52616142はだいたい以下と等価です:
52626143
52636144 open(FOO, "echo *.c | tr -s ' \t\r\f' '\\012\\012\\012\\012'|");
52646145 while (<FOO>) {
52656146 chomp;
52666147 chmod 0644, $_;
52676148 }
52686149
52696150=begin original
52706151
52716152except that the globbing is actually done internally using the standard
52726153C<File::Glob> extension. Of course, the shortest way to do the above is:
52736154
52746155=end original
52756156
52766157但し実際のグロブは内部的に標準の C<File::Glob> モジュールを使います。
52776158もちろん、もっと簡単に以下のように書けます:
52786159
52796160 chmod 0644, <*.c>;
52806161
52816162=begin original
52826163
52836164A (file)glob evaluates its (embedded) argument only when it is
52846165starting a new list. All values must be read before it will start
52856166over. In list context, this isn't important because you automatically
52866167get them all anyway. However, in scalar context the operator returns
52876168the next value each time it's called, or C<undef> when the list has
52886169run out. As with filehandle reads, an automatic C<defined> is
52896170generated when the glob occurs in the test part of a C<while>,
52906171because legal glob returns (e.g. a file called F<0>) would otherwise
52916172terminate the loop. Again, C<undef> is returned only once. So if
52926173you're expecting a single value from a glob, it is much better to
52936174say
52946175
52956176=end original
52966177
52976178(ファイル)グロブは新しいリストを開始するときにだけ(組み込みの)引数を
52986179評価します。
52996180全ての値は開始する前に読み込んでいなければなりません。
53006181これはリストコンテキストでは、とにかく自動的に全てを取り込むので
53016182重要ではありません。
5302しかし、スカラコンテキストではこの演算子は呼び出された時の
6183しかし、スカラコンテキストではこの演算子は呼び出された時の
53036184次の値か、リストがなくなったときには C<undef> を返します。
53046185ファイルハンドルを読み込む場合は、グロブが C<while> の条件部にある場合は
5305自動的な C<defined> が生成されます
6186自動的な C<defined> が生成されます;
53066187なぜならそうしないと、本来の glob の返り値 (F<0> というファイル) が
53076188ループを終了させるからです。
53086189ここでも、C<undef> は一度だけ返されます。
53096190従って、もしグロブから一つの値だけを想定している場合、
53106191以下のように書くことが:
53116192
53126193 ($file) = <blurch*>;
53136194
53146195=begin original
53156196
53166197than
53176198
53186199=end original
53196200
53206201以下のように書くよりはるかに良いです:
53216202
53226203 $file = <blurch*>;
53236204
53246205=begin original
53256206
53266207because the latter will alternate between returning a filename and
53276208returning false.
53286209
53296210=end original
53306211
53316212なぜなら後者はファイル名を返す場合と偽を返す場合があるからです。
53326213
53336214=begin original
53346215
53356216If you're trying to do variable interpolation, it's definitely better
53366217to use the glob() function, because the older notation can cause people
53376218to become confused with the indirect filehandle notation.
53386219
53396220=end original
53406221
5341変数変換に挑戦する場合、明らかに glob() 関数を使う方が良いです
6222変数変換に挑戦する場合、明らかに glob() 関数を使う方が良いです;
53426223なぜなら古い表記は間接ファイルハンドル表記と混乱するかも知れないからです。
53436224
53446225 @files = glob("$dir/*.[ch]");
53456226 @files = glob($files[$i]);
53466227
53476228=head2 Constant Folding
53486229X<constant folding> X<folding>
53496230
53506231(定数の畳み込み)
53516232
53526233=begin original
53536234
53546235Like C, Perl does a certain amount of expression evaluation at
53556236compile time whenever it determines that all arguments to an
53566237operator are static and have no side effects. In particular, string
53576238concatenation happens at compile time between literals that don't do
53586239variable substitution. Backslash interpolation also happens at
53596240compile time. You can say
53606241
53616242=end original
53626243
53636244C と同じように Perl でも、演算子に対するすべての引数がスタティックで、
53646245副作用がないと判断できれば、コンパイル時に式の評価を行なってしまいます。
53656246特に、変数置換の無いリテラルどうしの文字列連結はコンパイル時に行なわれます。
53666247バックスラッシュの解釈もコンパイル時に行なわれます。
6248以下のように書けて、
53676249
53686250 'Now is the time for all' . "\n" .
53696251 'good men to come to.'
53706252
53716253=begin original
53726254
53736255and this all reduces to one string internally. Likewise, if
53746256you say
53756257
53766258=end original
53776259
5378と書いても、内部的に 1 つの文字列になります。同様に
6260内部的に 1 つの文字列になります。同様に
53796261
53806262 foreach $file (@filenames) {
53816263 if (-s $file > 5 + 100 * 2**16) { }
53826264 }
53836265
53846266=begin original
53856267
53866268the compiler will precompute the number which that expression
53876269represents so that the interpreter won't have to.
53886270
53896271=end original
53906272
53916273と書くとコンパイラは、式が表わす数値をあらかじめ計算しますので、
53926274インタプリタで計算する必要がなくなっています。
53936275
53946276=head2 No-ops
53956277X<no-op> X<nop>
53966278
53976279(無実行)
53986280
53996281=begin original
54006282
54016283Perl doesn't officially have a no-op operator, but the bare constants
54026284C<0> and C<1> are special-cased to not produce a warning in a void
54036285context, so you can for example safely do
54046286
54056287=end original
54066288
54076289Perl は公式には無実行演算子はありませんが、裸の定数 C<0> と C<1> は
54086290特別に無効コンテキストでも警告を出さないことになっているので、
54096291例えば安全に以下のように書けます:
54106292
54116293 1 while foo();
54126294
54136295=head2 Bitwise String Operators
54146296X<operator, bitwise, string>
54156297
54166298(ビット列演算子)
54176299
54186300=begin original
54196301
54206302Bitstrings of any size may be manipulated by the bitwise operators
54216303(C<~ | & ^>).
54226304
54236305=end original
54246306
54256307任意のサイズのビット列はビット単位演算子(C<~ | & ^>)で操作できます。
54266308
54276309=begin original
54286310
54296311If the operands to a binary bitwise op are strings of different
54306312sizes, B<|> and B<^> ops act as though the shorter operand had
54316313additional zero bits on the right, while the B<&> op acts as though
54326314the longer operand were truncated to the length of the shorter.
54336315The granularity for such extension or truncation is one or more
54346316bytes.
54356317
54366318=end original
54376319
54386320二項ビット単位演算子のオペランドが異なった長さの文字列だった場合、
54396321B<|> と B<^> の演算子は短い側のオペランドの右側に追加のゼロが
5440ついているとみなします
6322ついているとみなします; 一方 B<&> 演算子は長い方のオペランドが短い方に
5441一方 B<&> 演算子は長い方のオペランドが短い方に切り詰められます。
6323切り詰められます。
54426324この拡張や短縮の粒度はバイト単位です。
54436325
54446326 # ASCII-based examples
54456327 print "j p \n" ^ " a h"; # prints "JAPH\n"
54466328 print "JA" | " ph\n"; # prints "japh\n"
54476329 print "japh\nJunk" & '_____'; # prints "JAPH\n";
54486330 print 'p N$' ^ " E<H\n"; # prints "Perl\n";
54496331
54506332=begin original
54516333
54526334If you are intending to manipulate bitstrings, be certain that
54536335you're supplying bitstrings: If an operand is a number, that will imply
54546336a B<numeric> bitwise operation. You may explicitly show which type of
54556337operation you intend by using C<""> or C<0+>, as in the examples below.
54566338
54576339=end original
54586340
54596341ビット列を操作したい場合は、確実にビット列が渡されるようにしてください:
54606342オペランドが数字の場合、B<数値> ビット単位演算を仮定します。
54616343明示的に演算の型を指定するときには、以下の例のように
54626344C<""> か C<0+> を使ってください。
54636345
6346=begin original
6347
54646348 $foo = 150 | 105; # yields 255 (0x96 | 0x69 is 0xFF)
54656349 $foo = '150' | 105; # yields 255
54666350 $foo = 150 | '105'; # yields 255
54676351 $foo = '150' | '105'; # yields string '155' (under ASCII)
54686352
6353=end original
6354
6355 $foo = 150 | 105; # 255 になる (0x96 | 0x69 は 0xFF)
6356 $foo = '150' | 105; # 255 になる
6357 $foo = 150 | '105'; # 255 になる
6358 $foo = '150' | '105'; # (ASCII では) 文字列 '155' になる
6359
6360=begin original
6361
54696362 $baz = 0+$foo & 0+$bar; # both ops explicitly numeric
54706363 $biz = "$foo" ^ "$bar"; # both ops explicitly stringy
54716364
6365=end original
6366
6367 $baz = 0+$foo & 0+$bar; # どちらのオペランドも明示的に数値
6368 $biz = "$foo" ^ "$bar"; # どちらのオペランドも明示的に文字列
6369
54726370=begin original
54736371
54746372See L<perlfunc/vec> for information on how to manipulate individual bits
54756373in a bit vector.
54766374
54776375=end original
54786376
54796377ビットベクタの個々のビットをどのように操作するかの情報については
54806378L<perlfunc/vec> を参照して下さい。
54816379
54826380=head2 Integer Arithmetic
54836381X<integer>
54846382
54856383(整数演算)
54866384
54876385=begin original
54886386
54896387By default, Perl assumes that it must do most of its arithmetic in
54906388floating point. But by saying
54916389
54926390=end original
54936391
54946392デフォルトでは、Perl は演算を浮動小数で行なわなければならないものと
54956393しています。
54966394しかし、(もしそうしたいなら)
54976395
54986396 use integer;
54996397
55006398=begin original
55016399
5502you may tell the compiler that it's okay to use integer operations
6400you may tell the compiler to use integer operations
5503(if it feels like it) from here to the end of the enclosing BLOCK.
6401(see L<integer> for a detailed explanation) from here to the end of
5504An inner BLOCK may countermand this by saying
6402the enclosing BLOCK. An inner BLOCK may countermand this by saying
55056403
55066404=end original
55076405
5508と書けば、その場所から現在の BLOCK の終わりまでは、整数演算
6406と書けば、その場所から現在の BLOCK の終わりまでは、整数演算
6407(詳しい説明は L<integer> を参照してください) を
55096408行なってよいと、コンパイラに指示することができます。
55106409内部の BLOCK で、
55116410
55126411 no integer;
55136412
55146413=begin original
55156414
55166415which lasts until the end of that BLOCK. Note that this doesn't
5517mean everything is only an integer, merely that Perl may use integer
6416mean everything is an integer, merely that Perl will use integer
5518operations if it is so inclined. For example, even under C<use
6417operations for arithmetic, comparison, and bitwise operators. For
5519integer>, if you take the C<sqrt(2)>, you'll still get C<1.4142135623731>
6418example, even under C<use integer>, if you take the C<sqrt(2)>, you'll
5520or so.
6419still get C<1.4142135623731> or so.
55216420
55226421=end original
55236422
55246423と書けば、その BLOCK の終わりまでは、指示を取り消すことになります。
5525これは全てを整数だけを使って処理することを意味するわけではないことに
6424これは全てを整数だけを使って処理することを意味するわけではなく、
5526注意してください。
6425単に Perl が算術、比較、ビット単位演算子で整数演算を
5527これは単に Perl が整数を使たい思ったとき使うかもれな
6426するとうだけであることに注意てくださ
5528というだけです。
55296427例えば、C<use integer> の指定があっても、C<sqrt(2)> とすると、
55306428C<1.4142135623731> といった結果が返ってきます。
55316429
55326430=begin original
55336431
55346432Used on numbers, the bitwise operators ("&", "|", "^", "~", "<<",
55356433and ">>") always produce integral results. (But see also
55366434L<Bitwise String Operators>.) However, C<use integer> still has meaning for
55376435them. By default, their results are interpreted as unsigned integers, but
55386436if C<use integer> is in effect, their results are interpreted
55396437as signed integers. For example, C<~0> usually evaluates to a large
55406438integral value. However, C<use integer; ~0> is C<-1> on two's-complement
55416439machines.
55426440
55436441=end original
55446442
55456443数値を使う場合、ビット単位演算子 ("&", "|", "^", "~", "<<", ">>") は
5546常に整数の結果を生成します(但し L<Bitwise String Operators> も
6444常に整数の結果を生成します
5547参照して下さい)
6445(但し L<Bitwise String Operators> も参照して下さい。)
55486446しかし、それでも C<use integer> は意味があります。
55496447デフォルトでは、これらの結果は符号なし整数として解釈されますが、
55506448C<use integer> が有効の場合は、符号付き整数として解釈されます。
55516449例えば、C<~0> は通常大きな整数の値として評価されます。
55526450しかし、C<use integer; ~0> は 2 の補数のマシンでは C<-1> になります。
55536451
55546452=head2 Floating-point Arithmetic
55556453X<floating-point> X<floating point> X<float> X<real>
55566454
55576455(浮動小数点演算)
55586456
55596457=begin original
55606458
55616459While C<use integer> provides integer-only arithmetic, there is no
55626460analogous mechanism to provide automatic rounding or truncation to a
55636461certain number of decimal places. For rounding to a certain number
55646462of digits, sprintf() or printf() is usually the easiest route.
55656463See L<perlfaq4>.
55666464
55676465=end original
55686466
55696467C<use integer> が整数演算を提供する一方、数を特定の桁で自動的に丸めたり
55706468切り捨てたりする機構はありません。
55716469数を丸めるには、sprintf() や printf() を使うのが一番簡単な方法です。
55726470L<perlfaq4> を参照して下さい。
55736471
55746472=begin original
55756473
55766474Floating-point numbers are only approximations to what a mathematician
55776475would call real numbers. There are infinitely more reals than floats,
55786476so some corners must be cut. For example:
55796477
55806478=end original
55816479
55826480浮動小数点数は数学者が実数と呼ぶものの近似でしかありません。
55836481実数は浮動小数点より無限に続くので、多少角が丸められます。
5584例:
6482えば:
55856483
55866484 printf "%.20g\n", 123456789123456789;
55876485 # produces 123456789123456784
55886486
55896487=begin original
55906488
5591Testing for exact equality of floating-point equality or inequality is
6489Testing for exact floating-point equality or inequality is not a
5592not a good idea. Here's a (relatively expensive) work-around to compare
6490good idea. Here's a (relatively expensive) work-around to compare
55936491whether two floating-point numbers are equal to a particular number of
55946492decimal places. See Knuth, volume II, for a more robust treatment of
55956493this topic.
55966494
55976495=end original
55986496
55996497浮動小数点数が等しいかどうかをちょうど同じかどうかで比較するのは
56006498いいアイデアではありません。
56016499以下に、二つの浮動小数点数が指定された桁まで等しいかどうかを
56026500比較する(比較的重い)次善の策を示します。
56036501この問題に関するより厳密な扱いについては Knuth, volume II を参照して下さい。
56046502
56056503 sub fp_equal {
56066504 my ($X, $Y, $POINTS) = @_;
56076505 my ($tX, $tY);
56086506 $tX = sprintf("%.${POINTS}g", $X);
56096507 $tY = sprintf("%.${POINTS}g", $Y);
56106508 return $tX eq $tY;
56116509 }
56126510
56136511=begin original
56146512
56156513The POSIX module (part of the standard perl distribution) implements
56166514ceil(), floor(), and other mathematical and trigonometric functions.
56176515The Math::Complex module (part of the standard perl distribution)
56186516defines mathematical functions that work on both the reals and the
56196517imaginary numbers. Math::Complex not as efficient as POSIX, but
56206518POSIX can't work with complex numbers.
56216519
56226520=end original
56236521
56246522POSIX モジュール(Perl 標準配布パッケージの一部) は ceil(), floor() 及び
56256523その他の数学関数や三角関数を実装しています。
56266524Math::Complex モジュール(Perl 標準配布パッケージの一部)は
56276525実数と虚数の両方で動作する数学関数を定義しています。
56286526Math::Complex は POSIX ほど効率的ではありませんが、
56296527POSIX は複素数は扱えません。
56306528
56316529=begin original
56326530
56336531Rounding in financial applications can have serious implications, and
56346532the rounding method used should be specified precisely. In these
56356533cases, it probably pays not to trust whichever system rounding is
56366534being used by Perl, but to instead implement the rounding function you
56376535need yourself.
56386536
56396537=end original
56406538
56416539金融アプリケーションにおける丸めは深刻な影響を与える可能性があり、
56426540使用する丸めメソッドは指定された精度で行われるべきです。
56436541このような場合、Perl が使用するシステム丸めを信用せず、
56446542代わりに自分自身で丸め関数を実装するべきです。
56456543
56466544=head2 Bigger Numbers
56476545X<number, arbitrary precision>
56486546
56496547(より大きな数)
56506548
56516549=begin original
56526550
5653The standard Math::BigInt and Math::BigFloat modules provide
6551The standard C<Math::BigInt>, C<Math::BigRat>, and C<Math::BigFloat> modules,
6552along with the C<bigint>, C<bigrat>, and C<bitfloat> pragmas, provide
56546553variable-precision arithmetic and overloaded operators, although
56556554they're currently pretty slow. At the cost of some space and
56566555considerable speed, they avoid the normal pitfalls associated with
56576556limited-precision representations.
56586557
56596558=end original
56606559
5661標準の Math::BigInt Math::BigFloat モジュールは多倍長演算を提供し、
6560標準の C<Math::BigInt>, C<Math::BigRat>, C<Math::BigFloat> モジュール
6561C<bigint>, C<bigrat>, C<bitfloat> プラグマは多倍長演算を提供し、
56626562演算子をオーバーロードしますが、これらは現在のところかなり遅いです。
56636563多少の領域とかなりの速度を犠牲にして、桁数が制限されていることによる
56646564ありがちな落とし穴を避けることができます。
56656565
5666 use Math::BigInt;
6566 use 5.010;
5667 $x = Math::BigInt->new('123456789123456789');
6567 use bigint; # easy interface to Math::BigInt
5668 print $x * $x;
6568 $x = 123456789123456789;
6569 say $x * $x;
6570 +15241578780673678515622620750190521
56696571
5670 # prints +15241578780673678515622620750190521
6572=begin original
56716573
6574Or with rationals:
6575
6576=end original
6577
6578あるいは分数を使って:
6579
6580 use 5.010;
6581 use bigrat;
6582 $a = 3/22;
6583 $b = 4/6;
6584 say "a/b is ", $a/$b;
6585 say "a*b is ", $a*$b;
6586 a/b is 9/44
6587 a*b is 1/11
6588
56726589=begin original
56736590
5674There are several modules that let you calculate with (bound only by
6591Several modules let you calculate with (bound only by memory and CPU time)
5675memory and cpu-time) unlimited or fixed precision. There are also
6592unlimited or fixed precision. There are also some non-standard modules that
5676some non-standard modules that provide faster implementations via
6593provide faster implementations via external C libraries.
5677external C libraries.
56786594
56796595=end original
56806596
56816597(メモリと CPU 時間のみに依存する)無制限か固定の精度での計算ができる
56826598モジュールがいくつかあります。
56836599さらに外部 C ライブラリを使ってより速い実装を提供する
56846600非標準のモジュールもあります。
56856601
56866602=begin original
56876603
56886604Here is a short, but incomplete summary:
56896605
56906606=end original
56916607
56926608以下は短いですが不完全なリストです。
56936609
56946610=begin original
56956611
5696 Math::Fraction big, unlimited fractions like 9973 / 12967
6612 Math::Fraction big, unlimited fractions like 9973 / 12967
5697 Math::String treat string sequences like numbers
6613 Math::String treat string sequences like numbers
5698 Math::FixedPrecision calculate with a fixed precision
6614 Math::FixedPrecision calculate with a fixed precision
5699 Math::Currency for currency calculations
6615 Math::Currency for currency calculations
5700 Bit::Vector manipulate bit vectors fast (uses C)
6616 Bit::Vector manipulate bit vectors fast (uses C)
5701 Math::BigIntFast Bit::Vector wrapper for big numbers
6617 Math::BigIntFast Bit::Vector wrapper for big numbers
5702 Math::Pari provides access to the Pari C library
6618 Math::Pari provides access to the Pari C library
5703 Math::BigInteger uses an external C library
6619 Math::BigInteger uses an external C library
5704 Math::Cephes uses external Cephes C library (no big numbers)
6620 Math::Cephes uses external Cephes C library (no big numbers)
5705 Math::Cephes::Fraction fractions via the Cephes library
6621 Math::Cephes::Fraction fractions via the Cephes library
5706 Math::GMP another one using an external C library
6622 Math::GMP another one using an external C library
57076623
57086624=end original
57096625
57106626 Math::Fraction 9973 / 12967 のような、大きくて無制限の分数
57116627 Math::String 文字列を数値のように扱う
57126628 Math::FixedPrecision 固定精度で計算する
57136629 Math::Currency 通貨の計算用
57146630 Bit::Vector (C を使って)ビットベクタを速く操作する
57156631 Math::BigIntFast 大きな数のための Bit::Vector のラッパー
57166632 Math::Pari Pari C ライブラリへのアクセスを提供する
57176633 Math::BigInteger 外部 C ライブラリを使う
57186634 Math::Cephes 外部の Cephes C を使う(大きな数はなし)
57196635 Math::Cephes::Fraction Cephes ライブラリを使った分数
57206636 Math::GMP これも外部 C ライブラリを使う
57216637
57226638=begin original
57236639
57246640Choose wisely.
57256641
57266642=end original
57276643
57286644うまく選んでください。
57296645
57306646=cut
57316647
57326648=begin meta
57336649
57346650Translate: 吉村 寿人 <JAE00534@niftyserve.or.jp> (5.000)
57356651Update: Kentaro Shirakata <argrath@ub32.org> (5.6.1-)
57366652Status: completed
57376653
57386654=end meta