Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Brainfunk. With Regex.

by oiskuu (Friar)
on Dec 10, 2013 at 19:06 UTC ( #1066494=perlmeditation: print w/ replies, xml ) Need Help??


my teacher assigned us a brainfuck interpreter[1]. Here's what I've arrived at.

#! /usr/bin/perl ($dpos, $data, $/) = (0, ""); sub data :lvalue { vec($data, $dpos, 8) } <> =~ m{ (?: [>] (?{++$dpos}) | [+] (?{++(data)}) | [.] (?{print chr data}) | [<] (?{--$dpos}) | [-] (?{--(data)}) | [,] (?{data= ord getc}) | [[] (?(?{data})(?0)|(?1)) []] | [^][<>.,+-] )*+\z | (?(?{data})(?0)|(?1)) | \z((?: [^][] | [[] (?1) []])*) }x; BEGIN { *ARGV = *DATA unless @ARGV } __DATA__ +++++[>+++++++++<-],[[>--.++>+<<-]>+.->[<.>-]<<,]

For timing and testing I have used 392quine.b. This, and some other bf programs found here.

I'd say this regex based interpreter is fairly legible and uncomplicated (*cough*), though couple of snags remain.
First and foremost, the unfortunate "recursion" limit is encountered when long (but non-recursing) code is run:
$ perl -w <(perl < Complex regular subexpression recursion limit (32766) exceeded at bf line 5, <> chunk 1. ...
It should output whatever it was fed ( itself), but goes apeshit midway through. The workaround is to use (?:(?:__)*)*; however, I find this just too disgraceful. In this thread, ikegami hints at possible upcoming fix. Well, that was four years ago, and it sure isn't fixed in v5.18.1, let alone v5.12.3. I wonder if this is solved in more recent perls?

Another annoyance is with the data sub. It can be written in several ways

sub data :lvalue { vec($data,$dpos,8) } # v5.16.1--OK; v5.12.3--Fail sub data :lvalue { vec($data,$dpos,8) //= 0 } # OK my @data; sub data :lvalue { $data[$dpos] &= 255 } # OK
The first one appears more expressive, though the array variant is no slower.

Finally, there may well be some important optimizations I've missed or somesuch. Suggestions are welcome, of course.

Comment on Brainfunk. With Regex.
Select or Download Code
Re: Brainfunk. With Regex.
by choroba (Canon) on Dec 10, 2013 at 21:08 UTC
    Get your reward!
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Brainfunk. With Regex.
by ambrus (Abbot) on Dec 11, 2013 at 10:36 UTC

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://1066494]
Approved by hdb
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (6)
As of 2015-03-27 00:43 GMT
Find Nodes?
    Voting Booth?

    When putting a smiley right before a closing parenthesis, do you:

    Results (597 votes), past polls