in reply to Help with simple calculator script.
If those few operations are all you need, there's nothing wrong with the if/else dispatching above. However, if you ever want to extend it to other mathmatical operations, I'd use a dispatch table:
my %OPERATIONS = ( '*' => sub { $_[0] * $_[1] }, '-' => sub { $_[0] - $_[1] }, '+' => sub { $_[0] + $_[1] }, ); # $operator, $first, and $second defined # elsewhere, from user input print "Result: ", $OPERATIONS{$operator}->($first, $second), "\n" if exists $OPERATIONS{$operator};
Also, avoid using $a and $b as variable names, as they have special meaning in sort subroutines.
----
I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
-- Schemer
:(){ :|:&};:
Note: All code is untested, unless otherwise stated
|
|---|