Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Simple text menu

by Juerd (Abbot)
on Dec 29, 2002 at 00:57 UTC ( #222832=note: print w/replies, xml ) Need Help??


in reply to Simple text menu

Based on your code, but made recursive, and with less array references:

#!/usr/bin/perl -w use strict; sub foo { print "FOO!\n" } sub bar { print "BAR!\n" } sub menu { my ($menu) = @_; for (;;) { print "\n$menu->[0]\n"; print map "$_. $menu->[$_ * 2 - 1]\n", 1 .. $#$menu / 2; print '> '; chomp (my $choice = readline *STDIN); if ($choice and $choice <= $#$menu / 2) { my $action = \$menu->[$choice * 2]; return if not defined $action; $action->() if ref $action eq 'CODE'; menu $action if ref $action eq 'ARRAY' } else { print "Invalid choice: $choice\n" } } } my ($mainmenu, $submenu); $mainmenu = [ 'Main menu', 'Foo' => \&foo, 'Submenu...' => sub { menu $submenu }, 'Exit' => undef, ]; $submenu = [ 'Submenu', 'Bar', => \&bar, 'Back to previous menu' => undef, ]; menu $mainmenu;
Update
Aristotle++ has a very good point with the arrayref used as action, so I used Acme::Magpie to steal it :)
menu [ 'Main menu', 'Foo' => \&foo, 'Submenu...' => [ 'Submenu', 'Bar', => \&bar, 'Back to previous menu' => undef, ], 'Exit' => undef, ];

- Yes, I reinvent wheels.
- Spam: Visit eurotraQ.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://222832]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2023-02-08 07:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    I prefer not to run the latest version of Perl because:







    Results (40 votes). Check out past polls.

    Notices?