Skip to content

Instantly share code, notes, and snippets.

@xy4n
Created February 17, 2014 16:27
Show Gist options
  • Save xy4n/9053842 to your computer and use it in GitHub Desktop.
Save xy4n/9053842 to your computer and use it in GitHub Desktop.
brainfuck.pl
#!/usr/bin/env perl
use warnings;
use strict;
use feature qw/switch/;
open my $stream, $ARGV[0] or die "Can't open file: $!";
my $size = 3000;
my @cells = (1..$size);
my $mptr = 0;
my $cptr = 0;
my @loops;
for my $i (0..scalar(@cells)-1) {
$cells[$i] = 0;
}
my $input = "";
while (<$stream>) {
chomp;
$input .= $_;
}
$input =~ s/[^\+\-\.\[\],<>]//g;
my $lleft = scalar(grep(/[\[]/, $input));
my $lright = scalar(grep(/[\]]/, $input));
die "Syntax error!" if $lleft != $lright;
while ($cptr < length($input)) {
my $c = substr($input, $cptr, 1);
$cptr++;
given ($c) {
when ("<") { if ($mptr == 0) {$mptr = $size;} else {$mptr--;} }
when (">") { if ($mptr == $size) {$mptr = 0;} else {$mptr++;} }
when ("+") { if ($cells[$mptr] == 255) {$cells[$mptr] = 0;} else {$cells[$mptr]++;} }
when ("-") { if ($cells[$mptr] == 0) {$cells[$mptr] = 255;} else {$cells[$mptr]--;} }
when (".") { print chr($cells[$mptr]); }
when (",") { $cells[$mptr] = ord(substr(<STDIN>,0,1)); }
when ("[") { push @loops, $cptr; }
when ("]") {
if ($cells[$mptr] != 0) {
$cptr = $loops[scalar(@loops)-1];
} else {
pop @loops;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment