5.22.1

名前

perltrap - Perl traps for the unwary

perltrap - 不注意による Perl の罠

説明

The biggest trap of all is forgetting to use warnings or use the -w switch; see warnings and perlrun. The second biggest trap is not making your entire program runnable under use strict. The third biggest trap is not reading the list of changes in this version of Perl; see perldelta.

最も大きな罠とは、use warnings あるいは -w スイッチを使うのを 忘れてしまうということです; warningsperlrun を 参照してください。 二番目に大きな罠とは、あなたのプログラム全体を use strict の元で 実行しないということです。 三番目の罠は、このバージョンの Perl での変更点を読まないということです; perldelta を参照してください。

awk の罠

Accustomed awk users should take special note of the following:

awk に慣れた方は、以下のようなことに特に注意してください:

  • A Perl program executes only once, not once for each input line. You can do an implicit loop with -n or -p.

    Perl のプログラムは、1 度だけ実行されます; 入力行毎ではありません。 -n-p を使って暗黙のループを使えます。

  • The English module, loaded via

    Englishモジュールを

        use English;

    allows you to refer to special variables (like $/) with names (like $RS), as though they were in awk; see perlvar for details.

    のようにしてロードすれば、awk でそうであったように ($/ のような)特殊変数を($RS のような)名前で参照することができます; 詳しくは perlvar を参照してください。

  • Semicolons are required after all simple statements in Perl (except at the end of a block). Newline is not a statement delimiter.

    Perl では、すべての単純文(simple statement)の末尾にセミコロンが必要です (ブロックの最後に置かれたときを除きます)。 改行は文の区切りとはなりません。

  • Curly brackets are required on ifs and whiles.

    ifwhile では中かっこが必要です。

  • Variables begin with "$", "@" or "%" in Perl.

    Perl では、変数は "$" か "@" か "%" で始まります。

  • Arrays index from 0. Likewise string positions in substr() and index().

    配列の添え字は 0 から始まります。 substr() や index() での文字列の位置も同様です。

  • You have to decide whether your array has numeric or string indices.

    配列の添え字が数値であるか、文字列であるかを決めなければなりません。

  • Hash values do not spring into existence upon mere reference.

    ハッシュ(連想配列)の値は、単に参照するだけでは存在することになりません。

  • You have to decide whether you want to use string or numeric comparisons.

    比較を文字列によって行うのか、数値によって行うのかを 決めなければなりません。

  • Reading an input line does not split it for you. You get to split it to an array yourself. And the split() operator has different arguments than awk's.

    入力を読み込むだけでは split は行われません。 配列への split は自分で行います。 また、split() 演算子の引数は awk のものと異なっています。

  • The current input line is normally in $_, not $0. It generally does not have the newline stripped. ($0 is the name of the program executed.) See perlvar.

    通常、カレント行は $0 ではなく $_ にあります。 一般的に、改行は取り除かれません。 ($0 には実行しているプログラムの名前があります)。 perlvar を参照してください。

  • $<digit> does not refer to fields--it refers to substrings matched by the last match pattern.

    $<digit> はフィールドを参照しません--これは直前に行った パターンマッチングの部分文字列を参照します。

  • The print() statement does not add field and record separators unless you set $, and $\. You can set $OFS and $ORS if you're using the English module.

    print() 文は、$,$\ に値を設定しない限りフィールド区切り子や レコード区切り子を付加しません。 English モジュールを使っていれば、$OFS や $ORS に対して 設定することもできます。

  • You must open your files before you print to them.

    ファイルに対して出力する前には、そのファイルをあらかじめオープンして おかなければなりません。

  • The range operator is "..", not comma. The comma operator works as in C.

    範囲演算子は ".." であって、カンマではありません。 カンマ演算子は C と同じような振る舞いをします。

  • The match operator is "=~", not "~". ("~" is the one's complement operator, as in C.)

    マッチ演算子は "=~" であって、"~" ではありません。 ("~" はCと同様に、1 の補数を取る演算子です。)

  • The exponentiation operator is "**", not "^". "^" is the XOR operator, as in C. (You know, one could get the feeling that awk is basically incompatible with C.)

    べき乗の演算子は "**" であって、"^" ではありません。 "^" は C と同様、XOR 演算子です。 (awk が基本的に C と非互換であることにお気付きかもしれませんね。)

  • The concatenation operator is ".", not the null string. (Using the null string would render /pat/ /pat/ unparsable, because the third slash would be interpreted as a division operator--the tokenizer is in fact slightly context sensitive for operators like "/", "?", and ">". And in fact, "." itself can be the beginning of a number.)

    連接演算子は "." であって、空文字列ではありません。 (空文字列を使ってしまうと /pat/ /pat/ が、その 3 番目のスラッシュが 除算演算子と解釈されてしまうので正しく解析できなくなります-- Perl の字句解析器は "/", "?", ">" といった演算子に対して 多少文脈依存となっています。 実際、"." 自身も数値の始まりとなる可能性もあります。)

  • The next, exit, and continue keywords work differently.

    キーワード next, exit, continue の振る舞いが異なります。

  • The following variables work differently:

    以下の変数の働きが異なります。

          Awk       Perl
          ARGC      scalar @ARGV (compare with $#ARGV)
          ARGV[0]   $0
          FILENAME  $ARGV
          FNR       $. - something
          FS        (whatever you like)
          NF        $#Fld, or some such
          NR        $.
          OFMT      $#
          OFS       $,
          ORS       $\
          RLENGTH   length($&)
          RS        $/
          RSTART    length($`)
          SUBSEP    $;
  • You cannot set $RS to a pattern, only a string.

    $RS に正規表現をセットすることはできません; できるのは文字列だけです。

  • When in doubt, run the awk construct through a2p and see what it gives you.

    妙だと思ったときには awk の構文を a2p に通して、出力されたものを 見てみましょう。

C/++ の罠

Cerebral C and C++ programmers should take note of the following:

知的な C と C++ のプログラマは以下のことに注意すべきです:

  • Curly brackets are required on if's and while's.

    ifwhile には中かっこが必要です。

  • You must use elsif rather than else if.

    else if ではなく、elsif を使わなければなりません。

  • The break and continue keywords from C become in Perl last and next, respectively. Unlike in C, these do not work within a do { } while construct. See "Loop Control" in perlsyn.

    C の breakcontinue は、Perl ではそれぞれ lastnext となります。 C とは異なり、これらは do { } while 構文では 使えません"Loop Control" in perlsyn を参照してください。

  • The switch statement is called given/when and only available in perl 5.10 or newer. See "Switch Statements" in perlsyn.

    switch 文は given/when と呼ばれ、perl 5.10 以降でのみ利用可能です。 "Switch Statements" in perlsyn を参照してください。

  • Variables begin with "$", "@" or "%" in Perl.

    Perlでは、変数は "$" か "@" か "%" で始まります。

  • Comments begin with "#", not "/*" or "//". Perl may interpret C/C++ comments as division operators, unterminated regular expressions or the defined-or operator.

    コメントの始まりは、"#" であり、"/*" や "//" ではありません。 Perl は C/C++ のコメントを除算演算子、終端していない正規表現、 定義性和演算子として解釈するかもしれません。

  • You can't take the address of anything, although a similar operator in Perl is the backslash, which creates a reference.

    なにかのアドレスを得ることはできません; Perl には似たような演算子である バックスラッシュがありますが、これはリファレンスを生成します。

  • ARGV must be capitalized. $ARGV[0] is C's argv[1], and argv[0] ends up in $0.

    ARGV は大文字でなければなりません。 $ARGV[0] が C での argv[1] に相当し、argv[0] にあたるものは $0 です。

  • System calls such as link(), unlink(), rename(), etc. return nonzero for success, not 0. (system(), however, returns zero for success.)

    link(), unlink(), rename() などのシステムコールは、成功時に 0 ではなく非 0 の値を返します。 (但し、system() は成功時に 0 を返します。)

  • Signal handlers deal with signal names, not numbers. Use kill -l to find their names on your system.

    シグナルハンドラは、シグナル番号ではなくシグナル名を扱います。 使用できるシグナル名は、kill -l として確かめてください。

JavaScript の罠

Judicious JavaScript programmers should take note of the following:

思慮深い JavaScript プログラマは以下のことに注意すべきです:

  • In Perl, binary + is always addition. $string1 + $string2 converts both strings to numbers and then adds them. To concatenate two strings, use the . operator.

    Perl では、二項の + は常に加算です。 $string1 + $string2 は両方の文字列を数値に変換してから加算します。 二つの文字列を結合するには、. 演算子を使ってください。

  • The + unary operator doesn't do anything in Perl. It exists to avoid syntactic ambiguities.

    + 単項演算子は Perl では何もしません。 これは文法的な曖昧さを避けるために存在しています。

  • Unlike for...in, Perl's for (also spelled foreach) does not allow the left-hand side to be an arbitrary expression. It must be a variable:

    for...in と異なり、Perl の for (foreach と書くこともあります) は 左側に任意の式を置くことはできません。 これは変数でなければなりません:

       for my $variable (keys %hash) {
            ...
       }

    Furthermore, don't forget the keys in there, as foreach my $kv (%hash) {} iterates over the keys and values, and is generally not useful ($kv would be a key, then a value, and so on).

    さらに、ここで keys を忘れないでください; foreach my $kv (%hash) {} は キーと値に対して反復するので、一般的には有用ではありません ($kv はキーになり、 次に値になり、という形になります)。

  • To iterate over the indices of an array, use foreach my $i (0 .. $#array) {}. foreach my $v (@array) {} iterates over the values.

    配列のインデックスに対して反復するには、 foreach my $i (0 .. $#array) {} を使ってください。 foreach my $v (@array) {} は値に対して反復します。

  • Perl requires braces following if, while, foreach, etc.

    Perl は if, while, foreach などに引き続いて中かっこが必要です。

  • In Perl, else if is spelled elsif.

    Perl では、else ifelsif と書きます。

  • ? : has higher precedence than assignment. In JavaScript, one can write:

    ? : は代入より高い優先順位を持ちます。 JavaScript では、以下のように書けて:

        condition ? do_something() : variable = 3

    and the variable is only assigned if the condition is false. In Perl, you need parentheses:

    条件が偽の場合にのみ変数に代入されます。 Perl では、かっこが必要です:

        $condition ? do_something() : ($variable = 3);

    Or just use if.

    または単に if を使ってください。

  • Perl requires semicolons to separate statements.

    Perl は文の分割にセミコロンが必要です。

  • Variables declared with my only affect code after the declaration. You cannot write $x = 1; my $x; and expect the first assignment to affect the same variable. It will instead assign to an $x declared previously in an outer scope, or to a global variable.

    my で宣言された変数は宣言の でのみ効果を持ちます。 $x = 1; my $x; と書いて最初の代入が同じ変数に影響すると 想定することはできません。 これは外側のスコープ、あるいはグローバル変数の $x に代入されます。

    Note also that the variable is not visible until the following statement. This means that in my $x = 1 + $x the second $x refers to one declared previously.

    また、変数は次の まで有効にならないことにも注意してください。 これは、my $x = 1 + $x とすると 2 番目の $x は前に宣言されたものを 参照するということです。

  • my variables are scoped to the current block, not to the current function. If you write {my $x;} $x;, the second $x does not refer to the one declared inside the block.

    my 変数のスコープは現在の関数ではなく現在のブロックです。 {my $x;} $x; と書くと、2 番目の $x はブロックの内側で宣言された変数を 参照できません。

  • An object's members cannot be made accessible as variables. The closest Perl equivalent to with(object) { method() } is for, which can alias $_ to the object:

    オブジェクトのメンバは変数としてアクセスできません。 with(object) { method() } の Perl での一番近い等価物は for で、 これは $_ がオブジェクトへの別名となります:

        for ($object) {
            $_->method;
        }
  • The object or class on which a method is called is passed as one of the method's arguments, not as a separate this value.

    メソッドが呼び出されたオブジェクトまたはクラスは、独立した this 値ではなく メソッドの引数の一つとして渡されます。

sed の罠

Seasoned sed programmers should take note of the following:

熟練した sed プログラマは以下のことに注意すべきです:

  • A Perl program executes only once, not once for each input line. You can do an implicit loop with -n or -p.

    Perl のプログラムは、1 度だけ実行されます; 入力行毎ではありません。 -n-p を使って暗黙のループを使えます。

  • Backreferences in substitutions use "$" rather than "\".

    置換における後方参照には、"\" ではなく "$" を使います。

  • The pattern matching metacharacters "(", ")", and "|" do not have backslashes in front.

    "(", ")", "|" といったパターンマッチのメタキャラクタは、その直前に バックスラッシュを置く必要はありません。

  • The range operator is ..., rather than comma.

    範囲演算子は ... であって、カンマではありません。

shell の罠

Sharp shell programmers should take note of the following:

鋭いシェルプログラマは以下のことに注意すべきです:

  • The backtick operator does variable interpolation without regard to the presence of single quotes in the command.

    バッククォート演算子は、コマンド内にシングルクォートがあっても 変数の展開を行ないます。

  • The backtick operator does no translation of the return value, unlike csh.

    バッククォート演算子は csh とは違って、返された値を変換しません。

  • Shells (especially csh) do several levels of substitution on each command line. Perl does substitution in only certain constructs such as double quotes, backticks, angle brackets, and search patterns.

    シェル (特に csh) は、コマンドラインごとに何段階もの置換を行ないます。 Perl はダブルクォート、バッククォート、山かっこ、検索パターンといった 特定の構造でだけ置換を行ないます。

  • Shells interpret scripts a little bit at a time. Perl compiles the entire program before executing it (except for BEGIN blocks, which execute at compile time).

    シェルは一度に少しずつ解釈を行ないます。 Perl は実行前にプログラム全体をコンパイルします (コンパイル時に実行される BEGIN ブロックを除く)。

  • The arguments are available via @ARGV, not $1, $2, etc.

    引数は $1, $2 などではなく、@ARGV から得られます。

  • The environment is not automatically made available as separate scalar variables.

    環境変数は、自動的には独立したスカラ変数として利用できるようになりません。

  • The shell's test uses "=", "!=", "<" etc for string comparisons and "-eq", "-ne", "-lt" etc for numeric comparisons. This is the reverse of Perl, which uses eq, ne, lt for string comparisons, and ==, != < etc for numeric comparisons.

    シェルの test は "=", "!=", "<" などを文字列比較に使い、"-eq", "-ne", "-lt" などを数値比較に使います。 これは Perl とは逆です; Perl では eq, ne, lt を文字列比較に使い、 ==, != < などを数値比較に使います。

Perl の罠

Practicing Perl Programmers should take note of the following:

実践的な Perl プログラマは以下のことに注意すべきです:

  • Remember that many operations behave differently in a list context than they do in a scalar one. See perldata for details.

    多くの演算子がリストコンテキストとスカラコンテキストとで 振る舞いが変わることを忘れないでください。 詳しくは perldata を参照してください。

  • Avoid barewords if you can, especially all lowercase ones. You can't tell by just looking at it whether a bareword is a function or a string. By using quotes on strings and parentheses on function calls, you won't ever get them confused.

    裸の単語、特に全てが小文字のものはできる限り使わないでください。 見た目だけではその「裸の単語」が関数なのか、 文字列なのかが判断できません。 文字列にはクォートを、関数呼び出しには括弧をつければ、 迷うこともないでしょう。

  • You cannot discern from mere inspection which builtins are unary operators (like chop() and chdir()) and which are list operators (like print() and unlink()). (Unless prototyped, user-defined subroutines can only be list operators, never unary ones.) See perlop and perlsub.

    組込み関数のどれが(chop() や chdir())のような単項演算子で、 どれが(print() や unlink())のような リスト演算子であるかは見ただけではわかりません。 (プロトタイプがなければ、ユーザー定義サブルーチンは リスト演算子として のみ 定義でき、単項演算子にはできません。) perlopperlsub を参照してください。

  • People have a hard time remembering that some functions default to $_, or @ARGV, or whatever, but that others which you might expect to do not.

    いくつかの関数が $_ や @ARGV などをデフォルトにしていますが、 同じことを期待する他の関数がデフォルトになっていないことを覚えるのに、 辛いタイピングが必要でしょう。

  • The <FH> construct is not the name of the filehandle, it is a readline operation on that handle. The data read is assigned to $_ only if the file read is the sole condition in a while loop:

    <FH> 構造はファイルハンドルではなく、そのハンドルに対する行読み込みの 操作(readline operation)です。 while ループの条件式の中にこのファイル読み込みだけがあった場合には 読み込まれたデータは $_ に代入されます。

        while (<FH>)      { }
        while (defined($_ = <FH>)) { }..
        <FH>;  # data discarded!
  • Remember not to use = when you need =~; these two constructs are quite different:

    =~ が必要なところで = を使わない、ということを忘れないでください; これら二つの構造はかなり違います:

        $x =  /foo/;
        $x =~ /foo/;
  • The do {} construct isn't a real loop that you can use loop control on.

    do {} 構造は、ループ制御を行えるような本当のループではありません。

  • Use my() for local variables whenever you can get away with it (but see perlform for where you can't). Using local() actually gives a local value to a global variable, which leaves you open to unforeseen side-effects of dynamic scoping.

    ローカル変数は、my() で済むところではこれで済ませてください (使えない場所については、perlform を参照してください)。 local() を使えばグローバル変数に対するローカルな値を与えますが、 動的スコープの不慮の副作用の可能性は、そのままです。

  • If you localize an exported variable in a module, its exported value will not change. The local name becomes an alias to a new value but the external name is still an alias for the original.

    モジュールにある export された変数を局所化すると、その export された 値は変更されません。 ローカル名は新しい値の別名(alias)となりますが、 外部名は元々の値の別名のままです。

As always, if any of these are ever officially declared as bugs, they'll be fixed and removed.

いつものように、バグとして公式に宣言されたものがあれば、 それは修正されて取り除かれるでしょう。