in reply to World Builder: the recovery and archeology of old programs.
My first crack at this may be more comprehensible:
use Scalar::Util qw( looks_like_number ); use List::Util qw( first ); my @menu = ( 'Known star', 'Create a new star', 'List Known Stars', 'Q +uit' ); my $input = '...'; my $picked; if ( looks_like_number $input ) { $picked = $menu[ $input - 1 ]; } else { $picked = first { length $input <= length $_ and lc $input eq lc substr $_, 0, length $input; } @menu; } if ( !defined $picked ) { die "What do you mean by '$input'?"; }
Basically, if the input looks like a number, it's used as an index into the array of menu items. Otherwise, it loops through the menu looking for the first thing that "matches" the input.
My rewrite made this more useful as a menu in real code. Each menu item is now a hash ref that has a reference to a sub to handle the menu item. If need be, you can add more "stuff" to each hash ref. For example, maybe instead of substrings, you want to have regular expressions match the user's input. In that case, you could have a qr// stuck on each one used in the first loop instead of lc substr.
use Scalar::Util qw( looks_like_number ); use List::Util qw( first ); my @menu = ( { title => 'Known star', handler => \&load_star }, { title => 'Create a new star', handler => \&create_star }, { title => 'List Known Stars', handler => \&list_stars }, { title => 'Quit', handler => sub { exit } } ); my $input = '...'; my $picked; if ( looks_like_number $input ) { $picked = $menu[ $input - 1 ]; } else { $picked = first { length $input <= length $_->{title} and lc $input eq lc substr $_->{title}, 0, length $input; } @menu; } if ( !defined $picked ) { die "What do you mean by '$input'?"; } # "call" the menu item $picked->{handler}->();
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: World Builder: the recovery and archeology of old programs.
by dwm042 (Priest) on Sep 17, 2008 at 16:51 UTC | |
by dwm042 (Priest) on Feb 04, 2009 at 15:36 UTC | |
|
Re^2: World Builder: the recovery and archeology of old programs.
by psini (Deacon) on Sep 17, 2008 at 16:27 UTC | |
by kyle (Abbot) on Sep 17, 2008 at 16:35 UTC |