Remove trailing if statements from Perl code

This Perl script demonstrates how to remove trailing if statements from Perl program code. For example, it converts

if (1) {
    print "OK" if 2;
}
else {
    print "Not OK" if 2 + 2 == 5;
}

(download)

into
if (1) {
    if (2) {
        print "OK";
    }
}
else {
    if (2 + 2 == 5) {
        print "Not OK";
    }
}

(download)

Here is the program:
#!/home/ben/software/install/bin/perl
use warnings;
use strict;
use File::Slurper 'read_text';

my @files = @ARGV;
for my $file (@files) {
    my $text = read_text ($file);
    remove_trailing_ifs ($text);
}
exit;

sub remove_trailing_ifs
{
    my ($text) = @_;
    $text =~ s/
                  ^
                  (?<leading_space>\h*)
                  (?<action>\S.*)
                  \s+
                  (?<type>if|unless)
                  \s+
                  (?<condition>.*)
                  ;
                  \s*
                  $
              /$+{leading_space}$+{type} ($+{condition}) {
$+{leading_space}    $+{action};
$+{leading_space}}/gxm;
    print $text;
}

(download)


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer