#!/usr/bin/perl
use strict;
use warnings;
use Tk;

### This program demonstrates both the original solution and the bonus
### To get just original functionality, remove all the 'bind' commands.
### To get just the bonus functionality, remove the $eq_btn button widget

my $mw = MainWindow->new();
$mw->geometry('800x600');

my ($num1, $num2, $op, $result);

my $num1_ent = $mw->Entry(-textvariable => \$num1);
my $num2_ent = $mw->Entry(-textvariable => \$num2);
my $ops_frm = $mw->Frame();
for my $op_choice (qw{+ - / *}) {
	my $op_rad = $ops_frm->Radiobutton(-text => $op_choice, -variable=>\$op, -value=>$op_choice);
	$op_rad->pack();
	$op_rad->bind('<Button-1>' => \&calculate);
	$op_rad->bind('<Key-space>' => \&calculate);
}

my $eq_btn = $mw->Button(-text=>'=', -command=>\&calculate);
my $answer_lbl = $mw->Label(-textvariable => \$result);

$num1_ent->grid($ops_frm, $num2_ent, $eq_btn, $answer_lbl);
for my $ent ($num1_ent, $num2_ent) {
	$ent->bind('<Key>' => \&calculate);
}

MainLoop;

sub calculate {
	if (!defined $num1 or !defined $num2 or !defined $op or $num1 !~ /^[+-]?\d+(?:\.\d+)?$/ or $num2 !~ /^[+-]?\d+(?:\.\d+)?$/) {
		$result = "Invalid args";
	} elsif ($op eq '/' and $num2 == 0) {
		$result = 'Infinity';
	} else {
		$result = eval "$num1 $op $num2";
	}
}