Grammar with error handling


examples/regex2/Add2.pm
grammar Add2 {
	rule TOP { ^ <math> $ }
	rule math { 
		<operand>
		[ <operator> || {die "missing operator"} ] 
		[ <operand> || { die "Missing second operand" } ]
		[ \S { die "Invalid value after the second operand" } ]?
	}
	token operand { \d+ }
	token operator { <[\+\*]> || \D { die "Invalid operator" } }
}

examples/regex2/Add2.pm.out
2 + 3 OK
2 + 4  OK
2 + 3 x exception received: Invalid value after the second operand
2 + exception received: Missing second operand
2 3 exception received: missing operator
2 - 3 exception received: Invalid operator

Copyright 2006, 2007, 2008, 2009, 2010 Gabor Szabo http://szabgab.com/ Index | TOC
If you are interested in on-site trainings by the author, please contact me directly.

Online courses:

Would you like to get
updated when I publish
the next article?

Follow me:

Google Plus Twitter RSS feed