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: Beginner: Re: [dannyb_16] Writing a Calculator : Edit Log



Zhris
Enthusiast

Oct 5, 2013, 11:39 PM


Views: 2687
Re: [dannyb_16] Writing a Calculator

Hi,

Just for reference...

1) It would be nice if the user could enter a single calculation as oppose to two numbers and an operation separately.

2) If lots of operations, then it would be nice to lookup the specific properties of the operation as oppose to a set of if/elsif conditions. This way we can add or adapt operations with ease.

Here is my version of your script:


Code
#!/usr/bin/perl 
use strict;
use warnings FATAL => qw/all/;

# op regexp, op override, calculation handler
my @properties =
(
[ qr{^(\+|plus|add)$}i , '+', sub {$_[0]+$_[1]} ],
[ qr{^(\-|minus|subtract)$}i, '-', sub {$_[0]-$_[1]} ],
[ qr{^(\*|times|multiply)$}i, '*', sub {$_[0]*$_[1]} ],
[ qr{^(\/|divide)$}i , '/', sub {$_[0]/$_[1]} ],
);
print "enter calculation...\n";
chomp(my $calc = <STDIN>);
my $err = "'$calc' is invalid\n";
my ($num1, $op, $num2, $ref);
die $err unless (($num1, $op, $num2) = $calc =~ m{^\s*(\d+)\s*(.+?)\s*(\d+)\s*$});
die $err unless (($ref) = grep { $op =~ $_->[0] } @properties);
print "$num1 $ref->[1] $num2 = ", $ref->[2]->($num1, $num2), "\n";


Another nice way to perform a calculation is using Perl's eval, although risky if the calculation comes from an untrusted source (could be protected by using the safe module). We can enter long complex calculations which fulfill the regexp, without having to provide specific properties for each operation:


Code
#!/usr/bin/perl  
use strict;
use warnings FATAL => qw/all/;

print "enter calculation...\n";
chomp(my $calc = <STDIN>);
my $err = "'$calc' is invalid\n";
die $err if $calc =~ m{[^\d\s()+*/-]};
my $res = eval $calc // die $err;
print "$calc = $res\n";


Chris


(This post was edited by Zhris on Oct 5, 2013, 11:55 PM)


Edit Log:
Post edited by Zhris (Enthusiast) on Oct 5, 2013, 11:40 PM
Post edited by Zhris (Enthusiast) on Oct 5, 2013, 11:55 PM


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

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