handlename's blog

コード片など

perltidyをPerl Best Practiceに即した形式にしてくれるパラメータ

perltidy、便利ですね。なにも考えなくても(見た目が)きれいなコードになおしてくれます。

で、最近読んでるPerlベストプラクティスに、こんな設定例が書いてありました。

perltidy
-q
-l=78  # Max line width is 78 cols
-i=4    #  indent level is 4 cols
-ci=4    # Continuation indent is 4 cols
-vt=2    # Maximal vertical tightness
-cti=0   # No extra indentation for closing brackets
-pt=1    # Medium parenthesis tightness
-bt=1    # Medium brace tightness
-sbt=1   # Medium square brace tightness
-bbt=1   # Medium block brace tightness
-nsfs    # No space for semicolons
-nolq    # Don't outdent long quoted strings
-wbb="% + * / x != == >= <= =~ !~ < > | & **= += *= &= <<= &&= -=
      /= |= >>= ||= .= %= ^= x="
         # Break before all operators

(オライリー・ジャパン Perlベストプラクティス / Damian Conway著, pp37-38)

いちいち設定するのも面倒だなー、と思いながらperldoc perltidyを見てたら、そのものずばりなオプションがありました。

-pbp, --perl-best-practices
    -pbp is an abbreviation for the parameters in the book Perl Best
    Practices by Damian Conway:

        -l=78 -i=4 -ci=4 -st -se -vt=2 -cti=0 -pt=1 -bt=1 -sbt=1 -bbt=1 -nsfs -nolq
        -wbb="% + - * / x != == >= <= =~ !~ < > &#9130; & =
              **= += *= &= <<= &&= -= /= &#9130;= >>= &#9130;&#9130;= //= .= %= ^= x="

    Note that the -st and -se flags make perltidy act as a filter on
    one file only.  These can be overridden with -nst and -nse if nec‐
    essary.

(perldoc perltidy)

つまり、

$ perltidy -pbp <filename>

とすればPerlベストプラクティスに則った形に整形してくれるわけですね。

普段emacsを使っているのでこんな関数を定義しています。

(defun perltidy-region ()
  "Run perltidy based on Perl Best Practice  on the current region."
  (interactive "r")
  (save-excursion
    (shell-command-on-region (point) (mark) "perltidy -q -pbp" nil t)))

折り返しの部分など、たまに手を入れたくなることもありますが、たいていの場合は整形したい部分をリージョン選択して perltidy-region を実行すればいい感じになります。