CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Intermediate:
Calculator

 



zapzap
User

Feb 15, 2014, 2:00 PM

Post #1 of 4 (1388 views)
Calculator Can't Post

Greetings All!
Hopefully everybody is doing well.

So I have attempted to create a calculator but I feel it can be optimized. If somebody can look over my code and suggest and demonstrate room for improvement I would be thankful as always. I always try to publish a solution even if it is horrible to demonstrate that I have put forth effort of my own.


Code
#!/usr/bin/perl 
use strict;
use warnings;

my @input = ('5','*','9','+','100','/','25','*','2','-','21');
my $result;
while (1) {
for my $index (0..$#input) {
if ($input[$index] =~ m{(\*|/)}) {
$result = eval "$input[$index-1] $1 $input[$index+1]";
splice(@input,$index-1,3,$result);
last;
}
}
last if(join('',@input) !~ m{\*|/});
}

while (1) {
for my $index (0..$#input) {
if ($input[$index] =~ m{(\+|-)}) {
$result = eval "$input[$index-1] $1 $input[$index+1]";
splice(@input,$index-1,3,$result);
last;
}
}
last if(join('',@input) !~ m{\+|-});
}
print "@input\n";


zap


Kenosis
User

Feb 15, 2014, 3:01 PM

Post #2 of 4 (1383 views)
Re: [zapzap] Calculator [In reply to] Can't Post

Why not just:

Code
use strict;  
use warnings;

my @input = ('5','*','9','+','100','/','25','*','2','-','21');
print eval "@input";



BillKSmith
Veteran

Feb 15, 2014, 9:09 PM

Post #3 of 4 (1360 views)
Re: [zapzap] Calculator [In reply to] Can't Post

Kenosis provided an excellent solution to your example, but I doubt that it meets your requirements. What are they? How much memory does your calculator have? Does it care about precedence? What happens if your input exceeds its capability? What functions does it support? How does it get its input? Are there any constraints on speed or memory?
Good Luck,
Bill


Laurent_R
Veteran / Moderator

Feb 16, 2014, 1:57 PM

Post #4 of 4 (1315 views)
Re: [zapzap] Calculator [In reply to] Can't Post

Hi,

just as a side note, using the eval function on user-supplied input can be a major security risk.

The fact that you are partly parsing the input can mitigate the risk to a large extent, but I still would not do it.

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives