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;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Brainfuck Interpreter
by Juerd (Abbot) on Mar 13, 2002 at 08:11 UTC | |
by tomhukins (Curate) on Mar 13, 2002 at 12:54 UTC | |
by Juerd (Abbot) on Mar 13, 2002 at 13:31 UTC | |
by o(o_o)o (Scribe) on Mar 13, 2002 at 15:33 UTC | |
by o(o_o)o (Scribe) on Mar 13, 2002 at 16:15 UTC | |
|
Re: Brainfuck Interpreter
by patgas (Friar) on Mar 13, 2002 at 16:49 UTC | |
by broquaint (Abbot) on Apr 18, 2002 at 11:01 UTC | |
|
Re: Brainfuck Interpreter
by kluzz (Initiate) on Apr 18, 2002 at 10:21 UTC | |
|
Re: Brainfuck Interpreter
by Bobcat (Scribe) on Apr 04, 2002 at 03:10 UTC |