1Perl::Critic::DEVELOPERU(s3e)r Contributed Perl DocumentaPteiroln::Critic::DEVELOPER(3)
2
3
4
6 Perl::Critic::DEVELOPER - How to make new Perl::Critic::Policy modules.
7
9 For developers who want to create custom coding standards, the
10 following tells how to create a Policy module for Perl::Critic.
11 Although the Perl::Critic distribution already includes a number of
12 Policies based on Damian Conway's book Perl Best Practices (which will
13 be referred to via "PBP" from here on), Perl::Critic is not limited to
14 his guidelines and can be used to enforce any practice, preference, or
15 style that you want to follow. You can even write Policies to enforce
16 contradictory guidelines. All you need to do is write a corresponding
17 Perl::Critic::Policy subclass, which may require as little as 10 lines
18 of code.
19
21 The heart of Perl::Critic is PPI, a parser and lexer for Perl. PPI
22 transforms Perl source code into a Document Object Model (DOM). Each
23 token in the document is represented by a PPI class, such as
24 PPI::Token::Operator or PPI::Token::Word, and then organized into
25 structure classes, like PPI::Statement::Expression and
26 PPI::Structure::Subroutine. The root node of the hierarchy is the
27 PPI::Document.
28
29 The Perl::Critic engine traverses each node in the PPI::Document tree
30 and invokes each of the Perl::Critic::Policy subclasses at the
31 appropriate node. The Policy can inspect the node, look at the
32 surrounding nodes, and do whatever else it wants. If the Policy
33 decides that that a coding standard has been violated, it returns one
34 or more Perl::Critic::Violation objects. If there are no violations,
35 then the Policy returns nothing.
36
37 Policies are usually written based on existing policies, so let's look
38 at one to see how it works. The RequireBlockGrep.pm Policy is
39 relatively simple and demonstrates most of the important issues. The
40 goal of this Policy is to enforce that every call to "grep" uses a
41 block for the first argument and not an expression. The reasons for
42 this Policy are discussed in detail in PBP.
43
45 First, the Policy module needs to have a name. Perl::Critic uses
46 Module::Pluggable to automatically discover all modules in the
47 "Perl::Critic::Policy" namespace. Also, we've adopted the convention
48 of grouping Policies into directories according to the chapters of PBP.
49 Since the goal of this Policy is to enforce the use of block arguments
50 to "grep" and it comes from the "Builtin Functions" chapter of PBP, we
51 call it "Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep".
52
53 package Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep;
54
55 Next, we set some pragmas and load the modules that we'll need. All
56 Policy modules inherit from the Perl::Critic::Policy class, which
57 provides no-op implementations of the basic methods. Our job is to
58 override these methods to make them do something useful.
59
60 Technically, "use strict" and "use warnings" are optional, but we don't
61 want Perl::Critic to be a hypocrite, now do we?
62
63 use strict;
64 use warnings;
65
66 use Readonly;
67
68 use Perl::Critic::Utils qw{ :severities :classification :ppi };
69 use base 'Perl::Critic::Policy';
70
71 our $VERSION = '1.05';
72
73 Next, we'll declare a description and explanation for this Policy. The
74 description is always just a string that basically says "this is what's
75 wrong." The explanation can be either a string with further details,
76 or a reference to an array of integers that correspond to page numbers
77 in PBP. We make them read-only because they never change. (See
78 Perl::Critic::ValuesAndExpressions::ProhibitConstantPragma for why we
79 don't "use constant".)
80
81 Readonly::Scalar my $DESC => q{Expression form of "grep"};
82 Readonly::Scalar my $EXPL => [ 169 ];
83
84 Most policies don't need to override the "initialize_if_enabled()"
85 method provided by Perl::Critic::Policy. However, if your Policy is
86 configurable via .perlcriticrc, you should implement a
87 "supported_parameters()" method and need to implement
88 "initialize_if_enabled()" to examine the $config values. Since this
89 Policy isn't configurable, we'll declare that by providing an
90 implementation of "supported_parameters()" that returns an empty list.
91
92 sub supported_parameters { return () }
93
94 Next, we define the "default_severity()" method, which must return an
95 integer indicating the severity of violating this Policy. Severity
96 values range from 1 to 5, where 5 is the "most severe." In general,
97 level 5 is reserved for things that are frequently misused and/or cause
98 bugs. Level 1 is for things that are highly subjective or purely
99 cosmetic. The Perl::Critic::Utils package exports several severity
100 constants that you can use here via the ":severities" tag.
101
102 sub default_severity { return $SEVERITY_HIGH }
103
104 Likewise, the "default_themes()" method returns a list of theme names.
105 Themes are intended to be named groups of Policies. All Policies that
106 ship with Perl::Critic have a "core" theme. Since use of "grep"
107 without blocks often leads to bugs, we include a "bugs" theme. And
108 since this Policy comes directly from PBP, this Policy should be a
109 member of the "pbp" theme.
110
111 sub default_themes { return qw( core bugs pbp ) }
112
113 As a Policy author, you can assign any themes you want to the Policy.
114 If you're publishing a suite of custom Policies, we suggest that you
115 create a unique theme that covers all the Policies in the distribution.
116 That way, users can easily enable or disable all of your policies at
117 once. For example, Policies in the Perl::Critic::More distribution all
118 have a "more" theme.
119
120 Next, we indicate what elements of the code this Policy will analyze,
121 like statements or variables or conditionals or POD. These elements
122 are specified as PPI classes such as PPI::Statement,
123 PPI::Token::Symbol, PPI::Structure::Conditional or PPI::Token::Pod
124 respectively. The "applies_to()" method returns a list of PPI package
125 names. (You can get that list of available package names via "perldoc
126 PPI".) As Perl::Critic traverses the document, it will call the
127 "violates()" method from this module whenever it encounters one of the
128 PPI types that are given here. In this case, we just want to test
129 calls to "grep". Since the token "grep" is a PPI::Token::Word, we
130 return that package name from the "applies_to()" method.
131
132 sub applies_to { return 'PPI::Token::Word' }
133
134 If your Policy needs to analyze several different types of elements,
135 the "applies_to" method may return the name of several PPI packages.
136 If your Policy needs to examine the file as a whole, then the
137 "applies_to" method should return PPI::Document. Since there is only
138 one PPI::Document element, your Policy would only be invoked once per
139 file.
140
141 Now comes the interesting part. The "violates()" method does all the
142 work. It is always called with 2 arguments: a reference to the current
143 PPI element that Perl::Critic is traversing, and a reference to the
144 entire PPI document. [And since this is an object method, there will be
145 an additional argument that is a reference to this object ($self), but
146 you already knew that!] Since this Policy does not need access to the
147 document as a whole, we ignore the last parameter by assigning to
148 "undef".
149
150 sub violates {
151 my ( $self, $elem, undef ) = @_;
152
153 The "violates()" method then often performs some tests to make sure we
154 have the right "type" of element. In our example, we know that the
155 element will be a PPI::Token::Word because that's what we declared back
156 in the "applies_to()" method. However, we didn't specify exactly which
157 "word" we were looking for. Evaluating a PPI element in a string
158 context returns the literal form of the code. (You can also use the
159 "content()" method.) So we make sure that this "PPI::Token::Word" is,
160 in fact, "grep". If it's not, then we don't need to bother examining
161 it.
162
163 return if $elem ne 'grep';
164
165 The "PPI::Token::Word" class is also used for barewords and methods
166 called on object references. It is possible for someone to declare a
167 bareword hash key as "%hash = ( grep => 'foo')". We don't want to test
168 those types of elements because they don't represent function calls to
169 "grep". So we use one of handy utility functions from
170 Perl::Critic::Utils to make sure that this "grep" is actually in the
171 right context. (The "is_function_call()" subroutine is brought in via
172 the ":classification" tag.)
173
174 return if ! is_function_call($elem);
175
176 Now that we know this element is a call to the "grep" function, we can
177 look at the nearby elements to see what kind of arguments are being
178 passed to it. In the following paragraphs, we discuss how to do this
179 manually in order to explore PPI; after that, we'll show how this
180 Policy actually uses facilities provided by Perl::Critic::Utils to get
181 this done.
182
183 Every PPI element is linked to its siblings, parent, and children (if
184 it has any). Since those siblings could just be whitespace, we use the
185 "snext_sibling()" to get the next code-sibling (the "s" in
186 "snext_sibling" stands for "significant").
187
188 my $sib = $elem->snext_sibling() or return;
189
190 In Perl, the parenthesis around argument lists are usually optional,
191 and PPI packs the elements into a PPI::Structure::List object when
192 parentheses are used. So if the sibling is a "PPI::Structure::List",
193 we pull out the first (significant) child of that list. This child
194 will be the first argument to "grep". If parentheses were not used,
195 then the sibling itself is the first argument.
196
197 my $arg = $sib->isa('PPI::Structure::List') ? $sib->schild(0) : $sib;
198
199 In actuality, this sort of function argument lookup is common, so there
200 is a "first_arg" in Perl::Critic::Utils subroutine available via the
201 ":ppi" tag. So we use that instead.
202
203 my $arg = first_arg($elem);
204
205 Finally, we now have a reference to the first argument to "grep". If
206 that argument is a block (i.e. something in curly braces), then it will
207 be a PPI::Structure::Block, in which case our Policy is satisfied and
208 we just return nothing.
209
210 return if !$arg;
211 return if $arg->isa('PPI::Structure::Block');
212
213 But if it is not a PPI::Structure::Block, then we know that this call
214 to "grep" must be using the expression form, and that violates our
215 Policy. So we create and return a new Perl::Critic::Violation object
216 via the "violation" in Perl::Critic::Policy method, passing in the
217 description, explanation, and a reference to the PPI element that
218 caused the violation. And that's all there is to it!
219
220 return $self->violation( $DESC, $EXPL, $elem );
221 }
222
223 1;
224
225 One last thing -- people are going to need to understand what is wrong
226 with the code when your Policy finds a problem. It isn't reasonable to
227 include all the details in your violation description or explanation.
228 So please include a DESCRIPTION section in the POD for your Policy. It
229 should succinctly describe the behavior and motivation for your Policy
230 and include a few examples of both good and bad code. Here's an
231 example:
232
233 =pod
234
235 =head1 NAME
236
237 Perl::Critic::Policy::BuiltinFunctions::RequireBlockGrep
238
239
240 =head1 DESCRIPTION
241
242 The expression forms of C<grep> and C<map> are awkward and hard to read.
243 Use the block forms instead.
244
245 @matches = grep /pattern/, @list; #not ok
246 @matches = grep { /pattern/ } @list; #ok
247
248 @mapped = map transform($_), @list; #not ok
249 @mapped = map { transform($_) } @list; #ok
250
251 =cut
252
253 When your policy has a section like this, users can invoke perlcritic
254 with a "--verbose" parameter of 10 or 11 or with a "%d" escape to see
255 it along with the rest of the output for violations of your policy.
256
258 Perl::Critic takes care of gathering configuration information for your
259 Policy, from whatever source the user specifies. (See "CONFIGURATION"
260 in Perl::Critic for the details of how a user specifies the values
261 you're going to receive.) What your Policy ends up receiving for the
262 value of a parameter is a string with leading and trailing whitespace
263 removed. By default, you will need to handle conversion of that string
264 to a useful form yourself. However, if you provide some metadata about
265 your parameters, the parameter handling will be taken care of for you.
266 (Additionally, tools that deal with Policies themselves can use this
267 information to enhance their functionality. See the perlcritic
268 "--profile-proto" option for an example.)
269
270 You can look at
271 Perl::Critic::Policy::ControlStructures::ProhibitCascadingIfElse for a
272 simple example of a configurable Policy and
273 Perl::Critic::Policy::Documentation::RequirePodSections for a more
274 complex one.
275
276 Do It All Yourself
277 The "initialize_if_enabled()" method for a Policy receives one
278 argument: an instance of Perl::Critic::PolicyConfig. This method is
279 only called if the user's configuration has enabled the policy. It
280 returns a boolean stating whether the Policy should continue to be
281 enabled. Generally, the only reason to return $FALSE is when some
282 external requirement is missing. For example,
283 Perl::Critic::Policy::CodeLayout::RequireTidyCode disables itself if
284 Perl::Tidy is not installed.
285
286 A basic, do-nothing implementation of "initialize_if_enabled()" would
287 be:
288
289 use Perl::Critic::Utils qw< :booleans >;
290
291 ...
292
293 sub initialize_if_enabled {
294 my ( $self, $config ) = @_;
295
296 return $TRUE;
297 }
298
299 As stated above, what you get in $config are trimmed strings. For
300 example, if the user's .perlcritic contains
301
302 [Your::Policy]
303 foo = bar baz
304 factor = 5.52
305 selections = 2 78 92
306
307 then $config will contain the equivalent of
308
309 my $config = {
310 foo => 'bar baz',
311 factor => '5.52',
312 selections => '2 78 92',
313 };
314
315 To make this available to the "violates()" method, the values are
316 usually put into $self under the name of the configuration item
317 prefixed with an underscore. E.g.
318
319 sub initialize_if_enabled {
320 my ( $self, $config ) = @_;
321
322 $self->{_foo} = $config->get{foo};
323 $self->{_factor} = $config->get{factor};
324 $self->{_selections} = $config->get{selections};
325
326 return $TRUE;
327 }
328
329 Often, you'll want to convert the configuration values into something
330 more useful. In this example, "selections" is supposed to be a list of
331 integers. Perl::Critic::Utils contains a number of functions that can
332 help you with this. Assuming that "violates()" wants to have
333 "selections" as an array, you'll want to have something like this:
334
335 use Perl::Critic::Utils qw{ :booleans :characters :data_conversion };
336
337 sub initialize_if_enabled {
338 my ( $self, $config ) = @_;
339
340 $self->{_foo} = $config->get{foo};
341 $self->{_factor} = $config->get{factor};
342
343 my $selections = $config->get{selections};
344 $selections = defined $selections ? $selections : $EMPTY_STRING;
345 $self->{_selections} = [ words_from_string($selections) ];
346
347 return $TRUE;
348 }
349
350 Since "selections" contains numbers, it may be desirable to change the
351 assignment to look like
352
353 $self->{_selections} = [ map { $_ + 0 } words_from_string($selections) ];
354
355 If "violates()" needs to quickly determine whether a particular value
356 is in "selections", you would want to use a hash instead of an array,
357 like this:
358
359 $self->{_selections} = { hashify( words_from_string($selections) ) };
360
361 For an example of a Policy that has some simple, but non-standard
362 configuration handling, see
363 Perl::Critic::Policy::CodeLayout::RequireTidyCode.
364
365 Note On Constructors
366 It used to be the case that Policies handled configuration by
367 implementing a constructor. However, there was no requirement to call
368 the base constructor; as long as the Policy ended up being a blessed
369 hash reference, everything was fine. Unfortunately, this meant that
370 Policies would be loaded and their prerequisites would be "use"d, even
371 if the Policy wasn't enabled, slowing things down. Also, this severely
372 restricted the core of Perl::Critic's ability to enhance things. Use
373 of constructors is deprecated and is incompatible with
374 "supported_parameters()" metadata below. Kindly use
375 "initialize_if_enabled()", instead, to do any sort of set up that you
376 need.
377
378 Providing Basic Configuration Information Via "supported_parameters()"
379 As minimum for a well behaved Policy, you should implement
380 "supported_parameters()" in order to tell the rest of "Perl::Critic"
381 what configuration values the Policy looks for, even if it is only to
382 say that the Policy is not configurable. In the simple form, this
383 function returns a list of the names of the parameters the Policy
384 supports. So, for an non-configurable Policy, as in the
385 "RequireBlockGrep" example above, this looked like
386
387 sub supported_parameters { return () }
388
389 For the example being used in the "initialize_if_enabled()" section
390 above, this would be
391
392 sub supported_parameters { return qw< foo factor selections >; }
393
394 Given this information, "Perl::Critic" can tell the user when they have
395 specified a parameter for a Policy which isn't valid, e.g. when they've
396 misspelled the name of the parameter, and can emit the parameter as
397 part of a .perlcriticrc prototype.
398
399 You can provide even more information about your Policy's configuration
400 by giving each parameter a description and a string representation of
401 the default value for the parameter. You do this by having the values
402 in the list returned by "supported_parameters()" be hash references
403 instead of strings, with keys of "name", "description", and
404 "default_string". For example,
405
406 sub supported_parameters {
407 return (
408 {
409 name => 'allowed_values',
410 description =>
411 'Individual and ranges of values to allow, and/or "all_integers".',
412 default_string => '0 1 2',
413 },
414 {
415 name => 'allowed_types',
416 description => 'Kind of literals to allow.',
417 default_string => 'Float',
418 },
419 );
420 }
421
422 Note that use of constructors is incompatible with specifying
423 parameters in this way.
424
425 Using "supported_parameters()" to Get It Done For You
426 The "supported_parameters()" discussion above showed how you could help
427 others with your Policy, but didn't do anything to make your life as a
428 Policy author easier; you still need to implement
429 "initialize_if_enabled()" to access any configuration that the user has
430 specified. To have the configuration automatically handled for you,
431 you need to declare how your parameters act by specifying a value for
432 their "behavior". For example, the following declares that a parameter
433 allows the user to choose from five specific values and that the user
434 can select any combination of them:
435
436 sub supported_parameters {
437 return (
438 {
439 name => 'allowed_types',
440 description => 'Kind of literals to allow.',
441 default_string => 'Float',
442 behavior => 'enumeration',
443 enumeration_values => [ qw{ Binary Exp Float Hex Octal } ],
444 enumeration_allow_multiple_values => 1,
445 },
446 );
447 }
448
449 When you specify a behavior, parsing and validation of the user-
450 specified and default values is done for you and your "violates()"
451 method can retrieve the value under the key of the parameter name
452 prefixed with an underscore, e.g., for the above declaration, the
453 parsed and validated value can be accessed via
454 "$self->{_allowed_types}".
455
456 The behaviors provide additional functionality to "Perl::Critic"; for
457 more on this, see Perl::Critic::PolicyParameter and
458 Perl::Critic::PolicyParameter::Behavior.
459
460 The following discusses each of the supported behaviors and the options
461 they support. For the full details of a behavior, see the
462 documentation for the implementing class.
463
464 "string"
465
466 Implemented in Perl::Critic::PolicyParameter::Behavior::String.
467
468 The most basic of behaviors, the value of the parameter will be stored
469 in the Policy as a string.
470
471 This behavior is not configurable.
472
473 "supported_parameters()" example
474
475 sub supported_parameters {
476 return (
477 {
478 name => 'a_string',
479 description => 'An example string.',
480 default_string => 'blah blah blah',
481 behavior => 'string',
482 },
483 );
484 }
485
486 Access example
487
488 sub violates {
489 my ($self, $element, $document) = @_;
490
491 ...
492 my $string = $self->{_a_string};
493 ...
494 }
495
496 "boolean"
497
498 Implemented in Perl::Critic::PolicyParameter::Behavior::Boolean.
499
500 The value of the parameter will be either $TRUE or $FALSE.
501
502 This behavior is not configurable.
503
504 "supported_parameters()" example
505
506 sub supported_parameters {
507 return (
508 {
509 name => 'a_boolean',
510 description => 'An example boolean.',
511 default_string => '1',
512 behavior => 'boolean',
513 },
514 );
515 }
516
517 Access example
518
519 sub violates {
520 my ($self, $element, $document) = @_;
521
522 ...
523 my $is_whatever = $self->{_a_boolean};
524 if ($is_whatever) {
525 ...
526 }
527 ...
528 }
529
530 "integer"
531
532 Implemented in Perl::Critic::PolicyParameter::Behavior::Integer.
533
534 The value is validated against "m/ \A [-+]? [1-9] [\d_]* \z /xms" (with
535 an special check for "0"). Notice that this means that underscores are
536 allowed in input values as with Perl numeric literals.
537
538 This takes two options, "integer_minimum" and "integer_maximum", which
539 specify endpoints of an inclusive range to restrict the value to.
540 Either, neither, or both may be specified.
541
542 "supported_parameters()" example
543
544 sub supported_parameters {
545 return (
546 {
547 name => 'an_integer',
548 description => 'An example integer.',
549 default_string => '5',
550 behavior => 'integer',
551 integer_minimum => 0,
552 integer_maximum => 10,
553 },
554 );
555 }
556
557 Access example
558
559 sub violates {
560 my ($self, $element, $document) = @_;
561
562 ...
563 my $integer = $self->{_an_integer};
564 if ($integer > $TURNING_POINT) {
565 ...
566 }
567 ...
568 }
569
570 "string list"
571
572 Implemented in Perl::Critic::PolicyParameter::Behavior::StringList.
573
574 The values will be derived by splitting the input string on blanks.
575 (See "words_from_string" in Perl::Critic::Utils.) The parameter will be
576 stored as a reference to a hash, with the values being the keys.
577
578 This takes one optional option, "list_always_present_values", of a
579 reference to an array of strings that will always be included in the
580 parameter value, e.g. if the value of this option is "[ qw{ a b c } ]"
581 and the user specifies a value of 'c d e', then the value of the
582 parameter will contain 'a', 'b', 'c', 'd', and 'e'.
583
584 "supported_parameters()" example
585
586 sub supported_parameters {
587 return (
588 {
589 name => 'a_string_list',
590 description => 'An example list.',
591 default_string => 'red pink blue',
592 behavior => 'string list',
593 list_always_present_values => [ qw{ green purple} ],
594 },
595 );
596 }
597
598 Access example
599
600 sub violates {
601 my ($self, $element, $document) = @_;
602
603 ...
604 my $list = $self->{_a_string_list};
605 my @list = keys %{$list};
606 ...
607 return if not $list->{ $element->content() };
608 ...
609 }
610
611 "enumeration"
612
613 Implemented in Perl::Critic::PolicyParameter::Behavior::Enumeration.
614
615 The values will be derived by splitting the input string on blanks.
616 (See "words_from_string" in Perl::Critic::Utils.) Depending upon the
617 value of the "enumeration_allow_multiple_values" option, the parameter
618 will be stored as a string or a reference to a hash, with the values
619 being the keys.
620
621 This behavior takes one required option and one optional one. A value
622 for "enumeration_values" of a reference to an array of valid strings is
623 required. A true value can be specified for
624 "enumeration_allow_multiple_values" to allow the user to pick more than
625 one value, but this defaults to false.
626
627 "supported_parameters()" example
628
629 use Perl::Critic::Utils qw{ :characters };
630
631 sub supported_parameters {
632 return (
633 {
634 name => 'a_single_valued_enumeration',
635 description =>
636 'An example enumeration that can only have a single value.',
637 default_string => $EMPTY,
638 behavior => 'enumeration',
639 enumeration_values => [ qw{ block statement pod operator } ],
640 enumeration_allow_multiple_values => 0,
641 },
642 {
643 name => 'a_multi_valued_enumeration',
644 description =>
645 'An example enumeration that can have multiple values.',
646 default_string => 'fe',
647 behavior => 'enumeration',
648 enumeration_values => [ qw{ fe fi fo fum } ],
649 enumeration_allow_multiple_values => 1,
650 },
651 );
652 }
653
654 Access example
655
656 sub violates {
657 my ($self, $element, $document) = @_;
658
659 ...
660 my $single_value = $self->{_a_single_valued_enumeration};
661 ...
662 my $multi_value = $self->{_a_multi_valued_enumeration};
663 if ( $multi_value->{fum} ) {
664 ...
665 }
666 ...
667 }
668
669 Using a Custom Parser
670 If none of the behaviors does exactly what you want it to, you can
671 provide your own parser for a parameter. The reason for doing this as
672 opposed to using an implementation of "initialize_if_enabled()" is that
673 it allows you to use a behavior to provide its extra functionality and
674 it provides a means for a "Perl::Critic" configuration program, e.g. an
675 IDE that integrates "Perl::Critic", to validate your parameter as the
676 user modifies its value.
677
678 The way you declare that you have a custom parser is to include a
679 reference to it in the parameter specification with the "parser" key.
680 For example:
681
682 sub supported_parameters {
683 return (
684 {
685 name => 'file_name',
686 description => 'A file for to read a list of values from.',
687 default_string => undef,
688 behavior => 'string',
689 parser => \&_parse_file_name,
690 },
691 );
692 }
693
694 A parser is a method on a subclass of Perl::Critic::Policy that takes
695 two parameters: the Perl::Critic::PolicyParameter that is being
696 specified and the value string provided by the user. The method is
697 responsible for dealing with any default value and for saving the
698 parsed value for later use by the "violates()" method.
699
700 An example parser (without enough error handling) for the above example
701 declaration:
702
703 use File::Slurp qw< slurp >;
704
705 use Perl::Critic::Exception::Configuration::Option::Policy::ParameterValue
706 qw{ throw_policy_value };
707
708 sub _parse_file_name {
709 my ($self, $parameter, $config_string) = @_;
710
711 my @thingies;
712
713 if ($config_string) {
714 if (not -r $config_string) {
715 throw_policy_value
716 policy => $self->get_short_name(),
717 option_name => $parameter->get_name(),
718 option_value => $config_string,
719 message_suffix => 'is not readable.';
720 }
721
722 @thingies = slurp $config_string;
723 }
724
725 $self->{_thingies} = \@thingies;
726
727 return;
728 }
729
730 Note that, if the value for the parameter is not valid, an instance of
731 Perl::Critic::Exception::Configuration::Option::Policy::ParameterValue
732 is thrown. This allows "Perl::Critic" to include that problem along
733 with any other problems found with the user's configuration in a single
734 error message.
735
736 Using Both "supported_parameters()" and "initialize_if_enabled()"
737 There are cases where a Policy needs additional initialization beyond
738 configuration or where the way it acts depends upon the combination of
739 multiple parameters. In such situations, you will need to create an
740 implementation of "initialize_if_enabled()". If you want to take
741 advantage of the supplied parameter handling from within implementation
742 of "initialize_if_enabled()", note that the information from
743 "supported_parameters()" will already have been used, with user-
744 supplied parameter values validated and placed into the Policy by the
745 time "initialize_if_enabled()" has been called. It is likely that you
746 will not need to refer the contents of the $config parameter; just pull
747 the information you need out of $self. In fact, any value for the
748 parameter values will be gone.
749
750 Summary of permitted hash keys in "supported_parameters()".
751 All types
752
753 - "name" (mandatory)
754 - "description" (optional)
755 - "behavior" (optional)
756 Currently, one of:
757
758 "boolean"
759 "enumeration"
760 "integer"
761 "string"
762 "string list"
763 - "default_string" (optional)
764 A string representation of the default value of the parameter.
765
766 - "parser" (optional)
767 A code ref to a custom parser for the parameter.
768
769 Enumerations
770
771 - "enumeration_values" (mandatory)
772 A mandatory reference to an array of strings.
773
774 - "enumeration_allow_multiple_values" (optional)
775 Boolean indicating whether or not the user is restricted to a
776 single value.
777
778 Integers
779
780 - "integer_minimum" (optional)
781 Minimum allowed value, inclusive.
782
783 - "integer_maximum" (optional)
784 Maximum allowed value, inclusive.
785
786 String lists
787
788 - "list_always_present_values" (optional)
789 A reference to an array of values that should always be included in
790 the value of the parameter.
791
793 "default_maximum_violations_per_document()"
794 Certain problems that a Policy detects can be endemic to a particular
795 file; if there's one violation, there's likely to be many. A good
796 example of this is
797 Perl::Critic::Policy::TestingAndDebugging::RequireUseStrict; if there's
798 one line before "use strict", there's a good chance that the entire
799 file is missing "use strict". In such cases, it's not much help to the
800 user to report every single violation. If you've got such a policy,
801 you should override default_maximum_violations_per_document() method to
802 provide a limit. The user can override this value with a value for
803 "maximum_violations_per_document" in their .perlcriticrc.
804
805 See the source code for
806 Perl::Critic::Policy::ValuesAndExpressions::ProhibitMagicNumbers and
807 Perl::Critic::Policy::TestingAndDebugging::RequireUseWarnings for
808 examples.
809
811 Create a Distribution
812 You need to come up with a name for your set of policies. Sets of add-
813 on policies are generally named "Perl::Critic::something", e.g.
814 Perl::Critic::More.
815
816 The module representing the distribution will not actually have any
817 functionality; it's just documentation and a name for users to use when
818 installing via CPAN/CPANPLUS. The important part is that this will
819 include a list of the included policies, with descriptions of each.
820
821 A typical implementation will look like:
822
823 package Perl::Critic::Example;
824
825 use strict;
826 use warnings;
827
828 our $VERSION = '1.000000';
829
830 1; # Magic true value required at end of module
831
832 __END__
833
834 =head1 NAME
835
836 Perl::Critic::Example - Policies for Perl::Critic that act as an example.
837
838 =head1 AFFILIATION
839
840 This module has no functionality, but instead contains documentation
841 for this distribution and acts as a means of pulling other modules
842 into a bundle. All of the Policy modules contained herein will have
843 an "AFFILIATION" section announcing their participation in this
844 grouping.
845
846
847 =head1 SYNOPSIS
848
849 Some L<Perl::Critic|Perl::Critic> policies that will help you keep your
850 code nice and compliant.
851
852
853 =head1 DESCRIPTION
854
855 The included policies are:
856
857 =over
858
859 =item L<Perl::Critic::Policy::Documentation::Example|Perl::Critic::Policy::Documentation::Example>
860
861 Complains about some example documentation issues. [Severity: 3]
862
863
864 =item L<Perl::Critic::Policy::Variables::Example|Perl::Critic::Policy::Variables::Example>
865
866 All modules must have at least one variable. [Severity: 3]
867
868
869 =back
870
871
872 =head1 CONFIGURATION AND ENVIRONMENT
873
874 All policies included are in the "example" theme. See the
875 L<Perl::Critic|Perl::Critic> documentation for how to make use of this.
876
877 Themes
878 Users can choose which policies to enable using themes. You should
879 implement "default_themes()" so that users can take advantage of this.
880 In particular, you should use a theme named after your distribution in
881 all your policies; this should match the value listed in the
882 "CONFIGURATION AND ENVIRONMENT" POD section as shown above.
883
884 default_themes { return qw< example math > }
885
886 If you're looking for ideas of what themes to use, have a look at the
887 output of "perlcritic --list-themes".
888
889 Documentation
890 AFFILIATION
891
892 Since all policies have to go somewhere under the
893 "Perl::Critic::Policy::" namespace, it isn't always clear what
894 distribution a policy came from when browsing through their
895 documentation. For this reason, you should include an "AFFILIATION"
896 section in the POD for all of your policies that state where the policy
897 comes from. For example:
898
899 =head1 AFFILIATION
900
901 This policy is part of L<Perl::Critic::Example|Perl::Critic::Example>.
902
903 CONFIGURATION
904
905 In order to make it clear what can be done with a policy, you should
906 always include a "CONFIGURATION" section in your POD, even if it's only
907 to say:
908
909 =head1 CONFIGURATION
910
911 This Policy is not configurable except for the standard options.
912
914 When you're trying to figure out what PPI is going to hand you for a
915 chunk of code, there is a tools/ppidump program in the Perl::Critic
916 distribution that will help you. For example, when developing the
917 above RequireBlockGrep example, you might want to try
918
919 tools/ppidump '@matches = grep /pattern/, @list;'
920
921 and
922
923 tools/ppidump '@matches = grep { /pattern/ } @list;'
924
925 to see the differences between the two cases.
926
927 Alternatively, see the "ppi_dumper" documentation at
928 http://search.cpan.org/dist/App-PPI-Dumper/script/ppi_dumper
929 <http://search.cpan.org/dist/App-PPI-Dumper/script/ppi_dumper> and the
930 "PPI::Tester" documentation at
931 http://search.cpan.org/dist/PPI-Tester/lib/PPI/Tester.pm
932 <http://search.cpan.org/dist/PPI-Tester/lib/PPI/Tester.pm>.
933
935 This is part of Perl::Critic version 1.106.
936
938 Jeffrey Ryan Thalhammer <thaljef@cpan.org>
939
941 Copyright (c) 2005-2009 Jeffrey Ryan Thalhammer. All rights reserved.
942
943 This program is free software; you can redistribute it and/or modify it
944 under the same terms as Perl itself. The full text of this license can
945 be found in the LICENSE file included with this module.
946
947
948
949perl v5.12.1 2010-09-08 Perl::Critic::DEVELOPER(3)