CUFP
o(o_o)o
well... i think this is cool even if you don't :p ... I've become interested in the esoteric languages Brainfuck and Befunge after getting enthusiastic about Obfuscated code, and have decided to make this Perl-Module which interprets Brainfuck code so that i can put brainfuck bit's into my programs for no reason but bordom ;)
<br><br>
i'm very happy with it.. i've tested it quite a bit and am very confident on it's accuracy, but if someone finds something wrong with it i shall aim to fix the problem :) It was quite easy to implement really, but i'm a newbie/rubbish programmer :p The only hard bit was the iteration step which i rightfully took as recursion..
<br><br>
<B>usage:</b>
<code>use Brainfuck;
bf_execute(">++++[<++++>-]<+++[->++++<]+
++[>---<-]++[>+.<-]>[>+>+<<-
]>----.>-.>++++[<+++>-]<--.<
.[-]+++++++[->+<]>.-.");
or
bf_load_sourcefile("asourcefile.b");
bf_execute();
</code>
<b>here's the code:</b>
<code>
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;
</code>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~<br/>
i would slit my wrists for you