Brainfuck

On March 16, 2010, in Development, Programmierung, by tov

Hmmm… Kleine Fingerübung in Perl (pre-alpha :-))

Ah ja: Brainfuck: http://lmgtfy.com/?q=Brainfuck

#!/usr/bin/env perl
use Term::ReadKey;
ReadMode 'raw';
my $debug = 0;

my $code;
if ($ARGV[0]){
	{ local $/ = undef; local *FILE; open FILE, "<".$ARGV[0]; $code = ; close FILE }
}

$code ||=
">+++++++++[<+++++++++++++>-]<-.-----.+++++++
.>+++[>++++++++++<-]
>++.<<----.+++.
--------- . -------.>++++[<+++++>-]<+.>++++++++++.";

$code =~ s/[^\.,+-\[\]<>]//msg;
$| = 1;
my @val;
@val[ 0 .. 29999 ] = (0) x 30000;
my $vpt = 0;
my @ls;
my @le;
my $lpt = 0;
my $cc  = 0;
my @c   = split( '', $code );
my $nc  = @c;
while ( $cc < $nc ) {
    $_ = $c[ $cc++ ];
    print "vpt:$vpt \$val[\$vpt]"
      . $val[$vpt]
      . " loop_counter:$loop_counter loop(counter)_start:"
      . $ls[$loop_counter]
      . " loop(counter)_end:"
      . $le[$loop_counter]
      . " cc:$cc command:$_\n"
      if $debug;
    // and do { $vpt < @val and $vpt++; next };
    /\+/ and do { $val[$vpt] = $val[$vpt] + 1; next; };
    /\-/ and do { $val[$vpt] = $val[$vpt] - 1; next; };
    /\./ and do { print chr( $val[$vpt] ); next; };
    /\,/ and do { $val[$vpt] = ord( ReadKey 0 ); next; };
    /\[/ and do {
        if   ( $val[$vpt] ) { $ls[ $lpt++ ] = $cc - 1 }
        else                { $cc = defined $le[$lpt] ? $le[$lpt] : (index($code,']',$cc)+1) }
        next;
    };
    /\]/ and do {
        $le[ --$lpt ] = $cc;
        $cc = $ls[$lpt];
        next;
    };
}
print "\n";