1 ##############################################################################
2 # $URL: http://perlcritic.tigris.org/svn/perlcritic/trunk/Perl-Critic/lib/Perl/Critic/DEVELOPER.pod $
3 # $Date: 2008-07-03 10:19:10 -0500 (Thu, 03 Jul 2008) $
6 ##############################################################################
10 =for stopwords lookup RequireBlockGrep
14 Perl::Critic::DEVELOPER - How to make new Perl::Critic::Policy modules.
19 For developers who want to create custom coding standards, the
20 following tells how to create a Policy module for L<Perl::Critic>.
21 Although the Perl::Critic distribution already includes a number of
22 Policies based on Damian Conway's book I<Perl Best Practices> (which
23 will be referred to via "I<PBP>" from here on), Perl::Critic is not
24 limited to his guidelines and can be used to enforce any practice,
25 preference, or style that you want to follow. You can even write
26 Policies to enforce contradictory guidelines. All you need to do is
27 write a corresponding L<Perl::Critic::Policy> subclass, which may
28 require as little as 10 lines of code.
33 The heart of Perl::Critic is L<PPI>, a parser and lexer for Perl. PPI
34 transforms Perl source code into a Document Object Model (DOM). Each
35 token in the document is represented by a PPI class, such as
36 L<PPI::Token::Operator> or L<PPI::Token::Word>, and then organized
37 into structure classes, like L<PPI::Statement::Expression> and
38 L<PPI::Structure::Subroutine>. The root node of the hierarchy is the
41 The L<Perl::Critic> engine traverses each node in the L<PPI::Document>
42 tree and invokes each of the L<Perl::Critic::Policy> subclasses at the
43 appropriate node. The Policy can inspect the node, look at the
44 surrounding nodes, and do whatever else it wants. If the Policy
45 decides that that a coding standard has been violated, it returns one
46 or more L<Perl::Critic::Violation> objects. If there are no
47 violations, then the Policy returns nothing.
49 Policies are usually written based on existing policies, so let's look
50 at one to see how it works. The F<RequireBlockGrep.pm> Policy is
51 relatively simple and demonstrates most of the important issues. The
52 goal of this Policy is to enforce that every call to C<grep> uses a
53 block for the first argument and not an expression. The reasons for
54 this Policy are discussed in detail in I<PBP>.
59 First, the Policy module needs to have a name. Perl::Critic uses
60 L<Module::Pluggable> to automatically discover all modules in the
61 C<Perl::Critic::Policy> namespace. Also, we've adopted the convention
62 of grouping Policies into directories according to the chapters of
63 I<PBP>. Since the goal of this Policy is to enforce the use of block
64 arguments to C<grep> and it comes from the "Builtin Functions" chapter
66 C<"Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep">.
68 package Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep;
70 Next, we set some pragmas and load the modules that we'll need. All
71 Policy modules inherit from the L<Perl::Critic::Policy> class, which
72 provides no-op implementations of the basic methods. Our job is to
73 override these methods to make them do something useful.
75 Technically, C<use strict> and C<use warnings> are optional, but we
76 don't want Perl::Critic to be a hypocrite, now do we?
83 use Perl::Critic::Utils qw{ :severities :classification :ppi };
84 use base 'Perl::Critic::Policy';
86 our $VERSION = '1.05';
88 Next, we'll declare a description and explanation for this Policy.
89 The description is always just a string that basically says "this is
90 what's wrong." The explanation can be either a string with further
91 details, or a reference to an array of integers that correspond to
92 page numbers in I<PBP>. We make them read-only because they never
94 L<Perl::Critic::ValuesAndExpressions::ProhibitConstantPragma> for why
95 we don't C<use constant>.)
97 Readonly::Scalar my $DESC => q{Expression form of "grep"};
98 Readonly::Scalar my $EXPL => [ 169 ];
100 Most policies don't need to override the C<initialize_if_enabled()>
101 method provided by L<Perl::Critic::Policy>. However, if your Policy
102 is configurable via F<.perlcriticrc>, you should implement a
103 C<supported_parameters()> method and need to implement
104 C<initialize_if_enabled()> to examine the C<$config> values. Since
105 this Policy isn't configurable, we'll declare that by providing an
106 implementation of C<supported_parameters()> that returns an empty
109 sub supported_parameters { return () }
111 Next, we define the C<default_severity()> method, which must return an
112 integer indicating the severity of violating this Policy. Severity
113 values range from 1 to 5, where 5 is the "most severe." In general,
114 level 5 is reserved for things that are frequently misused and/or
115 cause bugs. Level 1 is for things that are highly subjective or
116 purely cosmetic. The L<Perl::Critic::Utils> package exports several
117 severity constants that you can use here via the C<:severities> tag.
119 sub default_severity { return $SEVERITY_HIGH }
121 Likewise, the C<default_themes()> method returns a list of theme
122 names. Themes are intended to be named groups of Policies. All
123 Policies that ship with Perl::Critic have a C<"core"> theme. Since
124 use of C<grep> without blocks often leads to bugs, we include a
125 C<"bugs"> theme. And since this Policy comes directly from I<PBP>,
126 this Policy should be a member of the C<"pbp"> theme.
128 sub default_themes { return qw( core bugs pbp ) }
130 As a Policy author, you can assign any themes you want to the Policy.
131 If you're publishing a suite of custom Policies, we suggest that you
132 create a unique theme that covers all the Policies in the
133 distribution. That way, users can easily enable or disable all of
134 your policies at once. For example, Policies in the
135 L<Perl::Critic::More> distribution all have a C<"more"> theme.
137 Next, we indicate what elements of the code this Policy will analyze,
138 like statements or variables or conditionals or POD. These elements
139 are specified as PPI classes such as L<PPI::Statement>,
140 L<PPI::Token::Symbol>, L<PPI::Structure::Conditional> or
141 L<PPI::Token::Pod> respectively. The applies_to() method returns a
142 list of PPI package names. (You can get that list of available
143 package names via C<perldoc PPI>.) As Perl::Critic traverses the
144 document, it will call the C<violates()> method from this module
145 whenever it encounters one of the PPI types that are given here. In
146 this case, we just want to test calls to C<grep>. Since the token
147 "grep" is a L<PPI::Token::Word>, we return that package name from the
148 C<applies_to()> method.
150 sub applies_to { return 'PPI::Token::Word' }
152 If your Policy needs to analyze several different types of elements,
153 the C<applies_to> method may return the name of several PPI packages.
154 If your Policy needs to examine the file as a whole, then the
155 C<applies_to> method should return L<PPI::Document>. Since there is
156 only one PPI::Document element, your Policy would only be invoked once
159 Now comes the interesting part. The C<violates()> method does all the
160 work. It is always called with 2 arguments: a reference to the
161 current PPI element that Perl::Critic is traversing, and a reference
162 to the entire PPI document. [And since this is an object method, there
163 will be an additional argument that is a reference to this object
164 (C<$self>), but you already knew that!] Since this Policy does not
165 need access to the document as a whole, we ignore the last parameter
166 by assigning to C<undef>.
169 my ( $self, $elem, undef ) = @_;
171 The violates() method then often performs some tests to make sure we
172 have the right "type" of element. In our example, we know that the
173 element will be a L<PPI::Token::Word> because that's what we declared
174 back in the C<applies_to()> method. However, we didn't specify
175 exactly which "word" we were looking for. Evaluating a PPI element in
176 a string context returns the literal form of the code. (You can also
177 use the c<content()> method.) So we make sure that this
178 PPI::Token::Word is, in fact, "grep". If it's not, then we don't'
179 need to bother examining it.
181 return if $elem ne 'grep';
183 The C<PPI::Token::Word> class is also used for barewords and methods
184 called on object references. It is possible for someone to declare a
185 bareword hash key as C<<%hash = ( grep => 'foo' )>>. We don't want to
186 test those types of elements because they don't represent function
187 calls to C<grep>. So we use one of handy utility functions from
188 L<Perl::Critic::Utils> to make sure that this "grep" is actually in
189 the right context. (The C<is_function_call()> subroutine is brought
190 in via the C<:classification> tag.)
192 return if ! is_function_call($elem);
194 Now that we know this element is a call to the C<grep> function, we
195 can look at the nearby elements to see what kind of arguments are
196 being passed to it. In the following paragraphs, we discuss how to do
197 this manually in order to explore L<PPI>; after that, we'll show how
198 this Policy actually uses facilities provided by
199 L<Perl::Critic::Utils> to get this done.
201 Every PPI element is linked to its siblings, parent, and children (if
202 it has any). Since those siblings could just be whitespace, we use
203 the C<snext_sibling()> to get the next code-sibling (the "s" in
204 C<snext_sibling> stands for "significant").
206 my $sib = $elem->snext_sibling() or return;
208 In Perl, the parenthesis around argument lists are usually optional,
209 and PPI packs the elements into a L<PPI::Structure::List> object when
210 parentheses are used. So if the sibling is a PPI::Structure::List, we
211 pull out the first (significant) child of that list. This child will
212 be the first argument to C<grep>. If parentheses were not used, then
213 the sibling itself is the first argument.
215 my $arg = $sib->isa('PPI::Structure::List') ? $sib->schild(0) : $sib;
217 In actuality, this sort of function argument lookup is common, so
218 there is a L<Perl::Critic::Utils/"first_arg"> subroutine available via
219 the C<:ppi> tag. So we use that instead.
221 my $arg = first_arg($elem);
223 Finally, we now have a reference to the first argument to C<grep>. If
224 that argument is a block (i.e. something in curly braces), then it
225 will be a L<PPI::Structure::Block>, in which case our Policy is
226 satisfied and we just return nothing.
229 return if $arg->isa('PPI::Structure::Block');
231 But if it is not a L<PPI::Structure::Block>, then we know that this
232 call to C<grep> must be using the expression form, and that violates
233 our Policy. So we create and return a new L<Perl::Critic::Violation>
234 object via the L<Perl::Critic::Policy/"violation"> method, passing in
235 the description, explanation, and a reference to the PPI element that
236 caused the violation. And that's all there is to it!
238 return $self->violation( $DESC, $EXPL, $elem );
243 One last thing -- people are going to need to understand what is wrong
244 with the code when your Policy finds a problem. It isn't reasonable
245 to include all the details in your violation description or
246 explanation. So please include a DESCRIPTION section in the POD for
247 your Policy. It should succinctly describe the behavior and
248 motivation for your Policy and include a few examples of both good and
249 bad code. Here's an example:
255 Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep
260 The expression forms of C<grep> and C<map> are awkward and hard to read.
261 Use the block forms instead.
263 @matches = grep /pattern/, @list; #not ok
264 @matches = grep { /pattern/ } @list; #ok
266 @mapped = map transform($_), @list; #not ok
267 @mapped = map { transform($_) } @list; #ok
271 When your policy has a section like this, users can invoke
272 L<perlcritic> with a C<--verbose> parameter of C<10> or C<11> to see
273 it along with the rest of the output for violations of your policy.
276 =head1 MAKING YOUR POLICY CONFIGURABLE
278 L<Perl::Critic> takes care of gathering configuration information for
279 your Policy, from whatever source the user specifies. (See
280 L<Perl::Critic/"CONFIGURATION"> for the details of how a user specifies
281 the values you're going to receive.) What your Policy ends up
282 receiving for the value of a parameter is a string with leading and
283 trailing whitespace removed. By default, you will need to handle
284 conversion of that string to a useful form yourself. However, if you
285 provide some metadata about your parameters, the parameter handling
286 will be taken care of for you. (Additionally, tools that deal with
287 Policies themselves can use this information to enhance their
288 functionality. See the L<perlcritic> C<--profile-proto> option for an
292 L<Perl::Critic::Policy::ControlStructures::ProhibitCascadingIfElse>
293 for a simple example of a configurable Policy and
294 L<Perl::Critic::Policy::Documentation::RequirePodSections> for a more
297 =head2 Do It All Yourself
299 The C<initialize_if_enabled()> method for a Policy receives one
300 argument: an instance of L<Perl::Critic::PolicyConfig>. This method
301 is only called if the user's configuration has enabled the policy. It
302 returns a boolean stating whether the Policy should continue to be
303 enabled. Generally, the only reason to return C<$FALSE> is when some
304 external requirement is missing. For example,
305 L<Perl::Critic::Policy::CodeLayout::RequireTidyCode> disables itself
306 if L<Perl::Tidy> is not installed.
308 A basic, do-nothing implementation of C<initialize_if_enabled()> would
311 use Perl::Critic::Utils qw< :booleans >;
315 sub initialize_if_enabled {
316 my ( $self, $config ) = @_;
321 As stated above, what you get in C<$config> are trimmed strings. For
322 example, if the user's F<.perlcritic> contains
329 then C<$config> will contain the equivalent of
334 selections => '2 78 92',
337 To make this available to the C<violates()> method, the values are
338 usually put into C<$self> under the name of the configuration item
339 prefixed with an underscore. E.g.
341 sub initialize_if_enabled {
342 my ( $self, $config ) = @_;
344 $self->{_foo} = $config->get{foo};
345 $self->{_factor} = $config->get{factor};
346 $self->{_selections} = $config->get{selections};
351 Often, you'll want to convert the configuration values into something
352 more useful. In this example, C<selections> is supposed to be a list
353 of integers. L<Perl::Critic::Utils> contains a number of functions
354 that can help you with this. Assuming that C<violates()> wants to
355 have C<selections> as an array, you'll want to have something like
358 use Perl::Critic::Utils qw{ :booleans :characters :data_conversion };
360 sub initialize_if_enabled {
361 my ( $self, $config ) = @_;
363 $self->{_foo} = $config->get{foo};
364 $self->{_factor} = $config->get{factor};
366 my $selections = $config->get{selections};
367 $selections = defined $selections ? $selections : $EMPTY_STRING;
368 $self->{_selections} = [ words_from_string($selections) ];
373 Since C<selections> contains numbers, it may be desirable to change
374 the assignment to look like
376 $self->{_selections} = [ map { $_ + 0 } words_from_string($selections) ];
378 If C<violates()> needs to quickly determine whether a particular value
379 is in C<selections>, you would want to use a hash instead of an array,
382 $self->{_selections} = { hashify( words_from_string($selections) ) };
384 For an example of a Policy that has some simple, but non-standard
385 configuration handling, see
386 L<Perl::Critic::Policy::CodeLayout::RequireTidyCode>.
389 =head2 Note On Constructors
391 It used to be the case that Policies handled configuration by
392 implementing a constructor. However, there was no requirement to call
393 the base constructor; as long as the Policy ended up being a blessed
394 hash reference, everything was fine. Unfortunately, this meant that
395 Policies would be loaded and their prerequisites would be C<use>d,
396 even if the Policy wasn't enabled, slowing things down. Also, this
397 severely restricted the core of L<Perl::Critic>'s ability to enhance
398 things. Use of constructors is deprecated and is incompatible with
399 C<supported_parameters()> metadata below. Kindly use
400 C<initialize_if_enabled()>, instead, to do any sort of set up that you
405 =head2 Providing Basic Configuration Information Via C<supported_parameters()>
407 As minimum for a well behaved Policy, you should implement
408 C<supported_parameters()> in order to tell the rest of C<Perl::Critic>
409 what configuration values the Policy looks for, even if it is only to say
410 that the Policy is not configurable. In the simple form, this
411 function returns a list of the names of the parameters the Policy
412 supports. So, for an non-configurable Policy, as in the
413 C<RequireBlockGrep> example above, this looked like
415 sub supported_parameters { return () }
417 For the example being used in the C<initialize_if_enabled()> section
420 sub supported_parameters { return qw< foo factor selections >; }
422 Given this information, C<Perl::Critic> can tell the user when they
423 have specified a parameter for a Policy which isn't valid, e.g. when
424 they've misspelled the name of the parameter, and can emit the
425 parameter as part of a F<.perlcritic> prototype.
427 You can provide even more information about your Policy's
428 configuration by giving each parameter a description and a string
429 representation of the default value for the parameter. You do this by
430 having the values in the list returned by C<supported_parameters()> be
431 hash references instead of strings, with keys of C<name>,
432 C<description>, and C<default_string>. For example,
434 sub supported_parameters {
437 name => 'allowed_values',
439 'Individual and ranges of values to allow, and/or "all_integers".',
440 default_string => '0 1 2',
443 name => 'allowed_types',
444 description => 'Kind of literals to allow.',
445 default_string => 'Float',
450 Note that use of constructors is
451 L<incompatible|/"Note On Constructors"> with specifying parameters in
455 =head2 Using C<supported_parameters()> to Get It Done For You
457 The C<supported_parameters()> discussion above showed how you could
458 help others with your Policy, but didn't do anything to make your life
459 as a Policy author easier; you still need to implement
460 C<initialize_if_enabled()> to access any configuration that the user
461 has specified. To have the configuration automatically handled for
462 you, you need to declare how your parameters act by specifying a value
463 for their C<behavior>. For example, the following declares that a
464 parameter allows the user to choose from five specific values and that
465 the user can select any combination of them:
467 sub supported_parameters {
470 name => 'allowed_types',
471 description => 'Kind of literals to allow.',
472 default_string => 'Float',
473 behavior => 'enumeration',
474 enumeration_values => [ qw{ Binary Exp Float Hex Octal } ],
475 enumeration_allow_multiple_values => 1,
480 When you specify a behavior, parsing and validation of the
481 user-specified and default values is done for you and your
482 C<violates()> method can retrieve the value under the key of the
483 parameter name prefixed with an underscore, e.g., for the above
484 declaration, the parsed and validated value can be accessed via
485 C<<$self->{_allowed_types}>>.
487 The behaviors provide additional functionality to C<Perl::Critic>; for
488 more on this, see L<Perl::Critic::PolicyParameter> and
489 L<Perl::Critic::PolicyParameter::Behavior>.
491 The following discusses each of the supported behaviors and the
492 options they support. For the full details of a behavior, see the
493 documentation for the implementing class.
498 Implemented in L<Perl::Critic::PolicyParameter::Behavior::String>.
500 The most basic of behaviors, the value of the parameter will be stored
501 in the Policy as a string.
503 This behavior is not configurable.
505 =head4 C<supported_parameters()> example
507 sub supported_parameters {
511 description => 'An example string.',
512 default_string => 'blah blah blah',
513 behavior => 'string',
519 =head4 Access example
522 my ($self, $element, $document) = @_;
525 my $string = $self->{_a_string};
532 Implemented in L<Perl::Critic::PolicyParameter::Behavior::Boolean>.
534 The value of the parameter will be either L<Perl::Critic::Utils/$TRUE>
535 or L<Perl::Critic::Utils/$FALSE>.
537 This behavior is not configurable.
539 =head4 C<supported_parameters()> example
541 sub supported_parameters {
545 description => 'An example boolean.',
546 default_string => '1',
547 behavior => 'boolean',
553 =head4 Access example
556 my ($self, $element, $document) = @_;
559 my $is_whatever = $self->{_a_boolean};
569 Implemented in L<Perl::Critic::PolicyParameter::Behavior::Integer>.
571 The value is validated against C<m/ \A [-+]? [1-9] [\d_]* \z /xms>
572 (with an special check for "0"). Notice that this means that
573 underscores are allowed in input values as with Perl numeric literals.
575 This takes two options, C<integer_minimum> and
576 C<integer_maximum>, which specify endpoints of an inclusive range to
577 restrict the value to. Either, neither, or both may be specified.
579 =head4 C<supported_parameters()> example
581 sub supported_parameters {
584 name => 'an_integer',
585 description => 'An example integer.',
586 default_string => '5',
587 behavior => 'integer',
588 integer_minimum => 0,
589 integer_maximum => 10,
595 =head4 Access example
598 my ($self, $element, $document) = @_;
601 my $integer = $self->{_an_integer};
602 if ($integer > $TURNING_POINT) {
611 Implemented in L<Perl::Critic::PolicyParameter::Behavior::StringList>.
613 The values will be derived by splitting the input string on blanks.
614 (See L<Perl::Critic::Utils/"words_from_string">.) The parameter will
615 be stored as a reference to a hash, with the values being the keys.
617 This takes one optional option, C<always_present_values>, of a
618 reference to an array of strings that will always be included in the
619 parameter value, e.g. if the value of this option is
620 C<[ qw{ a b c } ]> and the user specifies a value of C<'c d e'>, then
621 the value of the parameter will contain C<'a'>, C<'b'>, C<'c'>,
624 =head4 C<supported_parameters()> example
626 sub supported_parameters {
629 name => 'a_string_list',
630 description => 'An example list.',
631 default_string => 'red pink blue',
632 behavior => 'string list',
633 always_present_values => [ qw{ green purple} ],
639 =head4 Access example
642 my ($self, $element, $document) = @_;
645 my $list = $self->{_a_string_list};
646 my @list = keys %{$list};
648 return if not $list->{ $element->content() };
655 Implemented in L<Perl::Critic::PolicyParameter::Behavior::Enumeration>.
657 The values will be derived by splitting the input string on blanks.
658 (See L<Perl::Critic::Utils/"words_from_string">.) Depending upon the
659 value of the C<enumeration_allow_multiple_values> option, the
660 parameter will be stored as a string or a reference to a hash, with
661 the values being the keys.
663 This behavior takes one required option and one optional one. A value
664 for C<enumeration_values> of a reference to an array of valid strings
665 is required. A true value can be specified for
666 C<enumeration_allow_multiple_values> to allow the user to pick more
667 than one value, but this defaults to false.
669 =head4 C<supported_parameters()> example
671 use Perl::Critic::Utils qw{ :characters };
673 sub supported_parameters {
676 name => 'a_single_valued_enumeration',
678 'An example enumeration that can only have a single value.',
679 default_string => $EMPTY,
680 behavior => 'enumeration',
681 enumeration_values => [ qw{ block statement pod operator } ],
682 enumeration_allow_multiple_values => 0,
685 name => 'a_multi_valued_enumeration',
687 'An example enumeration that can have multiple values.',
688 default_string => 'fe',
689 behavior => 'enumeration',
690 enumeration_values => [ qw{ fe fi fo fum } ],
691 enumeration_allow_multiple_values => 1,
697 =head4 Access example
700 my ($self, $element, $document) = @_;
703 my $single_value = $self->{_a_single_valued_enumeration};
705 my $multi_value = $self->{_a_multi_valued_enumeration};
706 if ( $multi_value->{fum} ) {
713 =head2 Using a Custom Parser
715 If none of the behaviors does exactly what you want it to, you can
716 provide your own parser for a parameter. The reason for doing this as
717 opposed to using an implementation of C<initialize_if_enabled()> is
718 that it allows you to use a behavior to provide its extra
719 functionality and it provides a means for a C<Perl::Critic>
720 configuration program, e.g. an IDE that integrates C<Perl::Critic>, to
721 validate your parameter as the user modifies its value.
723 The way you declare that you have a custom parser is to include a
724 reference to it in the parameter specification with the C<parser> key.
727 sub supported_parameters {
731 description => 'A file for to read a list of values from.',
732 default_string => undef,
733 behavior => 'string',
734 parser => \&_parse_file_name,
739 A parser is a method on a subclass of L<Perl::Critic::Policy> that
740 takes two parameters: the L<Perl::Critic::PolicyParameter> that is
741 being specified and the value string provided by the user. The method
742 is responsible for dealing with any default value and for saving the
743 parsed value for later use by the C<violates()> method.
745 An example parser (without enough error handling) for the above
748 use File::Slurp qw< slurp >;
750 use Perl::Critic::Exception::Configuration::Option::Policy::ParameterValue
751 qw{ throw_policy_value };
753 sub _parse_file_name {
754 my ($self, $parameter, $config_string) = @_;
758 if ($config_string) {
759 if (not -r $config_string) {
761 policy => $self->get_short_name(),
762 option_name => $parameter->get_name(),
763 option_value => $config_string,
764 message_suffix => 'is not readable.';
767 @thingies = slurp $config_string;
770 $self->{_thingies} = \@thingies;
775 Note that, if the value for the parameter is not valid, an instance of
776 L<Perl::Critic::Exception::Configuration::Option::Policy::ParameterValue>
777 is thrown. This allows C<Perl::Critic> to include that problem along
778 with any other problems found with the user's configuration in a
779 single error message.
782 =head2 Using Both C<supported_parameters()> and C<initialize_if_enabled()>
784 There are cases where a Policy needs additional initialization beyond
785 configuration or where the way it acts depends upon the combination of
786 multiple parameters. In such situations, you will need to create an
787 implementation of C<initialize_if_enabled()>. If you want to take
788 advantage of the supplied parameter handling from within
789 implementation of C<initialize_if_enabled()>, note that the
790 information from C<supported_parameters()> will already have been
791 used, with user-supplied parameter values validated and placed into
792 the Policy by the time C<initialize_if_enabled()> has been called. It
793 is likely that you will not need to refer the contents of the
794 C<$config> parameter; just pull the information you need out of
795 C<$self>. In fact, any value for the parameter values will be gone.
799 =head2 Summary of permitted hash keys in C<supported_parameters()>.
807 =item - "name" (mandatory)
809 =item - "description" (optional)
811 =item - "behavior" (optional)
829 =item - "default_string" (optional)
831 A string representation of the default value of the parameter.
833 =item - "parser" (optional)
835 A code ref to a custom parser for the parameter.
843 =item - "enumeration_values" (mandatory)
845 A mandatory reference to an array of strings.
847 =item - "enumeration_allow_multiple_values" (optional)
849 Boolean indicating whether or not the user is restricted to a single
858 =item - "integer_minimum" (optional)
860 Minimum allowed value, inclusive.
862 =item - "integer_maximum" (optional)
864 Maximum allowed value, inclusive.
872 =item - "list_always_present_values" (optional)
874 A reference to an array of values that should always be included in
875 the value of the parameter.
880 =head1 ADDITIONAL FEATURES
882 =head2 C<default_maximum_violations_per_document()>
884 Certain problems that a Policy detects can be endemic to a particular
885 file; if there's one violation, there's likely to be many. A good
887 L<Perl::Critic::Policy::TestingAndDebugging::RequireUseStrict>; if
888 there's one line before L<use strict>, there's a good chance that the
889 entire file is missing L<use strict>. In such cases, it's not much
890 help to the user to report every single violation. If you've got such
891 a policy, you should override
892 L<default_maximum_violations_per_document()|Perl::Critic::Policy/"default_maximum_violations_per_document()">
893 method to provide a limit. The user can override this value with a
894 value for "maximum_violations_per_document" in their F<.perlcriticrc>.
896 See the source code for
897 L<Perl::Critic::Policy::ValuesAndExpressions::ProhibitMagicNumbers>
898 and L<Perl::Critic::Policy::TestingAndDebugging::RequireUseWarnings>
902 =head1 DISTRIBUTING YOUR POLICIES
904 =head2 Create a Distribution
906 You need to come up with a name for your set of policies. Sets of
907 add-on policies are generally named C<Perl::Critic::I<something>>,
908 e.g. L<Perl::Critic::More>.
910 The module representing the distribution will not actually have any
911 functionality; it's just documentation and a name for users to use
912 when installing via L<CPAN>/L<CPANPLUS>. The important part is that
913 this will include a list of the included policies, with descriptions
916 A typical implementation will look like:
918 package Perl::Critic::Example;
923 our $VERSION = '1.000000';
925 1; # Magic true value required at end of module
931 Perl::Critic::Example - Policies for Perl::Critic that act as an example.
935 This module has no functionality, but instead contains documentation
936 for this distribution and acts as a means of pulling other modules
937 into a bundle. All of the Policy modules contained herein will have
938 an "AFFILIATION" section announcing their participation in this
944 Some L<Perl::Critic> policies that will help you keep your code
950 The included policies are:
954 =item L<Perl::Critic::Policy::Documentation::Example>
956 Complains about some example documentation issues. [Severity: 3]
959 =item L<Perl::Critic::Policy::Variables::Example>
961 All modules must have at least one variable. [Severity: 3]
967 =head1 CONFIGURATION AND ENVIRONMENT
969 All policies included are in the "example" theme. See the
970 L<Perl::Critic> documentation for how to make use of this.
975 Users can choose which policies to enable using themes. You should
976 implement C<default_themes()> so that users can take advantage of
977 this. In particular, you should use a theme named after your
978 distribution in all your policies; this should match the value listed
979 in the C<CONFIGURATION AND ENVIRONMENT> POD section as shown above.
981 default_themes { return qw< example math > }
983 If you're looking for ideas of what themes to do, have a look at the
984 output of C<perlcritic --list-themes>.
991 Since all policies have to go somewhere under the
992 C<Perl::Critic::Policy::> namespace, it isn't always clear what
993 distribution a policy came from when browsing through their
994 documentation. For this reason, you should include an C<AFFILIATION>
995 section in the POD for all of your policies that state where the
996 policy comes from. For example:
1000 This policy is part of L<Perl::Critic::Example>.
1003 =head3 CONFIGURATION
1005 In order to make it clear what can be done with a policy, you should
1006 always include a C<CONFIGURATION> section in your POD, even if it's
1009 =head1 CONFIGURATION
1011 This Policy is not configurable except for the standard options.
1016 When you're trying to figure out what L<PPI> is going to hand you for
1017 a chunk of code, there is a F<tools/ppidump> program in the
1018 L<Perl::Critic> distribution that will help you. For example, when
1019 developing the above RequireBlockGrep example, you might want to try
1021 tools/ppidump '@matches = grep /pattern/, @list;'
1025 tools/ppidump '@matches = grep { /pattern/ } @list;'
1027 to see the differences between the two cases.
1032 This is part of L<Perl::Critic> version 1.088.
1037 Jeffrey Ryan Thalhammer <thaljef@cpan.org>
1042 Copyright (c) 2005-2008 Jeffrey Ryan Thalhammer. All rights reserved.
1044 This program is free software; you can redistribute it and/or modify
1045 it under the same terms as Perl itself. The full text of this license
1046 can be found in the LICENSE file included with this module.
1050 ##############################################################################
1053 # cperl-indent-level: 4
1055 # indent-tabs-mode: nil
1056 # c-indentation-style: bsd
1058 # ex: set ts=8 sts=4 sw=4 tw=70 ft=pod expandtab shiftround :