Home: Perl Programming Help: Intermediate:
Calculator



zapzap
User

Feb 15, 2014, 2:00 PM


Views: 4305
Calculator

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


Views: 4300
Re: [zapzap] Calculator

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


Views: 4277
Re: [zapzap] Calculator

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


Views: 4232
Re: [zapzap] Calculator

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.