Skip to content

Instantly share code, notes, and snippets.

@warrenburton
Created March 14, 2014 10:34
Show Gist options
  • Save warrenburton/9545431 to your computer and use it in GitHub Desktop.
Save warrenburton/9545431 to your computer and use it in GitHub Desktop.
converts a typical C style enum declaration into a corresponding switch/case block
#! /usr/bin/perl
#enumify.pl
#converts a typical enum declaration into a corresponding switch/case block
#e.g.
# typedef enum {
# Foo,
# Bar,
# Baz
# } Boodle
#
# to
#
# switch(<#switchvar#>) {
# case Foo:
# break;
# case Bar:
# break;
# case Baz:
# break;
# default:
# break;
# }
#reads from STDIN or use filename as first arg
#on OS X combine with pbpaste e.g pbpaste | enumify.pl
sub trim { my $s = shift; $s =~ s/^\s+|\s+$//g; return $s };
my @lines;
$filename = $ARGV[0];
if (length($filename) > 0) {
{ local *FILE; open FILE, "<$filename"; @lines = <FILE>; close FILE }
} else {
@lines = <STDIN>;
}
if (scalar @lines) {
my $target = "switch(<#switchvar#>) {\n";
my $enumlock = 0;
foreach (@lines) {
if ($enumlock == 0 && m/enum/) {
$enumlock = 1;
}
elsif ( $enumlock == 1) {
$_ = trim($_);
if (!(m/[{}]/) && (length($_)>0)) {
$_ =~ s/,//;
$target = "$target case $_:\nbreak;\n";
}
}
}
$target = "$target default:\nbreak;\n}\n";
if ( $enumlock == 1) {
print $target;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment