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

Re: Ksh style select menus in perl

by jdporter (Paladin)
on Aug 01, 2002 at 20:54 UTC ( [id://186932]=note: print w/replies, xml ) Need Help??


in reply to Ksh style select menus in perl

First of all, the implicit looping in ksh's select is completely unnecessary. So too is the way it defaults to using the "positional parameters".

Here's how one might achieve the equivalent in perl:

my @menu = ( "Go left", "Go right" ); for my $i ( 0 .. $#menu ) { print $i+1, ") $menu[$i]\n"; } print "?"; $_ = <>; ($_) = /^(\d+)/; # extract just the digits, if any. $_--; # because the menu as displayed in 1-based. # now do whatever you want with the number in $_ and # the full text of the selected menu item in $menu[$_].
If you want looping, you can add that yourself.

hth, hand.

Replies are listed 'Best First'.
Re^2: Ksh style select menus in perl
by jdporter (Paladin) on Apr 27, 2005 at 17:39 UTC
    I've decided to provide a near-exact reimplementation in Perl. The main differences are that you don't specify the "looping" variable (it uses $_ instead), and the code block comes before the list of choices. This just seems more perlish. One of the fun things about this implementation is that, just like the ksh select statement, it temporarily owns stdin; to exit the loop, you hit ^D (or ^Z on DOS; or as appropriate for your system/terminal).
    sub ksh_select(&@) { my $cr = shift; my $prompt = $ENV{'PS3'} || '#? '; local *ARGV; local $| = 1; local $_; while (1) { for my $i ( 0 .. $#_ ) { print STDOUT $i+1, ") $_[$i]\n"; } print STDOUT $prompt; $_ = <>; defined $_ or return; chomp; $cr->( $_ ); } }
    A simple example usage:
    ksh_select { print "You chose $_\n" } qw( foo bar quux );
    A more realistic example:
    # in this example, the user has choices to navigate around some struct +ure. my %dispatch = ( First => \&goto_first, Prev => \&goto_prev, Next => \&goto_next, Last => \&goto_last, ); my @menu = qw( First Prev Next Last ); ksh_select { defined $menu[$_] ? $dispatch{$menu[$_]}->() : warn "Selection out of range!\n"; } @menu;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2024-04-24 00:34 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found