in reply to Parse user-entered expressions into subs for an awk-like program
On the face of it something as simple as:
use strict; use warnings; my %hash = (a => 1, b => 0, c => 3); while (<DATA>){ chomp; s/(\w+)/\$hash{$1}/g; my $ans = eval "$_"; if ($@) { print "Eval of $_ failed:\n $@\n"; } else { print "$_ = $ans\n"; } } __DATA__ a/b b+c c*a/(b+a)
which prints:
Eval of $hash{a}/$hash{b} failed: Illegal division by zero at (eval 10)[noname.pl:10] line 1, <DATA> +line 1. $hash{b}+$hash{c} = 3 $hash{c}*$hash{a}/($hash{b}+$hash{a}) = 3
does what you want. So where is the tricky part? Why do you need subs? If you need to reuse the expression store away the "parsed" version.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Parse user-entered expressions into subs for an awk-like program
by xaprb (Scribe) on Jan 28, 2007 at 22:06 UTC | |
by ysth (Canon) on Jan 28, 2007 at 22:38 UTC | |
by GrandFather (Saint) on Jan 28, 2007 at 22:52 UTC | |
by ysth (Canon) on Jan 28, 2007 at 23:53 UTC |