
Zhris
Enthusiast
Oct 5, 2013, 11:39 PM
Post #3 of 4
(2511 views)
|
Re: [dannyb_16] Writing a Calculator
[In reply to]
|
Can't Post
|
|
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:
#!/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:
#!/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)
|