5.34.0

名前

perlstyle - Perl style guide

perlstyle - Perl スタイルガイド

説明

Each programmer will, of course, have his or her own preferences in regards to formatting, but there are some general guidelines that will make your programs easier to read, understand, and maintain.

プログラマは、もちろん人それぞれ、フォーマットには好みがあるでしょう; しかし、いくつかのガイドラインに従うことによって、プログラムの可読性や 保守性をあげることができます。

The most important thing is to use strict and warnings in all your code or know the reason why not to. You may turn them off explicitly for particular portions of code via no warnings or no strict, and this can be limited to the specific warnings or strict features you wish to disable. The -w flag and $^W variable should not be used for this purpose since they can affect code you use but did not write, such as modules from core or CPAN.

もっとも重要なことは、あなたのコード全てで strictwarnings を使うことです; さもなければその理由を理解しておくべきです。 no warningsno strict を使用してコードの 一部だけで警告を明示的にオフにすることができ、 またこれによって無効にしたい warnings や strict の特定の機能を制限できます。 -w フラグと $^W 変数はこの目的のために使うべきではありません; これらはコアや CPAN のモジュールのような、あなたが使っているけれども 自分で書いていないコードに影響を与えるからです。

Regarding aesthetics of code lay out, about the only thing Larry cares strongly about is that the closing curly bracket of a multi-line BLOCK should line up with the keyword that started the construct. Beyond that, he has other preferences that aren't so strong:

コードレイアウトの美観に関しては、Larry が強く気にかけているのはたった一つ、 複数行の BLOCK の閉じ中かっこは、その構造を開始したキーワードと同じ位置に なくてはならないということだけです。 それは別として、そこまで強くはない彼の好みは以下の通りです:

  • 4-column indent.

    4 カラムのインデント。

  • Opening curly on same line as keyword, if possible, otherwise line up.

    可能なら、開始中かっことキーワードを同一行に; そうでなければ、開始を そろえる。

  • Space before the opening curly of a multi-line BLOCK.

    複数行 BLOCK の開始中かっこの前にスペース。

  • One-line BLOCK may be put on one line, including curlies.

    1 行の BLOCK は中かっこも含め、1 行で。

  • No space before the semicolon.

    セミコロンの前に空白なし。

  • Semicolon omitted in "short" one-line BLOCK.

    "短い" 1 行 BLOCK ではセミコロンを省略。

  • Space around most operators.

    ほとんどの演算子の前後にはスペース。

  • Space around a "complex" subscript (inside brackets).

    "複雑な"代入(ブラケット内)の前後にはスペース。

  • Blank lines between chunks that do different things.

    異なることをするチャンクの間には空行。

  • Uncuddled elses.

    else をくっつけない。

  • No space between function name and its opening parenthesis.

    関数名と開始カッコの間にはスペースなし。

  • Space after each comma.

    カンマの後ろにはスペース。

  • Long lines broken after an operator (except and and or).

    長い行は、演算子の後ろで改行する(andor を除く)。

  • Space after last parenthesis matching on current line.

    行の最後のカッコの後ろにスペース。

  • Line up corresponding items vertically.

    対応する要素の開始位置をそろえる。

  • Omit redundant punctuation as long as clarity doesn't suffer.

    冗長な表現は、わかりにくくならない限りは省略する。

Larry has his reasons for each of these things, but he doesn't claim that everyone else's mind works the same as his does.

Larry にはこれらそれぞれを好む理由がありますが、彼以外の人がこれとまったく 同じである必要はないといっています。

Here are some other more substantive style issues to think about:

他に、より重要なスタイルの問題を示します:

  • Just because you CAN do something a particular way doesn't mean that you SHOULD do it that way. Perl is designed to give you several ways to do anything, so consider picking the most readable one. For instance

    何かをある方法で できる からといって、そう すべき とは限りません。 Perl は一つのことを様々な方法でできるように設計されていますから、より 読みやすいものを選ぶように心がけてください。 たとえば、

        open(my $fh, '<', $foo) || die "Can't open $foo: $!";

    is better than

    というのは以下のものより良いです:

        die "Can't open $foo: $!" unless open(my $fh, '<', $foo);

    because the second way hides the main point of the statement in a modifier. On the other hand

    なぜなら、2 つ目では、この文の主要部が修飾子に隠れてしまっています。 逆に、

        print "Starting analysis\n" if $verbose;

    is better than

    というのは以下のものより良いです:

        $verbose && print "Starting analysis\n";

    because the main point isn't whether the user typed -v or not.

    この文の主要部は、ユーザが -v をタイプしたかどうか ではないからです。

    Similarly, just because an operator lets you assume default arguments doesn't mean that you have to make use of the defaults. The defaults are there for lazy systems programmers writing one-shot programs. If you want your program to be readable, consider supplying the argument.

    同様に、ある演算子がデフォルト引数を想定しているからといって、その デフォルトを使わなくてはならないということにはなりません。 このデフォルト値があるのは、怠惰なシステムプログラマが、一発プログラムを 書くときのためにあります。 プログラムを読みやすくするには、引数を省略しないようにしましょう。

    Along the same lines, just because you CAN omit parentheses in many places doesn't mean that you ought to:

    同様に、多くの場所でカッコを省略 できます が、以下のように 省略しすぎることは控えるべきでしょう:

        return print reverse sort num values %array;
        return print(reverse(sort num (values(%array))));

    When in doubt, parenthesize. At the very least it will let some poor schmuck bounce on the % key in vi.

    迷ったときは、カッコを書いてください。 少なくとも、間違えた部分は vi の % キーでハイライトすることができます。

    Even if you aren't in doubt, consider the mental welfare of the person who has to maintain the code after you, and who will probably put parentheses in the wrong place.

    迷っていないときも、あとでそのコードをメンテナンスする人の生活を 考えてください; 間違った個所にカッコをいれてしまうかもしれません。

  • Don't go through silly contortions to exit a loop at the top or the bottom, when Perl provides the last operator so you can exit in the middle. Just "outdent" it a little to make it more visible:

    ループの先頭や末尾で抜け出すのに、ばかげたコードをかかないでください; Perl には last 演算子があるので、途中で抜け出すことができます。 ちょっとだけ読みやすくするには "アウトデント" します:

        LINE:
            for (;;) {
                statements;
              last LINE if $foo;
                next LINE if /^#/;
                statements;
            }
  • Don't be afraid to use loop labels--they're there to enhance readability as well as to allow multilevel loop breaks. See the previous example.

    ループのラベルは積極的に使いましょう -- 可読性をあげるのと共に、多段階の ループ抜け出しもできるようになります。 先ほどの例を見てください。

  • Avoid using grep() (or map()) or `backticks` in a void context, that is, when you just throw away their return values. Those functions all have return values, so use them. Otherwise use a foreach() loop or the system() function instead.

    grep() (や map())、また `逆クォート` を無効コンテキスト、つまり 返り値を無視する文で使用しないでください。 これらの関数はすべて返り値を持っていますから、それを使用してください。 いらないのであれば、foreach() ループや system() 関数を 使用してください。

  • For portability, when using features that may not be implemented on every machine, test the construct in an eval to see if it fails. If you know what version or patchlevel a particular feature was implemented, you can test $] ($PERL_VERSION in English) to see if it will be there. The Config module will also let you interrogate values determined by the Configure program when Perl was installed.

    ポータビリティのために、すべてのマシンで実装されていないかもしれない機能を 使用する際は、それを eval で囲って、失敗するかどうかチェックしてください。 ある機能が、どのバージョンやパッチレベルで実装されているか知っている 場合には、$] (English モジュールでは、$PERL_VERSION) を チェックすることもできます。 Config モジュールを使えば、Perl インストール時の Configure プログラムに よって決定された値を調べることができます。

  • Choose mnemonic identifiers. If you can't remember what mnemonic means, you've got a problem.

    ニーモニックな識別子を選んでください。 そのニーモニックが何を意味するか思い出せなければ、問題です。

  • While short identifiers like $gotit are probably ok, use underscores to separate words in longer identifiers. It is generally easier to read $var_names_like_this than $VarNamesLikeThis, especially for non-native speakers of English. It's also a simple rule that works consistently with VAR_NAMES_LIKE_THIS.

    $gotit のような短い識別子なら ok ですが、より長い識別子の単語を 区切るにはアンダースコアを使用してください。 一般的には、とくに英語のネイティブスピーカーでない人にとっては、 $var_names_like_this の方が $VarNamesLikeThis より読みやすいです。 このルールは VAR_NAMES_LIKE_THIS についても同様に当てはまります。

    Package names are sometimes an exception to this rule. Perl informally reserves lowercase module names for "pragma" modules like integer and strict. Other modules should begin with a capital letter and use mixed case, but probably without underscores due to limitations in primitive file systems' representations of module names as files that must fit into a few sparse bytes.

    パッケージ名は、このルールの例外になることがあります。 Perl は小文字のモジュール名を、integerstrict のような"プラグマ" モジュールのために予約しています。 その他のモジュールは大文字からはじめて、小文字を混ぜて使用すべきですが、 アンダースコアは使用しません; プリミティブなファイルシステムでは、 モジュール名をファイルとして表現する際に、バイト数の制限があるためです。

  • You may find it helpful to use letter case to indicate the scope or nature of a variable. For example:

    変数のスコープや性質を表現するのに、大文字小文字を使うと便利でしょう。 たとえば:

        $ALL_CAPS_HERE   constants only (beware clashes with perl vars!)
        $Some_Caps_Here  package-wide global/static
        $no_caps_here    function scope my() or local() variables
        $ALL_CAPS_HERE   定数のみ (perl 変数との衝突に注意!)
        $Some_Caps_Here  パッケージワイドなグローバル/スタティック変数
        $no_caps_here    関数スコープの my(),local()変数

    Function and method names seem to work best as all lowercase. E.g., $obj->as_string().

    関数とメソッドの名前はすべて小文字だとベストです。 例えば、$obj->as_string()

    You can use a leading underscore to indicate that a variable or function should not be used outside the package that defined it.

    先頭にアンダースコアをつけることによって、変数や関数を定義したパッケージ外で 使用すべきでないことを示すことができます。

  • If you have a really hairy regular expression, use the /x or /xx modifiers and put in some whitespace to make it look a little less like line noise. Don't use slash as a delimiter when your regexp has slashes or backslashes.

    ほんとにごちゃごちゃな正規表現を使う場合には、/x/xx 修飾子を 使用してスペースをいれ、ごみみたいにならないようにしてください。 正規表現内にスラッシュやバックスラッシュがあるときには、デリミタに スラッシュを使わないように。

  • Use the new and and or operators to avoid having to parenthesize list operators so much, and to reduce the incidence of punctuation operators like && and ||. Call your subroutines as if they were functions or list operators to avoid excessive ampersands and parentheses.

    新しい andor 演算子を使用し、リスト演算子のカッコがたくさんに なったり、&&|| が大量発生するのを避けてください。 サブルーチンは、関数やリスト演算子であるかのように扱い、アンパサンドや カッコが大量発生するのを避けてください。

  • Use here documents instead of repeated print() statements.

    print() 文を繰り返さず、ヒアドキュメントを使用してください。

  • Line up corresponding things vertically, especially if it'd be too long to fit on one line anyway.

    対応するものの開始位置はそろえてください、とくに、1行におさまらないものに 関して。

        $IDX = $ST_MTIME;
        $IDX = $ST_ATIME       if $opt_u;
        $IDX = $ST_CTIME       if $opt_c;
        $IDX = $ST_SIZE        if $opt_s;
    
        mkdir $tmpdir, 0700 or die "can't mkdir $tmpdir: $!";
        chdir($tmpdir)      or die "can't chdir $tmpdir: $!";
        mkdir 'tmp',   0777 or die "can't mkdir $tmpdir/tmp: $!";
  • Always check the return codes of system calls. Good error messages should go to STDERR, include which program caused the problem, what the failed system call and arguments were, and (VERY IMPORTANT) should contain the standard system error message for what went wrong. Here's a simple but sufficient example:

    システムコールの返りコードはつねにチェックしてください。 良いエラーメッセージは STDERR に書き出され、問題を発生させた プログラム名や、失敗したシステムコールと引数、そして(とても重要)標準 システムエラーメッセージを含むべきです。 以下はシンプルですが、十分な例です:

        opendir(my $dh, $dir)        or die "can't opendir $dir: $!";
  • Line up your transliterations when it makes sense:

    見やすくなる場合には、tr の開始位置をそろえてください。

        tr [abc]
           [xyz];
  • Think about reusability. Why waste brainpower on a one-shot when you might want to do something like it again? Consider generalizing your code. Consider writing a module or object class. Consider making your code run cleanly with use strict and use warnings in effect. Consider giving away your code. Consider changing your whole world view. Consider... oh, never mind.

    再利用性を考慮しましょう。 同じことをあとでやるかもしれないときに、脳の力を一発のプログラムで 無駄にする必要はありますか? コードの一般化を考慮し、モジュールやオブジェクトクラスを書くことを 考慮しましょう。 コードが use strictuse warnings が有効でも きちんと動くか考慮しましょう。 コードを捨て去ることも考慮しましょう。 世界の見方を変えることを考慮しましょう。 他にも……ああ、もういいや。

  • Try to document your code and use Pod formatting in a consistent way. Here are commonly expected conventions:

    あなたのコードを文書化して、一貫した方法で Pod フォーマットを使うように 努力してください。 以下は広く想定されている慣習です:

    • use C<> for function, variable and module names (and more generally anything that can be considered part of code, like filehandles or specific values). Note that function names are considered more readable with parentheses after their name, that is function().

      関数名、変数名、モジュール名(およびより一般的には、ファイルハンドルや 特定の値のような、コードの一部と考えられるもの)には C<> を 使ってください。 関数名は、function() のように、名前の後ろにかっこを付けると より読みやすくなると考えられています。

    • use B<> for commands names like cat or grep.

      catgrep のようなコマンド名には B<> を使ってください。

    • use F<> or C<> for file names. F<> should be the only Pod code for file names, but as most Pod formatters render it as italic, Unix and Windows paths with their slashes and backslashes may be less readable, and better rendered with C<>.

      ファイル名には F<>C<> を使ってください。 F<> はファイル名のための唯一の Pod コードであるべきですが、 ほとんどの Pod フォーマッタはこれをイタリック体で表示するため、 Unix と Windows でパスに使われるスラッシュや逆スラッシュが読みにくいです; C<> はよりよく表示されます。

  • Be consistent.

    つねに一貫性を。

  • Be nice.

    つねに素敵に。