in reply to Inputing an Operator is it possible?
A Calculator might be a bad task as "one of your first programs", because parsing mathematical expressions is an advanced challenge, but you can do it in steps, getting better and better. First idea is getting operand,operator,operand as single unput:
chomp(my $left = <STDIN>); chomp(my $op = <STDIN>); chomp(my $right = <STDIN>); print $op eq '+' ? $left + $right : $op eq '-' ? $left - $right : $op eq '*' ? $left * $right : $op eq '/' ? $left / ($right||1) : "dunno operator '$op'", , "\n";
Next step is to read the whole thing in a one string:
chomp( my $expr = <STDIN> ); # and to parse it with simple split my ($left,$op,$right) = split /\s+/,$expr # next step is code of above
Sooner or later you'll want to replace the ?:?: .. chain with a hash:
my %operations = ( '+' => sub { (shift) + (shift) }, '-' => sub { (shift) - (shift) }, '*' => sub { (shift) * (shift) }, '/' => sub { (shift) / (shift||1) }, ); my ($left,$op,$right) = ...; #wherever you get them from print exists $operations{$op} ? $operations{$op}->($left,$right) : "dunno operator '$op'", "\n";
Next you want to verify the input using a regexp:
chomp(my $expr = <STDIN>); $expr =~ /(\d+)\s+([+-/*])\s+(\d+)/ or die "invalid input\n"; my ($left,$op,$right) = ($1,$2,$3); # ...
Then you'll find advanced regexps for numbers (see perlfaq4), Math::Expr, and finally Parse::RecDescent .
--
|
|---|