Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Friday, July 31, 2015

Powerful PERL Script for Large codes

 

Count lines of code in a C,C++,Java,perl,shell,html,VHDL,Verilog or Python file

   
#!/usr/bin/perl -0777
my @lines = ();
my $numofifs = 1;
my $commentstarted = 0;
my $notacfile = 0;

if($ARGV[0] !~ /\.[cCh]$/) {
  $notacfile = 1;
}

while(<>) {
     s/\/\*(.*?)\*\//cOmMeNt/gms;
     s/<!--(.*?)-->/cOmMeNt/gms;
     @tmp = split(/\n/);
     for(@tmp) {

     if (/cOmMeNt/) {
                unless(/cOmMeNt/ ) {
$_ = $_ . "\n";
                        push(@lines, $_);
next;
                 }
                 else {
                    if((/[\S]+[\s]*cOmMeNt/) || (/cOmMeNt[\s]*[\S]+/)) {
                       $_ = $_ . "\n";
                       push(@lines, $_);
                    }
           
                 }
         }
          else {
#slurp #if 0 comments
            if( (/^[\s]*#[\s]*if[\s]+0/) || ($commentstarted == 1) ) {
                if ( $commentstarted == 0) {
                  $commentstarted = 1;
                  next;
                }
                if(/^[\s]*#[\s]*if/) {
                 $numofifs = $numofifs + 1;
                 next;
                }
                unless(/^[\s]*#[\s]*endif/) {
              next; # slurp the comments
                }
                 else { # we found an endif, but we don't know if it is the right one...
                  $numofifs = $numofifs - 1;
                  if($numofifs == 0) {
                    $commentstarted = 0;
                    $numofifs = 1;
                  }
                  next;
                 }
            }

#leave out // comments
if(/^[\s]*\/\//) {
        next;
}
# leaave out # style comments if it is not a C/C++ file taking care to count #! line
               if($notacfile == 1) {
                unless(/^#!/) {
                  if  (/^[\s]*#/) {
   next;
                  }
                }
               }
#leave out blank lines ,vhdl  and assembly type comments
if( (/^[\s]*$/) || (/^[\s]*--/) || (/^[\s]*;/) ){
        next;
}

# Now leave out =head and =pod section till =cut in perl scripts
if( (/^=pod/) || (/^=head/) || ($commentstarted == 1) ) {
                if ( $commentstarted == 0) {
                  $commentstarted = 1;
                  next;
                }
               unless(/^=cut/) {
              next; # slurp the comments
                }
            # Now found cut, just fall thro'
            }
$_ = $_ . "\n";
                push(@lines, $_);
my @lines = ();
          }

      }
}
print "The number of lines of code in file is [1m " . @lines . " [0m\n";
exit @lines;

No comments:

Post a Comment