Login
Moved the check for conditionals strings to the top of _is_conditional. Also set...
[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$
c0b487cd 6# ex: set ts=8 sts=4 sw=4 expandtab
5cb27b1a
JRT
7########################################################################
8
9package Perl::Critic::Policy::Variables::ProhibitConditionalDeclarations;
10
11use strict;
12use warnings;
13use Perl::Critic::Utils;
5cb27b1a
JRT
14use List::MoreUtils qw(any);
15use base 'Perl::Critic::Policy';
16
8d36cd6f 17our $VERSION = '0.18';
5cb27b1a
JRT
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 {
e5f6c18d 33 my ( $self, $elem, undef ) = @_;
5cb27b1a
JRT
34
35 if ( $elem->find(\&_is_conditional) ) {
2c6df011 36 return $self->violation( $desc, $expl, $elem );
5cb27b1a
JRT
37 }
38 return; #ok!
39}
40
0853d023
AL
41my %conditionals = map {($_,1)} qw(if while foreach for until unless);
42
5cb27b1a 43sub _is_conditional {
e5f6c18d
AL
44 my (undef, $elem) = @_;
45
0853d023 46 return 0 if !$conditionals{$elem};
5cb27b1a
JRT
47 return if ! $elem->isa('PPI::Token::Word');
48 return if is_hash_key($elem);
49 return if is_method_call($elem);
e5f6c18d 50
0853d023 51 return 1;
5cb27b1a
JRT
52}
53
541;
55
56__END__
57
58#---------------------------------------------------------------------------
59
60=pod
61
62=head1 NAME
63
64Perl::Critic::Policy::Variables::ProhibitConditionalDeclarations
65
66=head1 DESCRIPTION
67
68Declaring a variable with a postfix conditional is really confusing.
69If the conditional is false, its not clear if the variable will
70be false, undefined, undeclared, or what. It's much more straightforward
71to make variable declarations separately.
72
73 my $foo = $baz if $bar; #not ok
74 my $foo = $baz unless $bar; #not ok
75 our $foo = $baz for @list; #not ok
76 local $foo = $baz foreach @list; #not ok
77
78=head1 AUTHOR
79
80Jeffrey R. Thalhammer <thaljef@cpan.org>
81
82=head1 COPYRIGHT
83
84Copyright (c) 2006 Chris Dolan. All rights reserved.
85
86This program is free software; you can redistribute it and/or modify
87it under the same terms as Perl itself. The full text of this license
88can be found in the LICENSE file included with this module.
89
90=cut