Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Re^2: Parsing with perl - Regexes and beyond

by Anonymous Monk
on Sep 18, 2016 at 21:19 UTC ( [id://1172078]=note: print w/replies, xml ) Need Help??


in reply to Re: Parsing with perl - Regexes and beyond
in thread RFC: Parsing with perl - Regexes and beyond

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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1172078]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (9)
As of 2024-03-29 15:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found