You are after a
dispatch table.
#!/usr/bin/perl
use warnings;
use strict;
my @actions = qw( add subtract quit );
my %dispatch = (
add => sub {
my ($x, $y) = map int rand 10, 1, 2;
print "$x + $y = ", $x + $y, "\n";
},
subtract => sub {
my ($x, $y) = map int rand 10, 1, 2;
print "$x - $y = ", $x - $y, "\n";
},
quit => sub { exit },
);
while (1) {
for my $idx (0 .. $#actions) {
print "$idx) $actions[$idx]\n";
}
chomp(my $choice = <>);
$choice = $actions[$choice] if $choice =~ /^[0-9]$/;
if (exists $dispatch{$choice}) {
$dispatch{$choice}->();
next
}
print "Invalid option.\n";
}