File Coverage

blib/lib/App/PerlNitpick/Rule/RewriteWithAssignmentOperators.pm
Criterion Covered Total %
statement 32 32 100.0
branch 6 10 60.0
condition 4 12 33.3
subroutine 5 5 100.0
pod 0 1 0.0
total 47 60 78.3


line stmt bran cond sub pod time code
1             package App::PerlNitpick::Rule::RewriteWithAssignmentOperators;
2              
3 1     1   344057 use Moose;
  1         520443  
  1         11  
4 1     1   8046 use PPI::Document;
  1         3  
  1         28  
5 1     1   6 use PPI::Token::Whitespace;
  1         3  
  1         49  
6              
7 1     1   8 no Moose;
  1         3  
  1         6  
8              
9             sub rewrite {
10 5     5 0 20516 my ($self, $document) = @_;
11              
12             my @found = grep {
13 4         44 my $c1 = $_->schild(0);
14 4         50 my $c2 = $_->schild(2);
15 4 50 33     79 $c1->isa('PPI::Token::Symbol') && $c1->raw_type eq '$' &&
      33        
      33        
      33        
16             $c2->isa('PPI::Token::Symbol') && $c2->raw_type eq '$' &&
17             $c1->content && $c2->content
18             } grep {
19 5         51 my $c = $_->schild(3);
20 5 50       100 $c->isa('PPI::Token::Operator') && $c->content !~ m{\A( -> | > | < )\z}x;
21             } grep {
22 5         119 my $c = $_->schild(1);
23 5 50       109 $c->isa('PPI::Token::Operator') && $c->content eq '='
24             } grep {
25 6         2381 $_->schildren == 6
26 5 50       16 } @{ $document->find('PPI::Statement') ||[] };
  5         31  
27            
28 5 100       152 return $document unless @found;
29              
30 4         13 for my $statement (@found) {
31 4         13 my @child = $statement->schildren;
32              
33             # assigment operator :)
34 4         68 my $assop = PPI::Token::Operator->new($child[3]->content . $child[1]->content);
35              
36 4         87 $child[3]->remove;
37 4         263 $child[2]->remove;
38 4         141 $child[1]->insert_after($assop);
39 4         209 $child[1]->remove;
40             }
41              
42 4         162 return $document;
43             }
44              
45             1;
46              
47             __END__
48              
49             =head1 DESCRIPTION
50              
51             This rule rewrites those assignments that alter a single varible with itself.
52             For example, this one:
53              
54             $x = $x + 2;
55              
56             Is rewritten with the C<+=> assignment operator, as:
57              
58             $x += 2;
59              
60             =cut