From 2a933bff8753d4986337c5b8c38cbb0cb8262bb6 Mon Sep 17 00:00:00 2001 From: Pragmatic Software Date: Mon, 24 Mar 2014 02:25:37 +0000 Subject: [PATCH] Improve math.pl to support specific math functions (e.g., sqrt, etc) --- PBot/VERSION.pm | 4 ++-- modules/math.pl | 40 +++++++++++++++++++++++++++++++--------- 2 files changed, 33 insertions(+), 11 deletions(-) diff --git a/PBot/VERSION.pm b/PBot/VERSION.pm index a28b7220..d1fa562d 100644 --- a/PBot/VERSION.pm +++ b/PBot/VERSION.pm @@ -13,8 +13,8 @@ use warnings; # These are set automatically by the build/commit script use constant { BUILD_NAME => "PBot", - BUILD_REVISION => 531, - BUILD_DATE => "2014-03-22", + BUILD_REVISION => 532, + BUILD_DATE => "2014-03-23", }; 1; diff --git a/modules/math.pl b/modules/math.pl index ae9ceb66..eca5783e 100755 --- a/modules/math.pl +++ b/modules/math.pl @@ -2,22 +2,44 @@ # Quick and dirty by :pragma +my ($arguments, $response, $invalid); -my ($arguments, $response); +my @valid_keywords = ( + 'sin', 'cos', 'tan', 'atan', 'exp', 'int', 'hex', 'oct', 'log', 'sqrt', + 'floor', 'ceil', 'asin', 'acos', 'log10', 'sinh', 'cosh', 'tanh', 'abs', + 'pi' +); if ($#ARGV < 0) { print "Dumbass.\n"; - die; + exit 0; } -$arguments = join(" ", @ARGV); +$arguments = join(' ', @ARGV); -if($arguments =~ m/[\$a-z]/i) -{ - print("Illegal characters, please only use numbers and valid operators (+, -, /, *, etc)."); - die(); +if($arguments =~ m/([\$`\|])/) { + $invalid = $1; +} else { + while($arguments =~ /([a-zA-Z]+)/g) { + my $keyword = $1; + $invalid = $keyword and last if not grep { /^$keyword$/ } @valid_keywords; + } } -$response = eval($arguments); -print "$arguments = $response"; +if($invalid) { + print "Illegal symbol '$invalid' in equation\n"; + exit 1; +} + +$response = eval("use POSIX qw/ceil floor/; use Math::Complex;" . $arguments); + +if($@) { + my $error = $@; + $error =~ s/ at \(eval \d+\) line \d+.//; + $error =~ s/[\n\r]+//g; + print $error; + exit 1; +} + +print "$arguments = $response\n";