Login
Added new ProhibitConditionalDeclarations policy. This policy
[gknop/Perl-Critic.git] / lib / Perl / Critic / Policy / Variables / ProhibitConditionalDeclarations.pm
CommitLineData
5cb27b1a
JRT
1#######################################################################
2# $URL$
3# $Date: 2006-01-30 19:49:47 -0800 (Mon, 30 Jan 2006) $
4# $Author$
5# $Revision$
6########################################################################
7
8package Perl::Critic::Policy::Variables::ProhibitConditionalDeclarations;
9
10use strict;
11use warnings;
12use Perl::Critic::Utils;
13use Perl::Critic::Violation;
14use List::MoreUtils qw(any);
15use base 'Perl::Critic::Policy';
16
17our $VERSION = '0.14_01';
18$VERSION = eval $VERSION; ## no critic
19
20#---------------------------------------------------------------------------
21
22my $desc = q{Variable declared in conditional statement};
23my $expl = q{Declare variables outside of the condition};
24
25#---------------------------------------------------------------------------
26
27sub default_severity { return $SEVERITY_HIGHEST }
28sub applies_to { return 'PPI::Statement::Variable' }
29
30#---------------------------------------------------------------------------
31
32sub violates {
33 my ( $self, $elem, $doc ) = @_;
34
35 if ( $elem->find(\&_is_conditional) ) {
36 my $sev = $self->get_severity();
37 return Perl::Critic::Violation->new( $desc, $expl, $elem, $sev );
38 }
39 return; #ok!
40}
41
42sub _is_conditional {
43 my ($doc, $elem) = @_;
44 return if ! $elem->isa('PPI::Token::Word');
45 return if is_hash_key($elem);
46 return if is_method_call($elem);
47 return any { $elem eq $_ } qw(if while foreach for until unless);
48}
49
501;
51
52__END__
53
54#---------------------------------------------------------------------------
55
56=pod
57
58=head1 NAME
59
60Perl::Critic::Policy::Variables::ProhibitConditionalDeclarations
61
62=head1 DESCRIPTION
63
64Declaring a variable with a postfix conditional is really confusing.
65If the conditional is false, its not clear if the variable will
66be false, undefined, undeclared, or what. It's much more straightforward
67to make variable declarations separately.
68
69 my $foo = $baz if $bar; #not ok
70 my $foo = $baz unless $bar; #not ok
71 our $foo = $baz for @list; #not ok
72 local $foo = $baz foreach @list; #not ok
73
74=head1 AUTHOR
75
76Jeffrey R. Thalhammer <thaljef@cpan.org>
77
78=head1 COPYRIGHT
79
80Copyright (c) 2006 Chris Dolan. All rights reserved.
81
82This program is free software; you can redistribute it and/or modify
83it under the same terms as Perl itself. The full text of this license
84can be found in the LICENSE file included with this module.
85
86=cut