here's the code:use Brainfuck; bf_execute(">++++[<++++>-]<+++[->++++<]+ ++[>---<-]++[>+.<-]>[>+>+<<- ]>----.>-.>++++[<+++>-]<--.< .[-]+++++++[->+<]>.-."); or bf_load_sourcefile("asourcefile.b"); bf_execute();
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~package Brainfuck; use strict; use vars qw($VERSION @ISA @EXPORT); @ISA = qw(Exporter); @EXPORT = qw( &bf_load_sourcefile &bf_execute ); $VERSION = 0.01; #setup the stack & global code scalar my @stack; my $stack_ptr = 0; my $thecode; #load a brainfuck sourcefile into the #interpreter sub bf_load_sourcefile { $thecode = ""; open(BF, "@_[0]") || return 0; while(<BF>) { $thecode .= $_; } close(BF); } #execute the given code either given into #this sub, or given by $thecode if no #params are passed to it. sub bf_execute { my $code; if(@_) { $code = shift; } else { $code = $thecode; } $code =~ s/\n|\s//g; my @chars = split(//, $code); my $index = 0; while($index<@chars) { $_ = @chars[$index]; if($_ eq "+") { @stack[$stack_ptr]++; } elsif($_ eq "-") { --@stack[$stack_ptr]; } elsif($_ eq "<") { $stack_ptr-- unless $stack_ptr == 0; } elsif($_ eq ">") { $stack_ptr++; } elsif($_ eq ".") { print chr(@stack[$stack_ptr]); } elsif($_ eq ",") { @stack[$stack_ptr] = ord(<>); } elsif($_ eq "[") { my $end = match_bracket($index, @chars); my $temp_ptr = $stack_ptr; while(@stack[$temp_ptr] > 0) { my $fragment; my $frag_index=$index+1; while($frag_index < $end ) { $fragment .= @chars[$frag_index]; $frag_index++; } #recursively call execute on the code #within the []s bf_execute($fragment); } #make the stack_ptr what it was before the iteration step $stack_ptr = $temp_ptr; $index = $end; } $index++; } } ############################ #private sub used by execute #to match up the open square #brackets with the close one sub match_bracket { my $index = shift; $index++; my @chars = @_; my $num_bracket = 1; while(1) { if(@chars[$index] eq "[") { $num_bracket++; } if(@chars[$index] eq "]" && $num_bracket == 1) { last; } elsif(@chars[$index] eq "]" && $num_bracket != 1) { $num_bracket--; } $index++; } return $index; } 1;
In reply to Brainfuck Interpreter by o(o_o)o
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |