# THE CODE ############################# #!/usr/bin/perl -w # a simple text-based menu system use strict; my ($menu1, $menu2); # Sample menus are defined below. Each menu is an anonymous # array. The first element is the title of the menu. The following # elements are anonymous arrays containing a description of the # menu item (it will be printed) and a reference to a routine to call # should that item be selected. # The following is a shortcut that can be used in other menus. my $quit_menu_item = [ "Quit", sub{exit;} ]; $menu1 = [ "Title of First Menu", [ "Do Something (first)", \&ds1 ], [ "Second Menu", sub{ &menu( $menu2 )} ], [ "Continue", sub {}], [ "Quit", sub {exit;} ], # We could have used our shortcut. ]; $menu2 = [ "Title of Second Menu", [ "Do Something (second)", \&ds2 ], [ "First Menu", sub{ &menu( $menu1 )} ], $quit_menu_item, # This is our shortcut. ]; ##### The menu routine itself. ##### sub menu { my $m = shift; my $choice; while (1) { print "$m->[0]:\n"; print map { "\t$_. $m->[$_][0]\n" } (1..$#$m); print "> "; chomp ($choice = <>); last if ( ($choice > 0) && ($choice <= $#$m )); print "You chose '$choice'. That is not a valid option.\n\n"; } &{$m->[$choice][1]}; } print "a\n"; # Do something 1 sub ds1 { print "\nIn ds1\n\n"; &menu($menu1); print "In ds1 after return to menu \n"; } print "b\n"; # Do something 2 sub ds2 { print "\nIn ds2\n\n"; &menu($menu2); print "In ds2 after return to menu \n"; } print "c\n"; ## TEST &menu($menu1); print "Continue after menu call \n"; # THE CONSOLE ############################# a b c Title of First Menu: 1. Do Something (first) 2. Second Menu 3. Continue 4. Quit > 1 In ds1 Title of First Menu: 1. Do Something (first) 2. Second Menu 3. Continue 4. Quit > 1 In ds1 Title of First Menu: 1. Do Something (first) 2. Second Menu 3. Continue 4. Quit > 2 Title of Second Menu: 1. Do Something (second) 2. First Menu 3. Quit > 1 In ds2 Title of Second Menu: 1. Do Something (second) 2. First Menu 3. Quit > 1 In ds2 Title of Second Menu: 1. Do Something (second) 2. First Menu 3. Quit > 2 Title of First Menu: 1. Do Something (first) 2. Second Menu 3. Continue 4. Quit > 3 In ds2 after return to menu In ds2 after return to menu In ds1 after return to menu In ds1 after return to menu Continue after menu call