Perl simple Code formater

I wrote just for fun a litte perl code formater, so  if you want to format your code you could use this snippet:

#!/usr/bin/perl
use strict;
use warnings;
#test sub as a single string
my $testvar = q(
sub _sort {my ($var,%args) = @_;$args{SORT} //= '';if($args{SORT} eq ''){return keys $var;}elsif(uc $args{SORT} eq 'CMP'){return sort {lc $a cmp lc $b} keys $var;}elsif(uc $args{SORT} eq '<=>'){return sort {lc $a <=> lc $b} keys $var;}elsif(uc $args{SORT} eq 'SORT'){return sort keys $var;}return keys $var;}
);
#run the sub
$testvar = _format($testvar);
#print the result
print $testvar.$/;

sub _format {
my $code = shift;
my @blocks = split(/(?<={|}|;)/o,$code);
my $ebene = 0;
$code =~ s/n//go;
    for (my $i=0;$i <= $#blocks;++$i){
        if($blocks[$i] =~ /$[A-Za-z0-9]{1,}{$/o){#open hash
              $blocks[$i] = ('    'x$ebene).$blocks[$i];
              $i += 2;
        }
        if($blocks[$i] =~ /.{0,}{$/o){#open block
            if($blocks[$i-1] =~ /n$/o){
                $blocks[$i] = ('    'x$ebene).$blocks[$i]."n";
            }else{
                $blocks[$i] = $blocks[$i]."n";
            }
            ++$ebene;
        }elsif($blocks[$i] =~ /^.{0,}}/o){#close block
            --$ebene;
            $blocks[$i] = ('    'x$ebene).$blocks[$i]."n";
        }elsif($blocks[$i] =~ /^.{0,};/o){#semicolon same block
            $blocks[$i] = ('    'x$ebene).$blocks[$i]."n";
        }
    }
return join('', @blocks);#rebuild
}

The result from a single line code is this :

sub _sort {
    my ($var,%args) = @_;                   
    $args{SORT}     //= '';                 
    if($args{SORT} eq ''){                  
        return keys $var;                   
    }      
    elsif(uc $args{SORT} eq 'CMP'){         
        return sort {                       
        lc $a cmp lc $b}                    
         keys $var;                         
    }      
    elsif(uc $args{SORT} eq '<=>'){         
        return sort {                       
        lc $a <=> lc $b}                    
         keys $var;                         
    }      
    elsif(uc $args{SORT} eq 'SORT'){        
        return sort keys $var;              
    }      
    return keys $var;                       
}

It was build for little subs so its possible that your big code is not formatted very well.

2 thoughts on “Perl simple Code formater”

  1. Hi all, here every person is sharing such know-how, so it’s fastidious to read this blog, and I used to go to see this blog every day.

  2. Very good information. Lucky me I discovered your website
    by accident (stumbleupon). I’ve saved as a favorite for later!

Leave a Reply

Your email address will not be published.

twenty − 7 =