Sample Recursive Descent Parser



1   Overview
2   Usage
3   Browse the code
4   Get the code

1. Overview.

This page provides a sample CLI calculator written in pure Perl 5.

The point of the program is to illustrate the structure of a simple math parser. A recursive-descent approach is used; the core consists of a single recursive routine (ParseMath).


  • No non-core CPAN modules or external parser tools or libraries are required.

  • PEMDAS compliant.

  • Supports standard four operators plus ** (exponentiation), some math functions (sqrt, cbrt, log, sin, cos, and tan), a few symbolic constants (e, phi, and pi).

  • Real numbers may optionally use scientific notation.

2. Usage.

Usage: parsemath “1.5+(2/3)*pi-sqrt(2)”

This is a CLI calculator program that takes a single arithmetic expression as an argument, evaluates it, and prints the result to standard output.

As a general rule, expressions should be quoted as shown here. Otherwise, “shell meta-character” problems may occur.

Numbers may be integers, ordinary real numbers, or real numbers in scientific notation. Examples of scientific notation: 1.3e+0 is equal to 1.3, 12e-1 is equal to 1.2, and 5e+1 is equal to 50. The + sign is optional in this context.

Supported operators include + (add), - (subtract or unary minus), * (multiply), / (divide), and ** (exponentiate).

Six functions are supported: sqrt (square root), cbrt (cube root), log (natural logarithm), sin, cos, and tan. The last three functions take angles in radians.

Three standard constants may be used: e, phi (the Golden Ratio), and pi.

3. Browse the code.

To browse the source code, click here.

4. Get the code.

To download everything that's available, right-click on this ZIP-file link and save the ZIP file to disk.

Hosting provided by Zymic.

For acknowledgments related to CSS and other code used, click here.

Linked or embedded works (software, books, articles, etc.) are presented under their own licenses.

Other unique content on this page, excluding screenshots, is distributed under the following license: C.C. Attribution NonCommercial ShareAlike 3.0. In some cases, screenshots are distributed under the same license. In other cases, the associated program's license applies.

image Valid XHTML 1.0