-
Notifications
You must be signed in to change notification settings - Fork 0
/
postfix_toggle.pl
executable file
·79 lines (60 loc) · 1.55 KB
/
postfix_toggle.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#! /usr/bin/perl
# To use, insert this in your .vimrc
# toggle postfix conditions in perl
# vnoremap <leader>f :! ~/.bin/postfix_toggle.pl<CR>
use strict;
use warnings;
use feature "say";
# http://babyl.dyndns.org/techblog/entry/statement-toggler
local $/;
my $snippet = <>;
$snippet =~ s/^\s*\n//gm;
my ($indent) = $snippet =~ /^(\s*)/;
$snippet =~ s/^$indent//gm;
my $operators = join '|', qw( if unless while for until );
my $block_re = qr/
^
(?<operator>$operators)
\s* (?:my \s+ (?<variable>\$\w+) \s* )?
\( \s* (?<array>[^)]+)\) \s* {
(?<inner>.*)
}
\s* $
/xs;
my $postfix_re = qr/
^
(?<inner>[^;]+?)
\s+ (?<operator>$operators)
\s+ (?<array>[^;]+?)
\s* ;
$
/xs;
if ( $snippet =~ $block_re ) {
$snippet = block_to_postfix( $snippet, %+ );
}
elsif ( $snippet =~ $postfix_re ) {
$snippet = postfix_to_block( $snippet, %+ );
}
$snippet =~ s/^/$indent/gm;
say $snippet;
sub postfix_to_block
{
my ( $snippet, %capture ) = @_;
$snippet = $capture{inner};
chomp $capture{array};
$snippet = "$capture{operator} ( $capture{array} ) {\n $snippet\n}";
}
sub block_to_postfix
{
my ( $snippet, %capture ) = @_;
return $snippet if $capture{inner} =~ /(;)/ > 1;
$snippet = $capture{inner};
$snippet =~ s/;\s*$//;
$snippet =~ s/\Q$capture{variable}/\$_/g if $capture{variable};
$snippet =~ s/\$_\s*=~\s*//g;
$capture{array} =~ s/\s*$//;
chomp $capture{array};
$snippet .= " $capture{operator} $capture{array};";
$snippet =~ s/\n//g;
return $snippet;
}