The good thing about this technique is that if you want to add an operation, say exponentiation, you only need to add one single line of code in the dispatch table (well, plus one line in your menu option). In addition, the return statement is not needed in the subs defined in the dispatch table (a function returns the last evaluated expression), so that the dispatch table could be:#!/usr/bin/perl use strict; use warnings; print"###simple calculator program##\n\n"; my $opt2 = "y"; my %operations = ( "+" => sub { return $_[0] + $_[1]}, "-" => sub { return $_[0] - $_[1]}, "*" => sub { return $_[0] * $_[1]}, "/" => sub { return $_[0] / $_[1]} ); while ($opt2 eq "y"){ print "enter the first number\n"; chomp( my $num1 = <> ); print "enter the second number\n"; chomp( my $num2 = <> ); print "enter your option\n\+ for addition\n\- for subtraction\n\* +for multiplication\n\/ for divison\n option:"; chomp(my $opt = <>); print "you have entered wrong option\n" and next unless defined $o +perations{$opt}; print "you pressed the $opt key\n"; print $operations{$opt}->( $num1, $num2), "\n\n"; print "do you want to continue press y or n?\n"; chomp ($opt2 =<>); }
.my %operations = ( "+" => sub { $_[0] + $_[1]}, "-" => sub { $_[0] - $_[1]}, "*" => sub { $_[0] * $_[1]}, "/" => sub { $_[0] / $_[1]}, "**" => sub { $_[0] ** $_[1]} );
In reply to Re: help me to find out the error??
by Laurent_R
in thread help me to find out the error??
by dacka
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |