수색…


Perl :: Critic 사용하기

자신이나 팀을 위해 모범 사례를 구현하기 시작하려면 Perl :: Critic 을 시작하는 것이 가장 좋습니다. 이 모듈은 Damien Conway의 Perl Best Practices 책자를 기반으로 작성되었으며 제안 된 내용을 구현하는 데 상당히 도움이됩니다.

주 : 필자는 (그리고 Conway 자신이이 책에서 말하고있는) 이러한 제안들에 대해 언급해야한다. 나는이 책이 대부분의 경우 견고한 추론을 제공한다는 것을 알았지 만, 나는 확실히 그것들 모두에 동의하지 않는다. 기억해야 할 중요한 점은 어떤 관행을 채택하기로 하든지간에 일관성을 유지한다는 것입니다. 코드의 예측 가능성이 높을수록 유지 관리가 쉬워집니다.

perlcritic.com 에서 브라우저를 통해 Perl :: Critic을 사용해 볼 수도 있습니다.

설치

cpan Perl::Critic

그러면 기본 룰 세트와 명령 줄에서 호출 할 수있는 perlcritic 스크립트가 설치됩니다.


기본 사용법

perlcritic대한 CPAN 문서 에는 전체 문서가 포함되어 있으므로 시작하기 위해 가장 일반적인 사용 사례 만 살펴 보겠습니다. 기본 사용법은 단순히 파일에서 perlcritic을 호출하는 것입니다.

 perlcritic -1 /path/to/script.pl

perlcritic은 스크립트와 모듈 모두에서 작동합니다. -1 은 스크립트에 대해 실행하려는 룰의 심각도 레벨을 나타냅니다. Perl :: Critic이 코드를 얼마나 많이 고를 지에 해당하는 5 가지 레벨이 있습니다.

-5 가 가장 부드럽고 예기치 않은 결과를 초래할 수있는 잠재적으로 위험한 문제에 대해서만 경고합니다. -1 은 가장 잔인하며 코드 정리가 깔끔한 것처럼 작은 것에 대해서는 불평 할 것입니다. 저의 경험에 비추어 볼 때, 레벨 3에 부합하는 코드를 유지하는 것은 위험 할 수 있습니다.

기본적으로 모든 실패는 규칙이 트리거하는 이유와 심각도를 나열합니다.

perlcritic -3 --verbose 8 /path/to/script.pl

Debugging module loaded at line 16, column 1.  You've loaded Data::Dumper, which probably shouln't be loaded in production.  (Severity: 4)
Private subroutine/method '_sub_name' declared but not used at line 58, column 1.  Eliminate dead code.  (Severity: 3)
Backtick operator used at line 230, column 37.  Use IPC::Open3 instead.  (Severity: 3)
Backtick operator used at line 327, column 22.  Use IPC::Open3 instead.  (Severity: 3)

정책보기

perlcritic의 --verbose 옵션을 사용하면 어떤 규칙이 트리거되고 있는지, 왜 그 이유를 신속하게 볼 수 있습니다 :

레벨을 8로 설정하면 경고를 트리거 한 규칙이 표시됩니다.

perlcritic -3 --verbose 8 /path/to/script.pl

[Bangs::ProhibitDebuggingModules] Debugging module loaded at line 16, column 1.  (Severity: 4)
[Subroutines::ProhibitUnusedPrivateSubroutines] Private subroutine/method '_sub_name' declared but not used at line 58, column 1.  (Severity: 3)
[InputOutput::ProhibitBacktickOperators] Backtick operator used at line 230, column 37.  (Severity: 3)
[InputOutput::ProhibitBacktickOperators] Backtick operator used at line 327, column 22.  (Severity: 3)

규칙 11의 수준에는 규칙이 존재하는 구체적인 이유가 표시됩니다.

perlcritic -3 --verbose 11 /path/to/script.pl

Debugging module loaded at line 16, near 'use Data::Dumper;'.
  Bangs::ProhibitDebuggingModules (Severity: 4)
    This policy prohibits loading common debugging modules like the
    Data::Dumper manpage.

    While such modules are incredibly useful during development and
    debugging, they should probably not be loaded in production use. If this
    policy is violated, it probably means you forgot to remove a `use
    Data::Dumper;' line that you had added when you were debugging.
Private subroutine/method '_svn_revisions_differ' declared but not used at line 58, near 'sub _sub_name {'.
  Subroutines::ProhibitUnusedPrivateSubroutines (Severity: 3)
    By convention Perl authors (like authors in many other languages)
    indicate private methods and variables by inserting a leading underscore
    before the identifier. This policy catches such subroutines which are
    not used in the file which declares them.

    This module defines a 'use' of a subroutine as a subroutine or method
    call to it (other than from inside the subroutine itself), a reference
    to it (i.e. `my $foo = \&_foo'), a `goto' to it outside the subroutine
    itself (i.e. `goto &_foo'), or the use of the subroutine's name as an
    even-numbered argument to `use overload'.
Backtick operator used at line 230, near 'my $filesystem_diff = join q{}, `diff $trunk_checkout $staging_checkout`;'.
  InputOutput::ProhibitBacktickOperators (Severity: 3)
    Backticks are super-convenient, especially for CGI programs, but I find
    that they make a lot of noise by filling up STDERR with messages when
    they fail. I think its better to use IPC::Open3 to trap all the output
    and let the application decide what to do with it.

        use IPC::Open3 'open3';
        $SIG{CHLD} = 'IGNORE';

        @output = `some_command`;                      #not ok

        my ($writer, $reader, $err);
        open3($writer, $reader, $err, 'some_command'); #ok;
        @output = <$reader>;  #Output here
        @errors = <$err>;     #Errors here, instead of the console
Backtick operator used at line 327, near 'my $output = `$cmd`;'.
  InputOutput::ProhibitBacktickOperators (Severity: 3)
    Backticks are super-convenient, especially for CGI programs, but I find
    that they make a lot of noise by filling up STDERR with messages when
    they fail. I think its better to use IPC::Open3 to trap all the output
    and let the application decide what to do with it.

        use IPC::Open3 'open3';
        $SIG{CHLD} = 'IGNORE';

        @output = `some_command`;                      #not ok

        my ($writer, $reader, $err);
        open3($writer, $reader, $err, 'some_command'); #ok;
        @output = <$reader>;  #Output here
        @errors = <$err>;     #Errors here, instead of the console

코드 무시

Perl :: Critic 정책을 준수 할 수없는 경우가 있습니다. 이 경우 Perl :: Critic이 무시할 수 있도록 특별한 주석 ( " ## critic () 사용 "및 " ## no critic ")을 코드 주위에 포함 할 수 있습니다. 괄호 안에 무시할 규칙을 추가하기 만하면됩니다 (배수는 쉼표로 구분할 수 있음).

##no critic qw(InputOutput::ProhibitBacktickOperator)
my $filesystem_diff = join q{}, `diff $trunk_checkout $staging_checkout`;
## use critic

전체 코드 블록을 래핑해야합니다. 또는 비평가가 ignore 문을 인식하지 못할 수 있습니다.

## no critic (Subroutines::ProhibitExcessComplexity)
sub no_time_to_refactor_this {
    ...
}
## use critic

문서 수준에서 실행되는 특정 정책이 있으므로이 방법으로 면제 할 수는 없습니다. 그러나, 그들은 끌 수 있습니다 ...


영구 예외 만들기

##를 사용하여 critic ()을 사용하는 것은 좋지만 코딩 표준을 채택하기 시작할 때 특정 규칙에 영구적 인 예외를 적용하려고 할 것입니다. .perlcriticrc 구성 파일을 작성하여이 작업을 수행 할 수 있습니다.

이 파일을 통해 실행할 정책뿐만 아니라 실행 방법을 사용자 정의 할 수 있습니다. 홈 디렉토리에 파일을 넣는 것만 큼 간단합니다 (Linux에서는 Windows에서 동일한 위치에 있는지 확실하지 않음). 또는 --profile 옵션을 사용하여 명령을 실행할 때 config 파일을 지정할 수 있습니다.

perlcritic -1 --profile=/path/to/.perlcriticrc /path/to/script.pl

다시 perlcritic CPAN 페이지 에는 이러한 옵션의 전체 목록이 있습니다. 내 자신의 구성 파일에서 몇 가지 예제를 나열합니다 :

기본 설정 적용 :

#very very harsh
severity = 1
color-severity-medium = bold yellow
color-severity-low = yellow
color-severity-lowest = bold blue

규칙 사용 안 함 (정책 이름 앞의 대시 참고) :

# do not require version control numbers
[-Miscellanea::RequireRcsKeywords]

# pod spelling is too over-zealous, disabling
[-Documentation::PodSpelling]

규칙 수정하기 :

# do not require checking for print failure ( false positives for printing to stdout, not filehandle )
[InputOutput::RequireCheckedSyscalls]
    functions = open close

# Allow specific unused subroutines for moose builders
[Subroutines::ProhibitUnusedPrivateSubroutines]
private_name_regex = _(?!build_)\w+

결론

제대로 활용 된 Perl :: Critic은 여러분이 사용하는 모범 사례 정책이 무엇이든 상관없이 팀이 코딩을 일관되고 쉽게 유지할 수 있도록 도와주는 귀중한 도구입니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow