in reply to Re: '+' to +
in thread '+' to +

I really like this solution, and decided to play around with it a little. Here it is with a little enhancement...

use warnings; use strict; my %arith; $arith{"+"} = sub { $_[0] + $_[1] }; $arith{"-"} = sub { $_[0] - $_[1] }; $arith{"*"} = sub { $_[0] * $_[1] }; $arith{"/"} = sub { $_[0] / $_[1] }; my $problem = "6 + 1"; my $answer; if ( $problem =~ /^(\d+)\s*(\S)\s*(\d+)$/ and exists $arith{$2} ) { eval { $answer = $arith{$2}->( $1, $3 ); } } else { die "Oops!\nOperation syntax not understood.\n"; } die "Woops!\n$@" if $@; print "$answer\n";

It's a long way from being a full fledged algeraic expression parser, but it is a little more robust.


Dave