#36 Code Generator

One of the problems with C and C++ is that there's no easy way of turning an enum into a string. To do so you have to write your own translation table. Or you can write a short Perl script to do the work for you.

The Code

 1 use strict; 2 use warnings; 3 4 if ($#ARGV != 0) { 5 print STDERR "Usage is $0 <input file>\n"; 6 exit (8); 7 } 8 9 $ARGV[0] =~ /^([^\.]*)/; 10 my $enum = $1; 11 my $ENUM = $enum; 12 $ENUM =~ tr [a-z] [A-Z]; 13 14 my @words = <>; 15 chomp(@words); 16 17 18 print "enum $ENUM {\n"; 19 foreach my $cur_word (@words) { 20 print " $cur_word,\n"; 21 } 22 print "};\n"; 23 24 print <<EOF; 25 static const char* const ${enum}_to_string[] = { 26 EOF 27 foreach my $cur_word (@words) { 28 print " \"$cur_word\",\n"; ...

Get Wicked Cool Perl Scripts now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.