=pod

=head1 NAME

Shell::POSIX::Select - The POSIX Shell's "select" loop for Perl

=head1 ALERT

Unfortunately, this module is difficult to install on many modern platforms. However, there is a package that installs easily on Debian and Ubuntu-based systems (and with some effort, possibly others), which you can find at http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=libshell-posix-select.

=head1 PURPOSE

This module implements the C<select> loop of the "POSIX" shells (Bash, Korn, and derivatives)
for Perl.
That loop is unique in two ways: it's by far the friendliest feature of any UNIX shell,
and it's the I<only> UNIX shell loop that's missing from the Perl language.  Until now!

What's so great about this loop? It automates the generation of a numbered menu
of choices, prompts for a choice, proofreads that choice and complains if it's invalid
(at least in this enhanced implementation), and executes a code-block with a variable
set to the chosen value.  That saves a lot of coding for interactive programs --
especially if the menu consists of many values!

The benefit of bringing this loop to Perl is that it obviates the
need for future programmers
to reinvent the I<Choose-From-A-Menu> wheel.

=head1 SYNOPSIS

=for comment
Resist temptation to add more spaces in line below; they cause bad wrapping for text-only document version
 
=for comment
The damn CPAN html renderer, which doesn't respond to
 =for html or =for HTML directives (!), can't get the following
 right!  It's showing the B<> codes!  Postscript and text work fine.
B<select>
[ [ my | local | our ] scalar_var ]
B<(> [LIST] B<)>
B<{> [CODE] B<}>

select [ [my|local|our] scalar_var ] ( [LIST] ) { [CODE] }

In the above, the enclosing square brackets I<(not typed)> identify optional elements, and vertical bars separate mutually-exclusive choices:

The required elements are the keyword C<select>,
the I<parentheses>, and the I<curly braces>.
See L<"SYNTAX"> for details.

=head1 ELEMENTARY EXAMPLES

NOTE: All non-trivial programming examples shown in this document are
distributed with this module, in the B<Scripts> directory.
L<"ADDITIONAL EXAMPLES">, covering more features, are shown below.

=head2 ship2me.plx

    use Shell::POSIX::Select;

    select $shipper ( 'UPS', 'FedEx' ) {
        print "\nYou chose: $shipper\n";
        last;
    }
    ship ($shipper, $ARGV[0]);  # prints confirmation message

B<Screen>

    ship2me.plx  '42 hemp toothbrushes'  # program invocation
    
    1) UPS   2) FedEx
    
    Enter number of choice: 2
    
    You chose: FedEx
    Your order has been processed.  Thanks for your business!


=head2 ship2me2.plx

This variation on the preceding example shows how to use a custom menu-heading and interactive prompt.

    use Shell::POSIX::Select qw($Heading $Prompt);

    $Heading='Select a Shipper' ;
    $Prompt='Enter Vendor Number: ' ;

    select $shipper ( 'UPS', 'FedEx' ) {
      print "\nYou chose: $shipper\n";
      last;
    }
    ship ($shipper, $ARGV[0]);  # prints confirmation message

B<Screen>

    ship2me2.plx '42 hemp toothbrushes'

    Select a Shipper

    1) UPS   2) FedEx

    Enter Vendor Number: 2

    You chose: FedEx
    Your order has been processed.  Thanks for your business!


=head1 SYNTAX

=head2 Loop Structure

Supported invocation formats include the following:

 use Shell::POSIX::Select ;

 select                 ()      { }         # Form 0
 select                 ()      { CODE }    # Form 1
 select                 (LIST)  { CODE }    # Form 2
 select         $var    (LIST)  { CODE }    # Form 3
 select my      $var    (LIST)  { CODE }    # Form 4
 select our     $var    (LIST)  { CODE }    # Form 5
 select local   $var    (LIST)  { CODE }    # Form 6


If the loop variable is omitted (as in I<Forms> I<0>, I<1> and I<2> above),
it defaults to C<$_>, C<local>ized to the loop's scope.
If the LIST is omitted (as in I<Forms> I<0> and I<1>), 
C<@ARGV> is used by default, unless the loop occurs within a subroutine, in which case 
C<@_> is used instead.
If CODE is omitted (as in I<Form> I<0>,
it defaults to a statement that B<prints> the loop variable.

The cases shown above are merely examples; all reasonable permutations are permitted, including:

 select       $var    (    )  { CODE }        
 select local $var    (LIST)  {      }

The only form that's I<not> allowed is one that specifies the loop-variable's declarator without naming the loop variable, as in: 

 select our () { } # WRONG!  Must name variable with declarator!

=head2 The Loop variable

See L<"SCOPING ISSUES"> for full details about the implications
of different types of declarations for the loop variable.

=head2 The $Reply Variable

When the interactive user responds to the C<select> loop's prompt
with a valid input (i.e., a number in the correct range),
the variable C<$Reply> is set within the loop to that number.
Of course, the actual item selected is usually of great interest than
its number in the menu, but there are cases in which access to this
number is useful (see L<"menu_ls.plx"> for an example).

=head1 OVERVIEW

This loop is syntactically similar to Perl's
C<foreach> loop, and functionally related, so we'll describe it in those terms.

 foreach $var  ( LIST ) { CODE }

The job of C<foreach> is to run one iteration of CODE for each LIST-item, 
with the current item's value placed in C<local>ized C<$var>
(or if the variable is missing, C<local>ized C<$_>).

 select  $var  ( LIST ) { CODE }

In contrast, the C<select> loop displays a numbered menu of
LIST-items on the screen, prompts for (numerical) input, and then runs an iteration
with C<$var> being set that number's LIST-item.

In other words, C<select> is like an interactive, multiple-choice version of a
C<foreach> loop.
And that's cool!  What's I<not> so cool is that
C<select> is also the I<only> UNIX shell loop that's been left out of
the Perl language.  I<Until now!>

This module implements the C<select> loop of the Korn and Bash
("POSIX") shells for Perl.
It accomplishes this through Filter::Simple's I<Source Code Filtering> service,
allowing the programmer to blithely proceed as if this control feature existed natively in Perl.

The Bash and Korn shells differ slightly in their handling
of C<select> loops, primarily with respect to the layout of the on-screen menu.
This implementation currently follows the Korn shell version most closely
(but see L<"TODO-LIST"> for notes on planned enhancements).

=head1 ENHANCEMENTS

Although the shell doesn't allow the loop variable to be omitted,
for compliance with Perlish expectations,
the C<select> loop uses C<local>ized C<$_> by default
(as does the native C<foreach> loop).  See L<"SYNTAX"> for details.

The interface and behavior of the Shell versions has been retained
where deemed desirable,
and sensibly modified along Perlish lines elsewhere.
Accordingly, the (primary) default LIST is B<@ARGV> (paralleling the Shell's B<"$@">),
menu prompts can be customized by having the script import and set B<$Prompt>
(paralleling the Shell's B<$PS3>),
and the user's response to the prompt appears in the 
variable B<$Reply> (paralleling the Shell's B<$REPLY>),
C<local>ized to the loop.

A deficiency of the shell implementation is the
inability of the user to provide a I<heading> for each C<select> menu. 
Sure, the
shell programmer can B<echo> a heading before the loop is entered and the
menu is displayed, but that approach doesn't help when an I<Outer loop> is
reentered on departure from an I<Inner loop>,
because the B<echo> preceding the I<Outer loop> won't be re-executed. 

A similar deficiency surrounds the handling of a custom prompt string, and
the need to automatically display it on moving from an inner loop 
to an outer one.

To address these deficiencies, this implementation provides the option of having a heading and prompt bound
to each C<select> loop.  See L<"IMPORTS AND OPTIONS"> for details.

Headings and prompts are displayed in reverse video on the terminal,
if possible, to make them more visually distinct.

Some shell versions simply ignore bad input,
such as the entry of a number outside the menu's valid range,
or alphabetic input.  I can't imagine any argument
in favor of this behavior being desirable when input is coming from a terminal,
so this implementation gives clear warning messages for such cases by default
(see L<"Warnings"> for details).

After a menu's initial prompt is issued, some shell versions don't
show it again unless the user enters an empty line. 
This is desirable in cases where the menu is sufficiently large as to 
cause preceding output to scroll off the screen, and undesirable otherwise.
Accordingly, an option is provided to enable or disable automatic prompting
(see L<"Prompts">).

This implementation always issues a fresh prompt 
when a terminal user submits EOF as input to a nested C<select> loop.
In such cases, experience shows it's critical to reissue the
menu of the outer loop before accepting any more input.

=head1 SCOPING ISSUES

If the loop variable is named and provided with a I<declarator> (C<my>, C<our>, or C<local>),
the variable is scoped within the loop using that type of declaration.
But if the variable is named but lacks a declarator, 
no declaration is applied to the variable.

This allows, for example,
a variable declared as private I<above the loop> to be accessible
from within the loop, and beyond it,
and one declared as private I<for the loop> to be confined to it:

    select my $loopvar ( ) { }
    print "$loopvar DOES NOT RETAIN last value from loop here\n";
    -------------------------------------------------------------
    my $loopvar;
    select $loopvar ( ) { }
    print "$loopvar RETAINS last value from loop here\n";

With this design, 
C<select> behaves differently than the
native C<foreach> loop, which nowadays employs automatic
localization.

    foreach $othervar ( ) { } # variable localized automatically
    print "$othervar DOES NOT RETAIN last value from loop here\n";

    select $othervar ( ) { } # variable in scope, or global
    print "$othervar RETAINS last value from loop here\n";

This difference in the treatment of variables is intentional, and appropriate.
That's because the whole point of C<select>
is to let the user choose a value from a list, so it's often
critically important to be able to see, even outside the loop,
the value assigned to the loop variable.

In contrast, it's usually considered undesirable and unnecessary
for the value of the
C<foreach> loop's variable to be visible outside the loop, because
in most cases it will simply be that of the last element in the list.

Of course, in situations where the
C<foreach>-like behavior of implicit C<local>ization is desired,
the programmer has the option of declaring the C<select> loop's
variable as C<local>.

Another deficiency of the Shell versions is that it's difficult for the
programmer to differentiate between a
C<select> loop being exited via C<last>,
versus the loop detecting EOF on input.
To correct this situation,
the variable C<$Eof> can be imported and checked for a I<TRUE> value
upon exit from a C<select> loop (see L<"Eof Detection">).

=head1 IMPORTS AND OPTIONS

=head2 Syntax

 use Shell::POSIX::Select (
     '$Prompt',      # to customize per-menu prompt
     '$Heading',     # to customize per-menu heading
     '$Eof',         # T/F for Eof detection
  # Variables must come first, then key/value options
     prompt   => 'Enter number of choice:',  # or 'whatever:'
     style    => 'Bash',     # or 'Korn'
     warnings => 1,          # or 0
     debug    => 0,          # or 1-9
     logging  => 0,          # or 1
     testmode => <unset>,    # or 'make', or 'foreach'
 );

I<NOTE:> The values shown for options are the defaults, except for C<testmode>, which doesn't have one.

=head2 Prompts

There are two ways to customize the prompt used to solicit choices from
C<select> menus; through use of the prompt I<option>, which applies to
all loops, or the C<$Prompt> variable, which can be set independently for
each loop.

=head3 The prompt option

The C<prompt> option is intended for use in
programs that either contain a single C<select> loop, or are
content to use the same prompt for every loop.
It allows a custom interactive prompt to be set in the B<use> statement.

The prompt string should not end in a whitespace character, because
that doesn't look nice when the prompt is highlighted for display
(usually in I<reverse video>).
To offset the cursor from the prompt's end,
I<one space> is inserted automatically 
after display highlighting has been turned off. 

If the environment variable C<$ENV{Shell_POSIX_Select_prompt}>
is present,
its value overrides the one in the B<use> statement.

The default prompt is "Enter number of choice:".
To get the same prompt as provided by the Korn or Bash shell,
use C<< prompt =>> Korn >> or C<< prompt => Bash >>.

=head3 The $Prompt variable

The programmer may also modify the prompt during execution,
which may be desirable with nested loops that require different user instructions.
This is accomplished by
importing the $Prompt variable, and setting it to the desired prompt string
before entering the loop.  Note that imported variables have to be listed
as the initial arguments to the C<use> directive, and properly quoted.
See L<"order.plx"> for an example.

NOTE: If the program's input channel is not connected to a terminal,
prompting is automatically disabled
(since there's no point in soliciting input from a I<pipe>!).

=head2 $Heading

The programmer has the option of binding a heading to each loop's menu,
by importing C<$Heading> and setting it just before entering the associated loop.
See L<"order.plx"> for an example.

=head2 $Eof

A common concern with the Shell's C<select> loop is distinguishing between
cases where a loop ends due to EOF detection, versus the execution of C<break>
(like Perl's C<last>).
Although the Shell programmer can check the C<$REPLY> variable to make
this distinction, this implementation localizes its version of that variable 
(C<$Reply>) to the loop,
obviating that possibility.

Therefore, to make EOF detection as convenient and easy as possible,
the programmer may import C<$Eof> and check it for a 
I<TRUE> value after a C<select> loop.
See L<"lc_filename.plx"> for a programming example.

=head2 Styles

The C<style> options I<Korn> and I<Bash> can be used to request a more Kornish or Bashlike style of behavior.
Currently, the only difference is that the former disables, and the latter enables,
prompting for every input.  A value can be
provided for the C<style> option
using an argument of the form C<< style => 'Korn' >> to the C<use> directive.
The default setting is C<Bash>.
If the environment variable C<$ENV{Shell_POSIX_Select_style}> is
set to C<Korn> or C<Bash>,
its value overrides the one provided with the B<use> statement.

=head2 Warnings

The C<warnings> option,
whose values range from C<0> to C<1>, enables informational messages meant to help
the interactive user provide correct inputs.
The default setting is C<1>, which provides warnings about incorrect
responses to menu prompts 
(I<non-numeric>, I<out of range>, etc.).
Level C<0> turns these off. 

If the environment variable C<$ENV{Shell_POSIX_Select_warnings}> is
present, its value takes precedence.

=head2 Logging

The C<logging> option, whose value ranges from C<0> to C<1>,
causes informational messages and source code to be saved in temporary files
(primarily for debugging purposes).

The default setting is C<0>, which disables logging.

If the environment variable C<$ENV{Shell_POSIX_Select_logging}> is
present, its value takes precedence.

=head2 Debug

The C<debug> option,
whose values range from C<0> to C<9>, enables informational messages
to aid in identifying bugs.
If the environment variable C<$ENV{Shell_POSIX_Select_debug}> is
present, and set to one of the acceptable values, it takes precedence.

This option is primarly intended for the author's use, but
users who find bugs may want to enable it and email the output to
L<"AUTHOR">.  But before concluding that the problem is truly a bug
in this module, please confirm that the program runs correctly with the option 
C<< testmode => foreach >> enabled (see L<"Testmode">).

=head2 Testmode

The C<testmode> option, whose values are 'make' and 'foreach',
changes the way the program is executed.  The 'make' option is used
during the module's installation, and causes the program to dump
the modified source code and screen display to files,
and then stop (rather than interacting with the user). 

If the environment variable C<$ENV{Shell_POSIX_Select_testmode}> is
present, and set to one of the acceptable values, it takes precedence.

With the C<foreach> option enabled, the program simply translates occurrences
of C<select> into C<foreach>, which provides a useful method for 
checking that the program is syntactically correct before any serious
filtering has been applied (which can introduce syntax errors).
This works because the two loops, in their I<full forms>, have identical syntax.

Note that before you use C<< testmode => foreach >>, you I<must> fill in any
missing parts that are required by C<foreach>.

For instance,

C<	select () {}> 

must be rewritten as follows, to explicitly show "@ARGV" (assuming it's not in a subroutine) and "print":

C<	foreach (@ARGV) { print; }>

=head1 ADDITIONAL EXAMPLES

NOTE: All non-trivial programming examples shown in this document are
distributed with this module, in the B<Scripts> directory.
See L<"ELEMENTARY EXAMPLES">
for simpler uses of C<select>.

=head2 pick_file.plx

This program lets the user choose filenames to be sent to the output.
It's sort of like an
interactive Perl C<grep> function, with a live user providing the 
filtering service.
As illustrated below,
it could be used with Shell command substitution to provide selected arguments to a command.

    use Shell::POSIX::Select  (
        prompt => 'Pick File(s):' ,
        style => 'Korn'  # for automatic prompting
    );
    select ( <*> ) { }

B<Screen>

    lp `pick_file`   # Using UNIX-like OS

    1) memo1.txt   2) memo2.txt   3) memo3.txt
    4) junk1.txt   5) junk2.txt   6) junk3.txt

    Pick File(s): 4
    Pick File(s): 2
    Pick File(s): ^D

    request id is yumpy@guru+587

=head2 browse_images.plx

Here's a simple yet highly useful script.   It displays a menu of all
the image files in the current directory, and then displays the chosen
ones on-screen using a backgrounded image viewer.
It uses Perl's C<grep> to filter-out filenames that don't
end in the desired extensions.

    use Shell::POSIX::Select ;

    $viewer='xv';  # Popular image viewer

    select ( grep /\.(jpg|gif|tif|png)$/i, <*> ) {
        system "$viewer $_ &" ;     # run viewer in background
    }

=head2 perl_man.plx

Back in the olden days, we only had one Perl man-page. It was
voluminous, but at least you knew what argument to give the B<man>
command to get the documentaton.

Now we have over a hundred Perl man pages, with unpredictable names
that are difficult to remember.  Here's the program I use that 
allows me to select the man-page of interest from a menu.

 use Shell::POSIX::Select ;

 # Extract man-page names from the TOC portion of the output of "perldoc perl"
 select $manpage ( sort ( `perldoc perl` =~ /^\s+(perl\w+)\s/mg) ) {
     system "perldoc '$manpage'" ;
 }

B<Screen>

  1) perl5004delta     2) perl5005delta     3) perl561delta    
  4) perl56delta       5) perl570delta      6) perl571delta    
 . . .

I<(This large menu spans multiple screens, but all parts can be accessed
 using your normal terminal scrolling facility.)>

 Enter number of choice: 6

 
 PERL571DELTA(1)       Perl Programmers Reference Guide 

 NAME
        perl571delta - what's new for perl v5.7.1

 DESCRIPTION
        This document describes differences between the 5.7.0
        release and the 5.7.1 release.
 . . .

=head2 pick.plx

This more general C<pick>-ing program lets the user make selections
from I<arguments>, if they're present, or else I<input>, in the spirit of Perl's
C<-n> invocation option and C<< <> >> input operator.

 use Shell::POSIX::Select ;

 BEGIN {
     if (@ARGV) {
         @choices=@ARGV ;
     }
     else { # if no args, get choices from input
         @choices=<STDIN>  or  die "$0: No data\n";
         chomp @choices ;
         # STDIN already returned EOF, so must reopen
         # for terminal before menu interaction
         open STDIN, "/dev/tty"  or
             die "$0: Failed to open STDIN, $!" ;  # UNIX example
     }
 }
 select ( @choices ) { }   # prints selections to output

B<Sample invocations (UNIX-like system)>

    lp `pick *.txt`    # same output as shown for "pick_file"

    find . -name '*.plx' -print | pick | xargs lp  # includes sub-dirs

    who |
        awk '{ print $1 }' |        # isolate user names
            pick |                  # select user names
                Mail -s 'Promote these people!'  boss


=head2 delete_file.plx

In this program, the user selects a filename 
to be deleted.  The outer loop is used to refresh the list,
so the file deleted on the previous iteration gets removed from the next menu.
The outer loop is I<labeled> (as C<OUTER>), so that the inner loop can refer to it when
necessary.

 use Shell::POSIX::Select (
     '$Eof',   # for ^D detection
     prompt=>'Choose file for deletion:'
 ) ;

 OUTER:
     while ( @files=<*.py> ) { # collect serpentine files
         select ( @files ) {   # prompt for deletions
             print STDERR  "Really delete $_? [y/n]: " ;
             my $answer = <STDIN> ;     # ^D sets $Eof below
             defined $answer  or  last OUTER ;  # exit on ^D
             $answer eq "y\n"  and  unlink  and  last ;
         }
         $Eof and last;
 }

=head2 lc_filename.plx

This example shows the benefit of importing C<$Eof>, 
so the outer loop can be exited when the user supplies
C<^D> to the inner one.

Here's how it works.
If the rename succeeds in the inner loop, execution
of C<last> breaks out of the C<select> loop;
$Eof will then be evaluated as I<FALSE>, and 
the C<while> loop will start a new C<select> loop,
with a (depleted) filename menu.  But if the user
presses C<^D> to the menu prompt, C<$Eof> will test
as I<TRUE>, triggering the exit from the C<while> loop.

 use Shell::POSIX::Select (
     '$Eof' ,
     prompt => 'Enter number (^D to exit):'
     style => 'Korn'  # for automatic prompting
 );

 # Rename selected files from current dir to lowercase
 while ( @files=<*[A-Z]*> ) {   # refreshes select's menu
     select ( @files ) { # skip fully lower-case names
         if (rename $_, "\L$_") {
             last ;
         }
         else {
             warn "$0: rename failed for $_: $!\n";
         }
     }
     $Eof  and  last ;   # Handle ^D to menu prompt
 }

B<Screen>

 lc_filename.plx

 1) Abe.memo   2) Zeke.memo
 Enter number (^D to exit): 1

 1) Zeke.memo
 Enter number (^D to exit): ^D

=head2 order.plx

This program sets a custom prompt and heading for each of
its two loops, and shows the use of a label on the outer loop.

 use Shell::POSIX::Select qw($Prompt $Heading);
 
 $Heading="\n\nQuantity Menu:";
 $Prompt="Choose Quantity:";
 
 OUTER:
   select my $quantity (1..4) {
      $Heading="\nSize Menu:" ;
      $Prompt='Choose Size:' ;
  
      select my $size ( qw (L XL) ) {
          print "You chose $quantity units of size $size\n" ;
          last OUTER ;    # Order is complete
      }
   }

B<Screen>

 order.plx

 Quantity Menu:
 1)  1    2)  2    3)  3    4)  4
 Choose Quantity: 4

 Size Menu:
 1) L   2) XL
 Choose Size: ^D       (changed my mind about the quantity)

 Quantity Menu:
 1)  1    2)  2    3)  3    4)  4
 Choose Quantity: 2

 Size Menu:
 1)  L    2)  XL
 Choose Size: 2
 You chose 2 units of size XL

=head2 browse_records.plx

This program shows how you can implement a "record browser",
that builds a menu from the designated field of each record, and then
shows the record associated with the selected field. 

To use a familiar
example, we'll browse the UNIX password file by user-name.

 use Shell::POSIX::Select ( style => 'Korn' );
 
 if (@ARGV != 2  and  @ARGV != 3) {
     die "Usage: $0 fieldnum filename [delimiter]" ;
 }
 
 # Could also use Getopt:* module for option parsing
 ( $field, $file, $delim) = @ARGV ;
 if ( ! defined $delim ) {
     $delim='[\040\t]+' # SP/TAB sequences
 }
 
 $field-- ;  # 2->1, 1->0, etc., for 0-based indexing
 
 foreach ( `cat "$file"` ) {
     # field is the key in the hash, value is entire record
     $f2r{ (split /$delim/, $_)[ $field ] } = $_ ;
 }
 
 # Show specified fields in menu, and display associated records
 select $record ( sort keys %f2r ) {
     print "$f2r{$record}\n" ;
 }

B<Screen>

 browsrec.plx  '1'  /etc/passwd  ':'

  1) at     2) bin       3) contix   4) daemon  5) ftp     6) games
  7) lp     8) mail      9) man     10) named  11) news   12) nobody
 13) pop   14) postfix  15) root    16) spug   17) sshd   18) tim

 Enter number of choice: 18

 tim:x:213:100:Tim Maher:/home/tim:/bin/bash

 Enter number of choice: ^D

=head2 menu_ls.plx

This program shows a prototype for a menu-oriented front end
to a UNIX command, that prompts the user for command-option choices,
assembles the requested command, and then runs it.

It employs the user's numeric choice,
stored in the C<$Reply> variable, to extract from an array the command
option associated with each option description.

 use Shell::POSIX::Select qw($Heading $Prompt $Eof) ;

 # following avoids used-only once warning
 my ($type, $format) ;
 
 # Would be more Perlish to associate choices with options
 # via a Hash, but this approach demonstrates $Reply variable
 
 @formats = ( 'regular', 'long' ) ;
 @fmt_opt = ( '',        '-l'   ) ;
 
 @types   = ( 'only non-hidden', 'all files' ) ;
 @typ_opt = ( '',                '-a' ,      ) ;
 
 print "** LS-Command Composer **\n\n" ;
 
 $Heading="\n**** Style Menu ****" ;
 $Prompt= "Choose listing style:" ;
 OUTER:
   select $format ( @formats ) {
       $user_format=$fmt_opt[ $Reply - 1 ] ;
   
       $Heading="\n**** File Menu ****" ;
       $Prompt="Choose files to list:" ;
       select $type ( @types ) {   # ^D restarts OUTER
           $user_type=$typ_opt[ $Reply - 1 ] ;
           last OUTER ;    # leave loops once final choice obtained
       }
   }
 $Eof  and  exit ;   # handle ^D to OUTER
 
 # Now construct user's command
 $command="ls  $user_format  $user_type" ;
 
 # Show command, for educational value
 warn "\nPress <ENTER> to execute \"$command\"\n" ;

 # Now wait for input, then run command
 defined <>  or  print "\n"  and  exit ;    
 
 system $command ;    # finally, run the command
 
B<Screen>

 menu_ls.plx
 
 ** LS-Command Composer **
 
 1) regular    2) long
 Choose listing format: 2
 
 1) only non-hidden   2) all files
 Choose files to list:  2 
 
 Press <ENTER> to execute "ls -l -a" <ENTER>

 total 13439
 -rw-r--r--    1 yumpy   gurus    1083 Feb  4 15:41 README
 -rw-rw-r--    6 yumpy   gurus     277 Dec 17 14:36 .exrc.mmkeys
 -rw-rw-r--    7 yumpy   gurus     285 Jan 16 18:45 .exrc.podkeys
 $

=head1 BUGS

Unfortunately, this module is difficult to install on many modern platforms. However, there is a package that installs easily on Debian and Ubuntu-based systems (and with some effort, possibly others), which you can find at http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=libshell-posix-select.

=head2 UNIX Orientation

I've been a UNIX programmer since 1976, and a Linux proponent since
1992, so it's most natural for me to program for those platforms.
Accordingly, this early release has some minor features that are only
allowed, or perhaps only entirely functional, on UNIX-like systems.
I'm open to suggestions on how to implement some of these features in
a more portable manner.

Some of the programming examples are also 
UNIX oriented, but it should be easy enough for those specializing on
other platforms to make the necessary adapations. 8-|

=head2 Terminal Display Modes

These have been tested under UNIX/Linux, and work as expected,
using B<tput>.  When time permits, I'll convert to a portable
implementation that will support other OSs.

=head2 Incorrect Line Numbers in Warnings

Because this module inserts new source code into your program,
Perl messages that reference line numbers will refer to a
different source file than you wrote.  For this reason,
only messages referring to lines before the first C<select>
loop in your program will be correct.

If you're on a UNIX-like system, by enabling the C<debugging>
and C<logging> options (see L<"Debug"> and L<"Logging">), you can
get an on-screen report of the proper offset to apply to interpret
the line numbers of the source code that gets dumped to the
F</tmp/SELECT_source> file.  Of course, if everything works correctly,
you'll have little reason to look at the source. 8-|

=head2 Comments can Interfere with Filtering

Because of the way Filter::Simple works,
ostensibly "commented-out" C<select> loops like the following
can actually break your program:

 # select (@ARGV)
 # { ; }
 select (@ARGV) { ; }

A future version of Filter::Simple
(or more precisely Text::Balanced, on which on which it depends)
may correct this problem.

In any case, there's an easy workaround for the commented-out select
loop problem; just
change I<se>lect into I<es>lect when you comment it out, and there'll
be no problem.

For other problems involving troublesome text within comments, see 
L<"Failure to Identify select Loops">.

=head2 Failure to Identify C<select> Loops

When a properly formed C<select> loop appears in certain contexts,
such as before a line containing certain patterns of dollar signs
or quotes,
it will not be properly identified and translated into standard Perl.

=begin comment

The following is such an example:

    use Shell::POSIX::Select;
    select (@names) { print ; }
    # $X$

=end comment

The failure of the filtering routine to rewrite the loop causes the
compiler to issue the following fatal error when it sees the
B<{> following the B<(LIST)>:
	
syntax error at I<filename> line I<X>, near ") {"

This of course prevents the program from running.

The problem is either a bug in Filter::Simple, or one of the modules on
which it depends.
Until this is resolved, you may be able to 
handle such cases by explicitly turning filtering off before the offending
code is encountered, using the B<no> directive:

    use Shell::POSIX::Select;     # filtering ON
    select (@names) { print ; }

    no Shell::POSIX::Select;      # filtering OFF
    # $X$

=head2 Restrictions on Loop-variable Names

Due to a bug in most versions of Text::Balanced,
loop-variable names that look like Perl operators,
including C<$m>, C<$a>, C<$s>, C<$y>, C<$tr>,
C<$qq>, C<$qw>, C<$qr>, and C<$qx>, and possibly others,
cause syntax errors.
Newer
versions of that module
(unreleased at the time of this writing)
have corrected this problem, 
so download the latest version if you must use such names.

=head2 Please Report Bugs!

This is a non-trivial program, that does some fairly complex parsing
and data munging,
so I'm sure there are some latent bugs awaiting your discovery.
Please share them with me, by emailing the offending code,
and/or the diagnostic messages enabled by the I<debug>
option setting (see L<"IMPORTS AND OPTIONS">).

=head1 TODO-LIST

=head2 More Shell-like Menus

In a future release, there could be options for
more accurately emulating Bash and Korn-style behavior,
if anybody cares (the main difference is in how the
items are ordered in the menus).

=head2 More Extensive Test Suite

More tests are needed, especially for the complex and tricky cases.

=head1 MODULE DEPENDENCIES

 File::Spec::Functions
 Text::Balanced
 Filter::Simple

=head1 EXPORTS: Default

 $Reply

This variable is C<local>ized to each C<select> loop,
and provides the menu-number of the most recent valid selection.
For an example of its use, see L<"menu_ls.plx">.

=head1 EXPORTS: Optional

 $Heading
 $Prompt
 $Eof

See L<"IMPORTS AND OPTIONS"> for details.

=head1 SCRIPTS

 browse_images
 browse_jpeg
 browse_records
 delete_file
 lc_filename
 long_listem
 menu_ls
 order
 perl_man
 pick
 pick_file

=head1 AUTHOR

 Tim Maher
 Consultix
 yumpy(AT)cpan.org
 http://www.teachmeperl.com

=head1 ACKNOWLEDGEMENTS

I probably never would have even attempted to write this module
if it weren't for the provision of Filter::Simple by Damian Conway, 
which I ruthlessly exploited to make a hard job easy. 

I<The Damian> also gave useful tips
during the module's development, for which I'm grateful.

I I<definitely> wouldn't have ever written this module, if I hadn't
found myself writing a chapter on I<Looping> for my upcoming 
B<Manning Publications> book,
and once again lamenting the fact that the most friendly Shell loop
was still missing from Perl. 
So in a fit of zeal, I vowed to rectify that oversight!

I hope you find this module as useful as I do! 8->

For more examples of how this loop can be used in Perl programs,
watch for my upcoming book, I<Minimal Perl: for Shell Users and Programmers>
(see
L<http://teachmeperl.com/mp4sh.html>) in mid-2004.

=head1 SEE ALSO

 man ksh     # on UNIX or UNIX-like systems

 man bash    # on UNIX or UNIX-like systems

=head1 DON'T SEE ALSO

B<perldoc -f select>, which has nothing to do with this module
(the names just happen to match up).

=head1 VERSION

 This document is identical to the document dated 2003 that describes
 software version 0.05, apart from this sentence and the added
 information about installing this module from the Debian/Ubuntu
 package, which appears under the ALERT and BUGS headings.

=head1 LICENSE

Copyright (C) 2002-2011, Timothy F. Maher.  All rights reserved. 

This module is free software;
you can redistribute it and/or modify it under the same terms as Perl itself.

=cut

__DATA__
	
#! /usr/bin/perl -w
BEGIN {
	@choices = (
		'ball', 'ball', 'bald' 'balloon', 'ballroom',
	);
}

OUTER: while (1) {
	$input=<STDIN>;
	chomp $input;

	foreach (@choices) {
		if ( "@choices" =~ /\b($input)\b/ or
		    ( @matches = "@choices" =~ /\b(${input}\w+)\b/g) == 1 ) {
			$choice=$&;
			last OUTER;
		}
		else {
			print"Matched: @matches\n";
			print "Too many matches; type more characters\n";
			last;
		}
	}
}
print "Your choice is $choice\n";