Archive for May, 2009

Brainfuck interpreter in Perl 6

Posted by Daniel on May 30, 2009
Perl 6, Programming / No Comments

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

Perl 6

Posted by Daniel on May 27, 2009
Perl 6, Programming / No Comments

This week I’ve been experimenting a little with Perl 6. It began as a quick question on IRC and somehow I ended up writing sample scripts in Perl 6. This week I ported the regex-dna benchmark to Perl 6, and I intend to port a few others. You can download it here.

One thing that’s new about Perl 6 is that it is a specification, similar to C, C++ and Java. Any product that meets the spec and passes the test suite can be called Perl 6 (there are many C compilers, and none of them is “the official C compiler”).

The implementation I have been experimenting with is Rakudo (compiler written in Perl 6 and Parrot assembly language) which seems to be the most active and the most complete. You can already write some Perl 6 programs with the Rakudo compiler. There is a wiki called November, a board game called druid, and a few others. Other notable implementations include Pugs (interpreter written in Haskell) and SMOP (interpreter written in C).

purchase software