Brainfuck interpreter in Perl 6

Posted by Daniel on May 30, 2009
Perl 6, Programming

I wrote a Brainfuck interpreter in Perl 6 (largely inspired by Acme::Brainfuck). Here it is in its entirety:

# Read the program.
my $program = $*IN.slurp;

# Compile to Perl 6.
$program .= subst(/\$/, 'P; };', :g);
$program .= subst(/(\++)/, { 'P += ' ~ $0.chars ~ ';' }, :g);
$program .= subst(/(\-+)/, { 'P -= ' ~ $0.chars ~ ';' }, :g);
$program .= subst(/(\>+)/, { '$ptr += ' ~ $0.chars ~ ';' }, :g);
$program .= subst(/(\<+)/, { '$ptr -= ' ~ $0.chars ~ ';' }, :g);
$program .= subst(/\./, 'print chr P;', :g);
$program .= subst(/\,/, 'P = ord getc;', :g);
$program .= subst(/\[/, 'while (P) {', :g);
$program .= subst(/\]/, '};', :g);
$program .= subst(/P/, '@P[$ptr]', :g);
$program  = 'my @P = (); my $ptr = 0;' ~ $program;

# Run
eval $program;

Here is “Hello world” in Brainfuck (taken from Wikipedia):

++++++++++    initializes cell zero to 10
[
   >+++++++>++++++++++>+++>+<<<<-
]             loop sets the next four cells to 70/100/30/10
>++.          print   'H'
>+.           print   'e'
+++++++.              'l'
.                     'l'
+++.                  'o'
>++.                  space
<<+++++++++++++++.    'W'
>.                    'o'
+++.                  'r'
------.               'l'
--------.             'd'
>+.                   '!'
>.                    newline

To run the program, just do: perl6 brainfuck.pl < hello.bf

No comments yet.

Leave a comment

WP_Big_City

Buy cheap softwarebuy adobe softwaredownload software software sales oem software