I\'m working on a Perl script that requires some basic menu functionality. Ultimately I would like each menu to have a few options and then the option to either return to th
Following is one approach. Each choice has an associated subroutine. When the choice is made, the corresponding subroutine is called. Here I am using anonymous subroutines but you can also use references to named subroutines.
use warnings; use strict;
sub menu {
my $args = shift;
my $title = $args->{title};
my $choices = $args->{choices};
while (1) {
print "--------------------\n";
print "$title\n";
print "--------------------\n";
for (my $i = 1; $i <= scalar(@$choices); $i++) {
my $itemHeading = $choices->[$i-1][0];
print "$i.\t $itemHeading\n";
}
print "\n?: ";
my $i = ; chomp $i;
if ($i && $i =~ m/[0-9]+/ && $i <= scalar(@$choices)) {
&{$choices->[$i-1][1]}();
} else {
print "\nInvalid input.\n\n";
}
}
}
my $menus = {};
$menus = {
"1" => {
"title" => "Menu 1 header",
"choices" => [
[ "Choice 1" , sub { print "Choice 1 selected"; }],
[ "Choice 2" , sub { print "Choice 2 selected"; }],
[ "Menu 2" , sub { menu($menus->{2}); }],
[ "Exit" , sub { exit; }],
],
},
"2" => {
"title" => "Menu 2 header",
"choices" => [
[ "Choice 3" , sub { print "Choice 3 selected"; }],
[ "Choice 4" , sub { print "Choice 4 selected"; }],
[ "Menu 1" , sub { menu($menus->{1}); }],
[ "Exit" , sub { exit; }],
],
},
};
menu($menus->{1});