Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Simple text menu

by Juerd (Abbot)
on Dec 29, 2002 at 00:57 UTC ( [id://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?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2024-04-23 12:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found