Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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

In reply to Re^2: Parsing with perl - Regexes and beyond by Anonymous Monk
in thread RFC: Parsing with perl - Regexes and beyond by moritz

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (6)
As of 2024-03-28 23:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found