Why so big? And notice all the modules it takes to parse (snicker :).
It has to be correct because it passes all your test cases :)
#!/usr/bin/perl
# http://perlmonks.org/?node=678124
use strict; # browseruk.pl - modified Pratt parser by tybalt89
use warnings; # https://en.wikipedia.org/wiki/Pratt_parser
sub err { die "ERROR ", s/\G/ <@_> /r, "\n" }
sub expr # two statement parser - precedences: (3 **) (2 * /) (1 + -)
{
my $answer =
/\G\s* - /gcx ? -expr(3) : # unary minus
/\G\s* \+ /gcx ? +expr(3) : # unary plus
/\G\s* \( /gcx ? ( expr(0), /\G\s* \) /gcx || err 'missing )' )[
+0] :
/\G\s* ((?:\d+(?:\.\d*)?|\.\d+)(e[+-]?\d+)?) /gcx ? $1 :
err 'bad operand';
$answer =
/\G\s* \*\* /gcx ? $answer ** expr(3) :
$_[0] > 2 ? return $answer :
/\G\s* \* /gcx ? $answer * expr(3) :
/\G\s* \/ /gcx ? $answer / expr(3) :
$_[0] > 1 ? return $answer :
/\G\s* \+ /gcx ? $answer + expr(2) :
/\G\s* \- /gcx ? $answer - expr(2) : return $answer while 1;
}
for ( @ARGV ? @ARGV : <DATA> ) # source as commandline args or DATA
{
my $answer = expr(0);
/\G\s*\z/gc ? print s/\s*\z/ = $answer\n/r : err 'incomplete parse';
$answer == eval or print "MISMATCH with perl @{[ eval ]}\n";
}
__DATA__
1 + 2
2 - 1
2 * 1
1 / 2
(((7 + 5) * (9 + 13)) / ((4 + 3) * (17 - 2 + 3)))
23 ** 2
1.1e10 ** -10
1 + 2 * 3
3 + 2 ** 2 ** 2 * 3
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|