Do you mean something like this?
https://rosettacode.org/wiki/Compiler/AST_interpreter#Perl
This reads in a flattened Abstract Syntax Tree (AST)
and generates from it a tree of perl objects it can
then run with a simple ->run method and polymorphism.
This does have a hash %variables that is shared between several of the subs in different packages(classes).
There is also this, a simpler tree based expression parser and evaluator that again
uses perl polymorphism to calculate a result from a tree of objects. I'm considering submitting this to
https://rosettacode.org/wiki/Arithmetic_evaluation
but I'm not sure if I will.
#!/usr/bin/perl
use strict; # https://rosettacode.org/wiki/Arithmetic_evaluation
use warnings;
sub node { bless [ splice @_, 1 ], shift }
sub error { die s/\G.*//sr =~ tr/\t/ /cr, "^ $_[0] !\n" }
sub want { /\G$_[1]/gc ? shift : error pop }
sub expr
{
/\G\h+/gc;
my $tree =
/\G\d+/gc ? node NUMBER => $& :
/\G\(/gc ? want expr(0), qr/\)/, 'Missing Right Paren' :
error 'Operand Expected';
$tree =
/\G\h+/gc ? $tree :
$_[0] <= 0 && /\G\+/gc ? node ADD => $tree, expr(1) :
$_[0] <= 0 && /\G\-/gc ? node SUBTRACT => $tree, expr(1) :
$_[0] <= 1 && /\G\*/gc ? node MULTIPLY => $tree, expr(2) :
$_[0] <= 1 && /\G\//gc ? node DIVIDE => $tree, expr(2) :
return $tree while 1;
}
sub ADD::value { $_[0][0]->value + $_[0][1]->value }
sub SUBTRACT::value { $_[0][0]->value - $_[0][1]->value }
sub MULTIPLY::value { $_[0][0]->value * $_[0][1]->value }
sub DIVIDE::value { $_[0][0]->value / $_[0][1]->value }
sub NUMBER::value { $_[0][0] }
sub NUMBER::show { "$_[0][0]\n" }
sub UNIVERSAL::show
{ ref($_[0]) . "\n" . join('', map $_->show, @{$_[0]}) =~ s/^/ /g
+mr }
while( <DATA> )
{
eval
{
print;
my $tree = want expr(0), "\n", 'Incomplete Parse';
print $tree->show, "value of tree = ", $tree->value, "\n\n";
} or print "$@\n";
}
__DATA__
(1+3)*7
42 +
( 33 + ( 7 * 8 )
123 456
foobar
7 / foobar
7 foobar
10 - 3 - 1
10 - (3 - 1)
2 * 3 + 4 * 5
2 + 3 * 4 + 5
((((( 7 / 4 )))))
((((( 7 / 4 ))))))))
2 + (3 + 4 no_names_allowed )
7 )
1 + 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.