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 (<STDIN>); 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) +; } }

Replies are listed 'Best First'.
Re: BF Interpreter
by jdporter (Paladin) on Mar 08, 2006 at 22:38 UTC

    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.
      Another varation:
      $cd .= $_ while <STDIN>; 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 :)
        Typo. s/jump_head/jump_ahead/
Re: BF Interpreter
by locked_user mtve (Deacon) on Mar 09, 2006 at 09:33 UTC

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

    Also, does your interpreter support nested []?