#!/usr/bin/perl use strict; use warnings; use feature qw(say); local $\ = "\n"; my %math = ( 'addition' => { 'result' => 'sum', 'operator' => '+', 'function' => sub {my ($i,$j) = @_; return $i + $j}, }, 'subtraction' => { 'result' => 'difference', 'operator' => '-', 'function' => sub {my ($i,$j) = @_; return $i - $j}, }, 'multiplication' => { 'result' => 'product', 'operator' => '*', 'function' => sub {my ($i,$j) = @_; return $i * $j}, }, 'division' => { 'result' => 'quotient', 'operator' => '/', 'function' => sub {my ($i,$j) = @_; return $i / $j}, }, ); my $operation = (keys %math)[rand keys %math]; sub random_number { return 1 + int(rand(7)); } my $random_number_1 = random_number(); my $random_number_2 = random_number(); sub math_answer { my ($answer,$loop) = @_; my $result = int($math{$operation}{'function'}->($random_number_1,$random_number_2)); my $equation = qq($random_number_1 $math{$operation}{'operator'} $random_number_2); if ($answer eq "hint") { print $equation; my $user_answer = <>; math_answer($user_answer,1); } elsif ($answer == $result) { print "True"; } else { if ($loop == 1) { print "False, why don't you try again? The equation is $equation."; my $user_answer = <>; math_answer($user_answer,++$loop); } else { print "False, the answer is $result."; } } } print qq(What is the $math{$operation}{'result'} of $random_number_1 and $random_number_2 to the nearest integer? (type "hint" to show the equation)); my $user_answer = <>; chomp $user_answer; math_answer($user_answer,1);