in reply to BF Interpreter

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.

Replies are listed 'Best First'.
Re^2: BF Interpreter
by aweeraman (Novice) on Mar 09, 2006 at 22:48 UTC
    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/