My major is too easy...


This weekend, I had absolutely nothing to do. I didn't have any homework, studying, projects or the like because my major is far too easy. So I got bored and wrote a complete Brainfuck interpreter in Perl.

The interpreter was the easiest; it took me a morning to get that working albeit without support for nested parens. After that, I decided to write a text to Brainfuck converter, which (not surprisingly) turns text into executable Brainfuck code. Maybe if I get bored again, I could write a module to output the equivalent Perl or C code given some Brainfuck code.

This was my first real project using object oriented Perl. In all honesty, I like that Perl's object system allows for many different types of objects (objects can be scalars, arrays, or hashes) and how flexible that is. Unfortunately, I didn't get to exploit that flexibility in my code. It's still cool though.

What I wrote is 2 Perl modules that make up the linked list that store data generated by Brainfuck code, a Perl module that interprets and runs the code, and a Perl module that translates text to executable Brainfuck code. I know I could have used a pre-built linked list, but I thought it was more fun to write my own.

The biggest challenge was definitely writing the translation code. I could've done it the easy way, and just output x amount of pluses for the character code of each letter, but I decided that was the lamest way to write Brainfuck. Instead, I looped through each character in the phrase, and added some nodes in my Brainfuck code that corresponded to the tens place of each character code. Then, when outputting a character, my Brainfuck code would change the data pointer to the node that was set to the tens place of the character code of the desired character, and increment or decrement it to the proper value.

A more ideal way to do it (to generate cleaner Brainfuck, at least) is to set each of those prep nodes to the nearest multiple of 20 for each character code, and then use whichever node is closest to the desired value. Maybe if I feel like doing more with this, then I'll add that feature (probably not).

In addition to writing all this, I also made a GitHub account. My GitHub has all the above code, so you can clone the repo if you want to see what the code looks like (it's actually really easy to read Perl).

This whole idea came from an idea on CSH. A guy here decided to publish a "Hello World of the Week" article in our newsletter, and to combat him I wrote a Brainfuck version of Hello World. This contest grew, and other people joined (albeit humorously) with such contributions as a boot loader that printed out Hello World, Hello World in White Space, and Hello World in Microsoft Word. My contribution (also in my git repo) generated valid Brainfuck code for the phrase Hello World, and then ran it through my interpreter (aka Hello World in 425ish lines).