BF Interpreter
aweeraman
created: 2006-03-08 17:02:00
Here's a very trivial BF interpreter. Its written in as few lines as possible while trying to keep it readable. It expects BF code on standard input.
#!/usr/bin/perl

$cd .= $_ while ();

sub get_char {
	exit if ($ch_ptr == length($cd));
	return substr($cd, $ch_ptr++, 1);
}

while (1) {
	$ch = get_char;
	$cell[$cl_ptr]++ if ($ch eq '+');
	$cell[$cl_ptr]-- if ($ch eq '-');
	(($_ = chr($cell[$cl_ptr])) && print) if ($ch eq '.');
	$cl_ptr++ if ($ch eq '>');
	$cl_ptr-- if ($ch eq '<');
	if ($ch eq ',') {
		$inp_ch = getc(STDIN);
		$cell[$cl_ptr] = ord($inp_ch);
	} elsif ($ch eq '[') {
		($ch_ptr = index($cd, ']', $ch_ptr)) if ($cell[$cl_ptr] == 0);
	} elsif ($ch eq ']') {
		($ch_ptr = rindex($cd, '[', $ch_ptr)) if ($cell[$cl_ptr] != 0);
	}
}
Re: BF Interpreter
created: 2006-03-08 17:38:14

Not bad, not bad...

{
	my $cd = join '', <>;
	my $ch_ptr = 0;

	sub get_char
	{
		exit if $ch_ptr == length $cd;
		substr $cd, $ch_ptr++, 1;
	}
	sub jump_ahead
	{
		$ch_ptr = index $cd, ']', $ch_ptr
	}
	sub jump_behind
	{
		$ch_ptr = rindex $cd, '[', $ch_ptr
	}
}

my @cell;
my $cl_ptr = 0;

my %disp = (
	'+' => sub { $cell[$cl_ptr]++ },
	'-' => sub { $cell[$cl_ptr]-- },
	'.' => sub { print chr($cell[$cl_ptr]) },
	'>' => sub { $cl_ptr++ },
	'<' => sub { $cl_ptr-- },
	',' => sub { $cell[$cl_ptr] = ord( getc() ) },
	'[' => sub { jump_ahead() if $cell[$cl_ptr] == 0 },
	']' => sub { jump_behind() if $cell[$cl_ptr] != 0 },
);

($disp{get_char()} or sub{})->() while 1;
We're building the house of the future together.
Re^2: BF Interpreter
created: 2006-03-09 17:48:49
Another varation:
$cd .= $_ while ;

sub jump_ahead {
        (($ch_ptr = index($cd, ']', $ch_ptr))) if (!$cell[$cl_ptr]);
}

sub jump_behind {
        (($ch_ptr = rindex($cd, '[', $ch_ptr))) if ($cell[$cl_ptr]);
}

while (1) {
        exit if ($ch_ptr == length($cd));
        $ch = substr($cd, $ch_ptr++, 1);

        ($ch eq '>') && $cl_ptr++;
        ($ch eq '<') && $cl_ptr--;
        ($ch eq '+') && $cell[$cl_ptr]++;
        ($ch eq '-') && $cell[$cl_ptr]--;
        ($ch eq '.') && (($_ = chr($cell[$cl_ptr])) && print);
        ($ch eq ',') && ($cell[$cl_ptr] = ord(getc));
        ($ch eq '[') && jump_head;
        ($ch eq ']') && jump_behind;
}
Although I prefer your version :)
Re^3: BF Interpreter
created: 2006-03-10 18:38:57
Typo. s/jump_head/jump_ahead/
Re: BF Interpreter
created: 2006-03-09 04:33:37

Dropping readable part, you may check results here, or this thread

Also, does your interpreter support nested []?

perlmonks.org content © perlmonks.org and aweeraman, jdporter, mtve

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03