File Coverage

blib/lib/Babble/Plugin/DefinedOr.pm
Criterion Covered Total %
statement 21 21 100.0
branch 4 4 100.0
condition n/a
subroutine 4 4 100.0
pod 0 1 0.0
total 29 30 96.6


line stmt bran cond sub pod time code
1             package Babble::Plugin::DefinedOr;
2              
3 1     1   71235 use Moo;
  1         7194  
  1         5  
4              
5             sub transform_to_plain {
6 6     6 0 6909 my ($self, $top) = @_;
7             $top->each_match_within(Statement => [
8             [ before => '(?>(?&PerlPrefixPostfixTerm))' ],
9             [ op => '(?>(?&PerlOWS) //=)' ], '(?>(?&PerlOWS))',
10             [ after => '(?>(?&PerlPrefixPostfixTerm))' ],
11             '(?>(?&PerlOWS))',
12             [ trail => '
13             (?&PerlStatementModifier)?+
14             (?>(?&PerlOWS))
15             (?> ; | (?= \} | \z ))
16             ' ],
17             ] => sub {
18 2     2   7 my ($m) = @_;
19 2         13 my ($before, $after, $trail) = $m->subtexts(qw(before after trail));
20 2         21 s/^\s+//, s/\s+$// for ($before, $after);
21 2         11 my $assign = 'defined($_) or $_ = '.$after.' for '.$before;
22 2 100       11 if (length($trail) > 1) {
23 1         4 $assign = 'do { '.$assign.' } '
24             }
25 2         16 $m->replace_text($assign.$trail);
26 6         91 });
27             my $tf = sub {
28 4     4   16 my ($m) = @_;
29 4         24 my ($before, $after) = $m->subtexts(qw(before after));
30 4         39 s/^\s+//, s/\s+$// for ($before, $after);
31 4 100       86 if ($m->submatches->{op}->text =~ /=$/) {
32 2         48 $after = '($_ = '.$after.')';
33             }
34 4         108 $m->replace_text('(map +(defined($_) ? $_ : '.$after.'), '.$before.')[0]');
35 6         136 };
36 6         62 $top->each_match_within(BinaryExpression => [
37             [ before => '(?>(?&PerlPrefixPostfixTerm))' ],
38             [ op => '(?>(?&PerlOWS) //)' ], '(?>(?&PerlOWS))',
39             [ after => '(?>(?&PerlPrefixPostfixTerm))' ],
40             ] => $tf);
41 6         91 $top->each_match_within(Assignment => [
42             [ before => '(?>(?&PerlConditionalExpression))' ],
43             [ op => '(?>(?&PerlOWS) //=)' ], '(?>(?&PerlOWS))',
44             [ after => '(?>(?&PerlConditionalExpression))' ],
45             ] => $tf);
46             }
47              
48             1;
49             __END__
50              
51             =head1 NAME
52              
53             Babble::Plugin::DefinedOr - Plugin for defined-or (//) syntax
54              
55             =head1 SYNOPSIS
56              
57             Converts usage of the defined-or syntax from
58              
59             $foo // $bar
60              
61             to
62              
63             (map +(defined($_) ? $_ : $bar), $foo)[0]
64              
65             =head1 SEE ALSO
66              
67             L<E<sol>E<sol> syntax|Syntax::Construct/"//">
68              
69             =cut