#!/usr/bin/perl
# comments.pl
# by Richard Lawrence 2001
# Correctly comments #endif's in line with their associated #ifdef,
# #ifndef and #if.
#
# usage: comments.pl <filename>
#
# Not fully tested. Use at own risk
#
use strict;
my @define;
open(FILE, "$ARGV[0]") || die "Can't open $ARGV[0] to read: $!";
while(<FILE>)
{
chomp;
if (/^ *\#if (.+)/ || /^\#ifdef (.+)/)
{
push @define, $1;
print "$_\n";
}
elsif (/^ *\#ifndef (.+)/)
{
push @define, "!$1";
print "$_\n";
}
elsif (/^( *)\#else/)
{
my $len = @define;
my $def = invert($define[$len-1]);
print "$1#else /* $def */\n";
}
elsif (/^( *)\#endif/)
{
my $def = pop @define;
print "$1#endif /* $def */\n";
}
else
{
print "$_\n";
}
}
close FILE;
exit(0);
sub invert
{
my $f = substr($_[0], 0, 1);
return substr($_[0], 1, length($_[0])) if ($f eq "!");
return "!$_[0]";
}