.\" Automatically generated by Pod::Man 4.09 (Pod::Simple 3.35) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .if !\nF .nr F 0 .if \nF>0 \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} .\} .\" ======================================================================== .\" .IX Title "Shell::POSIX::Select 3pm" .TH Shell::POSIX::Select 3pm "2017-11-15" "perl v5.26.1" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" Shell::POSIX::Select \- The POSIX Shell's "select" loop for Perl .SH "PURPOSE" .IX Header "PURPOSE" This module implements the \f(CW\*(C`select\*(C'\fR loop of the \*(L"\s-1POSIX\*(R"\s0 shells (Bash, Korn, and derivatives) for Perl. That loop is unique in two ways: it's by far the friendliest feature of any \s-1UNIX\s0 shell, and it's the \fIonly\fR \s-1UNIX\s0 shell loop that's missing from the Perl language. Until now! .PP 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! .PP The benefit of bringing this loop to Perl is that it obviates the need for future programmers to reinvent the \fIChoose-From-A-Menu\fR wheel. .SH "SYNOPSIS" .IX Header "SYNOPSIS" select [ [my|local|our] scalar_var ] ( [\s-1LIST\s0] ) { [\s-1CODE\s0] } .PP In the above, the enclosing square brackets \fI(not typed)\fR identify optional elements, and vertical bars separate mutually-exclusive choices: .PP The required elements are the keyword \f(CW\*(C`select\*(C'\fR, the \fIparentheses\fR, and the \fIcurly braces\fR. See \*(L"\s-1SYNTAX\*(R"\s0 for details. .SH "ELEMENTARY EXAMPLES" .IX Header "ELEMENTARY EXAMPLES" \&\s-1NOTE:\s0 All non-trivial programming examples shown in this document are distributed with this module, in the \fBScripts\fR directory. \&\*(L"\s-1ADDITIONAL EXAMPLES\*(R"\s0, covering more features, are shown below. .SS "ship2me.plx" .IX Subsection "ship2me.plx" .Vb 1 \& use Shell::POSIX::Select; \& \& select $shipper ( \*(AqUPS\*(Aq, \*(AqFedEx\*(Aq ) { \& print "\enYou chose: $shipper\en"; \& last; \& } \& ship ($shipper, $ARGV[0]); # prints confirmation message .Ve .PP \&\fBScreen\fR .PP .Vb 1 \& ship2me.plx \*(Aq42 hemp toothbrushes\*(Aq # program invocation \& \& 1) UPS 2) FedEx \& \& Enter number of choice: 2 \& \& You chose: FedEx \& Your order has been processed. Thanks for your business! .Ve .SS "ship2me2.plx" .IX Subsection "ship2me2.plx" This variation on the preceding example shows how to use a custom menu-heading and interactive prompt. It also presents all menus in one column. .PP .Vb 1 \& use Shell::POSIX::Select qw($Heading $Prompt $MaxColumns); \& \& $Heading = \*(AqSelect a Shipper\*(Aq ; \& $Prompt = \*(AqEnter Vendor Number: \*(Aq ; \& $MaxColumns = 1; \& select $shipper ( \*(AqUPS\*(Aq, \*(AqFedEx\*(Aq ) { \& print "\enYou chose: $shipper\en"; \& last; \& } \& ship ($shipper, $ARGV[0]); # prints confirmation message .Ve .PP \&\fBScreen\fR .PP .Vb 1 \& ship2me2.plx \*(Aq42 hemp toothbrushes\*(Aq \& \& Select a Shipper \& \& 1) UPS 2) FedEx \& \& Enter Vendor Number: 2 \& \& You chose: FedEx \& Your order has been processed. Thanks for your business! .Ve .SH "SYNTAX" .IX Header "SYNTAX" .SS "Loop Structure" .IX Subsection "Loop Structure" Supported invocation formats include the following: .PP .Vb 1 \& 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 .Ve .PP If the loop variable is omitted (as in \fIForms\fR \fI0\fR, \fI1\fR and \fI2\fR above), it defaults to \f(CW$_\fR, \f(CW\*(C`local\*(C'\fRized to the loop's scope. If the \s-1LIST\s0 is omitted (as in \fIForms\fR \fI0\fR and \fI1\fR), \&\f(CW@ARGV\fR is used by default, unless the loop occurs within a subroutine, in which case \&\f(CW@_\fR is used instead. If \s-1CODE\s0 is omitted (as in \fIForm\fR \fI0\fR, it defaults to a statement that \fBprints\fR the loop variable. .PP The cases shown above are merely examples; all reasonable permutations are permitted, including: .PP .Vb 2 \& select $var ( ) { CODE } \& select local $var (LIST) { } .Ve .PP The only form that's \fInot\fR allowed is one that specifies the loop-variable's declarator without naming the loop variable, as in: .PP .Vb 1 \& select our () { } # WRONG! Must name variable with declarator! .Ve .SS "The Loop variable" .IX Subsection "The Loop variable" See \*(L"\s-1SCOPING ISSUES\*(R"\s0 for full details about the implications of different types of declarations for the loop variable. .ie n .SS "The $Reply Variable" .el .SS "The \f(CW$Reply\fP Variable" .IX Subsection "The $Reply Variable" When the interactive user responds to the \f(CW\*(C`select\*(C'\fR loop's prompt with a valid input (i.e., a number in the correct range), the variable \f(CW$Reply\fR 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\*(R" for an example). .SH "OVERVIEW" .IX Header "OVERVIEW" This loop is syntactically similar to Perl's \&\f(CW\*(C`foreach\*(C'\fR loop, and functionally related, so we'll describe it in those terms. .PP .Vb 1 \& foreach $var ( LIST ) { CODE } .Ve .PP The job of \f(CW\*(C`foreach\*(C'\fR is to run one iteration of \s-1CODE\s0 for each LIST-item, with the current item's value placed in \f(CW\*(C`local\*(C'\fRized \f(CW$var\fR (or if the variable is missing, \f(CW\*(C`local\*(C'\fRized \f(CW$_\fR). .PP .Vb 1 \& select $var ( LIST ) { CODE } .Ve .PP In contrast, the \f(CW\*(C`select\*(C'\fR loop displays a numbered menu of LIST-items on the screen, prompts for (numerical) input, and then runs an iteration with \f(CW$var\fR being set that number's LIST-item. .PP In other words, \f(CW\*(C`select\*(C'\fR is like an interactive, multiple-choice version of a \&\f(CW\*(C`foreach\*(C'\fR loop. And that's cool! What's \fInot\fR so cool is that \&\f(CW\*(C`select\*(C'\fR is also the \fIonly\fR \s-1UNIX\s0 shell loop that's been left out of the Perl language. \fIUntil now!\fR .PP This module implements the \f(CW\*(C`select\*(C'\fR loop of the Korn and Bash (\*(L"\s-1POSIX\*(R"\s0) shells for Perl. It accomplishes this through Filter::Simple's \fISource Code Filtering\fR service, allowing the programmer to blithely proceed as if this control feature existed natively in Perl. .PP The Bash and Korn shells differ slightly in their handling of \f(CW\*(C`select\*(C'\fR 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\*(R" for notes on planned enhancements). .SH "ENHANCEMENTS" .IX Header "ENHANCEMENTS" Although the shell doesn't allow the loop variable to be omitted, for compliance with Perlish expectations, the \f(CW\*(C`select\*(C'\fR loop uses \f(CW\*(C`local\*(C'\fRized \f(CW$_\fR by default (as does the native \f(CW\*(C`foreach\*(C'\fR loop). See \*(L"\s-1SYNTAX\*(R"\s0 for details. .PP 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 \s-1LIST\s0 is \fB\f(CB@ARGV\fB\fR (paralleling the Shell's \fB\*(L"$@\*(R"\fR), menu prompts can be customized by having the script import and set \fB\f(CB$Prompt\fB\fR (paralleling the Shell's \fB\f(CB$PS3\fB\fR), and the user's response to the prompt appears in the variable \fB\f(CB$Reply\fB\fR (paralleling the Shell's \fB\f(CB$REPLY\fB\fR), \&\f(CW\*(C`local\*(C'\fRized to the loop. .PP A deficiency of the shell implementation is the inability of the user to provide a \fIheading\fR for each \f(CW\*(C`select\*(C'\fR menu. Sure, the shell programmer can \fBecho\fR a heading before the loop is entered and the menu is displayed, but that approach doesn't help when an \fIOuter loop\fR is reentered on departure from an \fIInner loop\fR, because the \fBecho\fR preceding the \fIOuter loop\fR won't be re-executed. .PP 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. .PP To address these deficiencies, this implementation provides the option of having a heading and prompt bound to each \f(CW\*(C`select\*(C'\fR loop. See \*(L"\s-1IMPORTS AND OPTIONS\*(R"\s0 for details. .PP Headings and prompts are displayed in reverse video on the terminal, if possible, to make them more visually distinct. .PP 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\*(R" for details). .PP 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\*(R"). .PP This implementation always issues a fresh prompt when a terminal user submits \s-1EOF\s0 as input to a nested \f(CW\*(C`select\*(C'\fR loop. In such cases, experience shows it's critical to reissue the menu of the outer loop before accepting any more input. .SH "SCOPING ISSUES" .IX Header "SCOPING ISSUES" If the loop variable is named and provided with a \fIdeclarator\fR (\f(CW\*(C`my\*(C'\fR, \f(CW\*(C`our\*(C'\fR, or \f(CW\*(C`local\*(C'\fR), 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. .PP This allows, for example, a variable declared as private \fIabove the loop\fR to be accessible from within the loop, and beyond it, and one declared as private \fIfor the loop\fR to be confined to it: .PP .Vb 6 \& select my $loopvar ( ) { } \& print "$loopvar DOES NOT RETAIN last value from loop here\en"; \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \& my $loopvar; \& select $loopvar ( ) { } \& print "$loopvar RETAINS last value from loop here\en"; .Ve .PP With this design, \&\f(CW\*(C`select\*(C'\fR behaves differently than the native \f(CW\*(C`foreach\*(C'\fR loop, which nowadays employs automatic localization. .PP .Vb 2 \& foreach $othervar ( ) { } # variable localized automatically \& print "$othervar DOES NOT RETAIN last value from loop here\en"; \& \& select $othervar ( ) { } # variable in scope, or global \& print "$othervar RETAINS last value from loop here\en"; .Ve .PP This difference in the treatment of variables is intentional, and appropriate. That's because the whole point of \f(CW\*(C`select\*(C'\fR 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. .PP In contrast, it's usually considered undesirable and unnecessary for the value of the \&\f(CW\*(C`foreach\*(C'\fR 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. .PP Of course, in situations where the \&\f(CW\*(C`foreach\*(C'\fR\-like behavior of implicit \f(CW\*(C`local\*(C'\fRization is desired, the programmer has the option of declaring the \f(CW\*(C`select\*(C'\fR loop's variable as \f(CW\*(C`local\*(C'\fR. .PP Another deficiency of the Shell versions is that it's difficult for the programmer to differentiate between a \&\f(CW\*(C`select\*(C'\fR loop being exited via \f(CW\*(C`last\*(C'\fR, versus the loop detecting \s-1EOF\s0 on input. To correct this situation, the variable \f(CW$Eof\fR can be imported and checked for a \fI\s-1TRUE\s0\fR value upon exit from a \f(CW\*(C`select\*(C'\fR loop (see \*(L"Eof Detection\*(R"). .SH "IMPORTS AND OPTIONS" .IX Header "IMPORTS AND OPTIONS" .SS "Syntax" .IX Subsection "Syntax" .Vb 10 \& use Shell::POSIX::Select ( \& \*(Aq$Prompt\*(Aq, # to customize per\-menu prompt \& \*(Aq$Heading\*(Aq, # to customize per\-menu heading \& \*(Aq$MaxColumns\*(Aq, # to limit visual number of columns of choices \& \*(Aq$Eof\*(Aq, # T/F for Eof detection \& # Variables must come first, then key/value options \& prompt => \*(AqEnter number of choice:\*(Aq, # or \*(Aqwhatever:\*(Aq \& style => \*(AqBash\*(Aq, # or \*(AqKorn\*(Aq \& warnings => 1, # or 0 \& debug => 0, # or 1\-5 \& logging => 0, # or 1 \& testmode => , # or \*(Aqmake\*(Aq, or \*(Aqforeach\*(Aq \& ); .Ve .PP \&\fI\s-1NOTE:\s0\fR The values shown for options are the defaults, except for \f(CW\*(C`testmode\*(C'\fR, which doesn't have one. .SS "Prompts" .IX Subsection "Prompts" There are two ways to customize the prompt used to solicit choices from \&\f(CW\*(C`select\*(C'\fR menus; through use of the prompt \fIoption\fR, which applies to all loops, or the \f(CW$Prompt\fR variable, which can be set independently for each loop. .PP \fIThe prompt option\fR .IX Subsection "The prompt option" .PP The \f(CW\*(C`prompt\*(C'\fR option is intended for use in programs that either contain a single \f(CW\*(C`select\*(C'\fR loop, or are content to use the same prompt for every loop. It allows a custom interactive prompt to be set in the \fBuse\fR statement. .PP 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 \fIreverse video\fR). To offset the cursor from the prompt's end, \&\fIone space\fR is inserted automatically after display highlighting has been turned off. .PP If the environment variable \f(CW$ENV{Shell_POSIX_Select_prompt}\fR is present, its value overrides the one in the \fBuse\fR statement. .PP The default prompt is \*(L"Enter number of choice:\*(R". To get the same prompt as provided by the Korn or Bash shell, use \f(CW\*(C`prompt =>> Korn\*(C'\fR or \f(CW\*(C`prompt => Bash\*(C'\fR. .PP \fIThe \f(CI$Prompt\fI variable\fR .IX Subsection "The $Prompt variable" .PP 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 \f(CW$Prompt\fR 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 \f(CW\*(C`use\*(C'\fR directive, and properly quoted. See \*(L"order.plx\*(R" for an example. .PP \&\s-1NOTE:\s0 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 \fIpipe\fR!). .ie n .SS "$Heading" .el .SS "\f(CW$Heading\fP" .IX Subsection "$Heading" The programmer has the option of binding a heading to each loop's menu, by importing \f(CW$Heading\fR and setting it just before entering the associated loop. See \*(L"order.plx\*(R" for an example. .ie n .SS "$Eof" .el .SS "\f(CW$Eof\fP" .IX Subsection "$Eof" A common concern with the Shell's \f(CW\*(C`select\*(C'\fR loop is distinguishing between cases where a loop ends due to \s-1EOF\s0 detection, versus the execution of \f(CW\*(C`break\*(C'\fR (like Perl's \f(CW\*(C`last\*(C'\fR). Although the Shell programmer can check the \f(CW$REPLY\fR variable to make this distinction, this implementation localizes its version of that variable (\f(CW$Reply\fR) to the loop, obviating that possibility. .PP Therefore, to make \s-1EOF\s0 detection as convenient and easy as possible, the programmer may import \f(CW$Eof\fR and check it for a \&\fI\s-1TRUE\s0\fR value after a \f(CW\*(C`select\*(C'\fR loop. See \*(L"lc_filename.plx\*(R" for a programming example. .SS "Number of Columns" .IX Subsection "Number of Columns" By default, the visual length of each option is examined, and the list is spread across as many columns as will reasonably fit in the terminal. You can override this behavior by importing and setting \f(CW$MaxColumns\fR to the maximum number of columns you wish to display. See Scripts/max_columns_1.plx in the distribution as an example. .SS "Styles" .IX Subsection "Styles" The \f(CW\*(C`style\*(C'\fR options \fIKorn\fR and \fIBash\fR 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 \f(CW\*(C`style\*(C'\fR option using an argument of the form \f(CW\*(C`style => \*(AqKorn\*(Aq\*(C'\fR to the \f(CW\*(C`use\*(C'\fR directive. The default setting is \f(CW\*(C`Bash\*(C'\fR. If the environment variable \f(CW$ENV{Shell_POSIX_Select_style}\fR is set to \f(CW\*(C`Korn\*(C'\fR or \f(CW\*(C`Bash\*(C'\fR, its value overrides the one provided with the \fBuse\fR statement. .SS "Warnings" .IX Subsection "Warnings" The \f(CW\*(C`warnings\*(C'\fR option, whose values range from \f(CW0\fR to \f(CW1\fR, enables informational messages meant to help the interactive user provide correct inputs. The default setting is \f(CW1\fR, which provides warnings about incorrect responses to menu prompts (\fInon-numeric\fR, \fIout of range\fR, etc.). Level \f(CW0\fR turns these off. .PP If the environment variable \f(CW$ENV{Shell_POSIX_Select_warnings}\fR is present, its value takes precedence. .SS "Logging" .IX Subsection "Logging" The \f(CW\*(C`logging\*(C'\fR option, whose value ranges from \f(CW0\fR to \f(CW1\fR, causes informational messages and source code to be saved in temporary files (primarily for debugging purposes). .PP The default setting is \f(CW0\fR, which disables logging. .PP If the environment variable \f(CW$ENV{Shell_POSIX_Select_logging}\fR is present, its value takes precedence. .SS "Debug" .IX Subsection "Debug" The \f(CW\*(C`debug\*(C'\fR option, whose values range from \f(CW0\fR to \f(CW9\fR, enables informational messages to aid in identifying bugs. If the environment variable \f(CW$ENV{Shell_POSIX_Select_debug}\fR is present, and set to one of the acceptable values, it takes precedence. .PP 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"\s-1AUTHOR\*(R"\s0. But before concluding that the problem is truly a bug in this module, please confirm that the program runs correctly with the option \&\f(CW\*(C`testmode => foreach\*(C'\fR enabled (see \*(L"Testmode\*(R"). .SS "Testmode" .IX Subsection "Testmode" The \f(CW\*(C`testmode\*(C'\fR 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). .PP If the environment variable \f(CW$ENV{Shell_POSIX_Select_testmode}\fR is present, and set to one of the acceptable values, it takes precedence. .PP With the \f(CW\*(C`foreach\*(C'\fR option enabled, the program simply translates occurrences of \f(CW\*(C`select\*(C'\fR into \f(CW\*(C`foreach\*(C'\fR, 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 \fIfull forms\fR, have identical syntax. .PP Note that before you use \f(CW\*(C`testmode => foreach\*(C'\fR, you \fImust\fR fill in any missing parts that are required by \f(CW\*(C`foreach\*(C'\fR. .PP For instance, .PP \&\f(CW\*(C` select () {}\*(C'\fR .PP must be rewritten as follows, to explicitly show \*(L"@ARGV\*(R" (assuming it's not in a subroutine) and \*(L"print\*(R": .PP \&\f(CW\*(C` foreach (@ARGV) { print; }\*(C'\fR .SH "ADDITIONAL EXAMPLES" .IX Header "ADDITIONAL EXAMPLES" \&\s-1NOTE:\s0 All non-trivial programming examples shown in this document are distributed with this module, in the \fBScripts\fR directory. See \*(L"\s-1ELEMENTARY EXAMPLES\*(R"\s0 for simpler uses of \f(CW\*(C`select\*(C'\fR. .SS "pick_file.plx" .IX Subsection "pick_file.plx" This program lets the user choose filenames to be sent to the output. It's sort of like an interactive Perl \f(CW\*(C`grep\*(C'\fR 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. .PP .Vb 5 \& use Shell::POSIX::Select ( \& prompt => \*(AqPick File(s):\*(Aq , \& style => \*(AqKorn\*(Aq # for automatic prompting \& ); \& select ( <*> ) { } .Ve .PP \&\fBScreen\fR .PP .Vb 1 \& 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 .Ve .SS "browse_images.plx" .IX Subsection "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 \f(CW\*(C`grep\*(C'\fR to filter-out filenames that don't end in the desired extensions. .PP .Vb 1 \& use Shell::POSIX::Select ; \& \& $viewer=\*(Aqxv\*(Aq; # Popular image viewer \& \& select ( grep /\e.(jpg|gif|tif|png)$/i, <*> ) { \& system "$viewer $_ &" ; # run viewer in background \& } .Ve .SS "perl_man.plx" .IX Subsection "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 \fBman\fR command to get the documentaton. .PP 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. .PP .Vb 1 \& use Shell::POSIX::Select ; \& \& # Extract man\-page names from the TOC portion of the output of "perldoc perl" \& select $manpage ( sort ( \`perldoc perl\` =~ /^\es+(perl\ew+)\es/mg) ) { \& system "perldoc $manpage" ; \& } .Ve .PP \&\fBScreen\fR .PP .Vb 3 \& 1) perl5004delta 2) perl5005delta 3) perl561delta \& 4) perl56delta 5) perl570delta 6) perl571delta \& . . . .Ve .PP \&\fI(This large menu spans multiple screens, but all parts can be accessed using your normal terminal scrolling facility.)\fR .PP .Vb 1 \& Enter number of choice: 6 \& \& \& PERL571DELTA(1) Perl Programmers Reference Guide \& \& NAME \& perl571delta \- what\*(Aqs new for perl v5.7.1 \& \& DESCRIPTION \& This document describes differences between the 5.7.0 \& release and the 5.7.1 release. \& . . . .Ve .SS "pick.plx" .IX Subsection "pick.plx" This more general \f(CW\*(C`pick\*(C'\fR\-ing program lets the user make selections from \fIarguments\fR, if they're present, or else \fIinput\fR, in the spirit of Perl's \&\f(CW\*(C`\-n\*(C'\fR invocation option and \f(CW\*(C`<>\*(C'\fR input operator. .PP .Vb 1 \& use Shell::POSIX::Select ; \& \& BEGIN { \& if (@ARGV) { \& @choices=@ARGV ; \& } \& else { # if no args, get choices from input \& @choices= or die "$0: No data\en"; \& 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 .Ve .PP \&\fBSample invocations (UNIX-like system)\fR .PP .Vb 1 \& lp \`pick *.txt\` # same output as shown for "pick_file" \& \& find . \-name \*(Aq*.plx\*(Aq \-print | pick | xargs lp # includes sub\-dirs \& \& who | \& awk \*(Aq{ print $1 }\*(Aq | # isolate user names \& pick | # select user names \& Mail \-s \*(AqPromote these people!\*(Aq boss .Ve .SS "delete_file.plx" .IX Subsection "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 \fIlabeled\fR (as \f(CW\*(C`OUTER\*(C'\fR), so that the inner loop can refer to it when necessary. .PP .Vb 4 \& use Shell::POSIX::Select ( \& \*(Aq$Eof\*(Aq, # for ^D detection \& prompt=>\*(AqChoose file for deletion:\*(Aq \& ) ; \& \& OUTER: \& while ( @files=<*.py> ) { # collect serpentine files \& select ( @files ) { # prompt for deletions \& print STDERR "Really delete $_? [y/n]: " ; \& my $answer = ; # ^D sets $Eof below \& defined $answer or last OUTER ; # exit on ^D \& $answer eq "y\en" and unlink and last ; \& } \& $Eof and last; \& } .Ve .SS "lc_filename.plx" .IX Subsection "lc_filename.plx" This example shows the benefit of importing \f(CW$Eof\fR, so the outer loop can be exited when the user supplies \&\f(CW\*(C`^D\*(C'\fR to the inner one. .PP Here's how it works. If the rename succeeds in the inner loop, execution of \f(CW\*(C`last\*(C'\fR breaks out of the \f(CW\*(C`select\*(C'\fR loop; \&\f(CW$Eof\fR will then be evaluated as \fI\s-1FALSE\s0\fR, and the \f(CW\*(C`while\*(C'\fR loop will start a new \f(CW\*(C`select\*(C'\fR loop, with a (depleted) filename menu. But if the user presses \f(CW\*(C`^D\*(C'\fR to the menu prompt, \f(CW$Eof\fR will test as \fI\s-1TRUE\s0\fR, triggering the exit from the \f(CW\*(C`while\*(C'\fR loop. .PP .Vb 5 \& use Shell::POSIX::Select ( \& \*(Aq$Eof\*(Aq , \& prompt => \*(AqEnter number (^D to exit):\*(Aq \& style => \*(AqKorn\*(Aq # for automatic prompting \& ); \& \& # Rename selected files from current dir to lowercase \& while ( @files=<*[A\-Z]*> ) { # refreshes select\*(Aqs menu \& select ( @files ) { # skip fully lower\-case names \& if (rename $_, "\eL$_") { \& last ; \& } \& else { \& warn "$0: rename failed for $_: $!\en"; \& } \& } \& $Eof and last ; # Handle ^D to menu prompt \& } .Ve .PP \&\fBScreen\fR .PP .Vb 1 \& lc_filename.plx \& \& 1) Abe.memo 2) Zeke.memo \& Enter number (^D to exit): 1 \& \& 1) Zeke.memo \& Enter number (^D to exit): ^D .Ve .SS "order.plx" .IX Subsection "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. .PP .Vb 1 \& use Shell::POSIX::Select qw($Prompt $Heading); \& \& $Heading="\en\enQuantity Menu:"; \& $Prompt="Choose Quantity:"; \& \& OUTER: \& select my $quantity (1..4) { \& $Heading="\enSize Menu:" ; \& $Prompt=\*(AqChoose Size:\*(Aq ; \& \& select my $size ( qw (L XL) ) { \& print "You chose $quantity units of size $size\en" ; \& last OUTER ; # Order is complete \& } \& } .Ve .PP \&\fBScreen\fR .PP .Vb 1 \& 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 .Ve .SS "browse_records.plx" .IX Subsection "browse_records.plx" This program shows how you can implement a \*(L"record browser\*(R", that builds a menu from the designated field of each record, and then shows the record associated with the selected field. .PP To use a familiar example, we'll browse the \s-1UNIX\s0 password file by user-name. .PP .Vb 1 \& use Shell::POSIX::Select ( style => \*(AqKorn\*(Aq ); \& \& 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=\*(Aq[\e040\et]+\*(Aq # 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}\en" ; \& } .Ve .PP \&\fBScreen\fR .PP .Vb 1 \& browsrec.plx \*(Aq1\*(Aq /etc/passwd \*(Aq:\*(Aq \& \& 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 .Ve .SS "menu_ls.plx" .IX Subsection "menu_ls.plx" This program shows a prototype for a menu-oriented front end to a \s-1UNIX\s0 command, that prompts the user for command-option choices, assembles the requested command, and then runs it. .PP It employs the user's numeric choice, stored in the \f(CW$Reply\fR variable, to extract from an array the command option associated with each option description. .PP .Vb 1 \& 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 = ( \*(Aqregular\*(Aq, \*(Aqlong\*(Aq ) ; \& @fmt_opt = ( \*(Aq\*(Aq, \*(Aq\-l\*(Aq ) ; \& \& @types = ( \*(Aqonly non\-hidden\*(Aq, \*(Aqall files\*(Aq ) ; \& @typ_opt = ( \*(Aq\*(Aq, \*(Aq\-a\*(Aq , ) ; \& \& print "** LS\-Command Composer **\en\en" ; \& \& $Heading="\en**** Style Menu ****" ; \& $Prompt= "Choose listing style:" ; \& OUTER: \& select $format ( @formats ) { \& $user_format=$fmt_opt[ $Reply \- 1 ] ; \& \& $Heading="\en**** 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\*(Aqs command \& $command="ls $user_format $user_type" ; \& \& # Show command, for educational value \& warn "\enPress to execute \e"$command\e"\en" ; \& \& # Now wait for input, then run command \& defined <> or print "\en" and exit ; \& \& system $command ; # finally, run the command .Ve .PP \&\fBScreen\fR .PP .Vb 1 \& 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 to execute "ls \-l \-a" \& \& 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 \& $ .Ve .SH "BUGS" .IX Header "BUGS" .SS "\s-1UNIX\s0 Orientation" .IX Subsection "UNIX Orientation" I've been a \s-1UNIX\s0 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. .PP Some of the programming examples are also \&\s-1UNIX\s0 oriented, but it should be easy enough for those specializing on other platforms to make the necessary adapations. 8\-} .SS "Terminal Display Modes" .IX Subsection "Terminal Display Modes" These have been tested under UNIX/Linux, and work as expected, using \fBtput\fR. When time permits, I'll convert to a portable implementation that will support other OSs. .SS "Incorrect Line Numbers in Warnings" .IX Subsection "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 \f(CW\*(C`select\*(C'\fR loop in your program will be correct. .PP If you're on a UNIX-like system, by enabling the \f(CW\*(C`debugging\*(C'\fR and \f(CW\*(C`logging\*(C'\fR options (see \*(L"Debug\*(R" and \*(L"Logging\*(R"), 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 \&\fI/tmp/SELECT_source\fR file. Of course, if everything works correctly, you'll have little reason to look at the source. 8\-} .SS "Please Report Bugs!" .IX Subsection "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 \fIdebug\fR option setting (see \*(L"\s-1IMPORTS AND OPTIONS\*(R"\s0). .SH "TODO-LIST" .IX Header "TODO-LIST" .SS "More Shell-like Menus" .IX Subsection "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). .SS "More Extensive Test Suite" .IX Subsection "More Extensive Test Suite" More tests are needed, especially for the complex and tricky cases. .SH "MODULE DEPENDENCIES" .IX Header "MODULE DEPENDENCIES" .Vb 3 \& File::Spec::Functions \& Text::Balanced \& Filter::Simple .Ve .SH "EXPORTS: Default" .IX Header "EXPORTS: Default" .Vb 1 \& $Reply .Ve .PP This variable is \f(CW\*(C`local\*(C'\fRized to each \f(CW\*(C`select\*(C'\fR loop, and provides the menu-number of the most recent valid selection. For an example of its use, see \*(L"menu_ls.plx\*(R". .SH "EXPORTS: Optional" .IX Header "EXPORTS: Optional" .Vb 4 \& $Heading \& $Prompt \& $MaxColumns \& $Eof .Ve .PP See \*(L"\s-1IMPORTS AND OPTIONS\*(R"\s0 for details. .SH "SCRIPTS" .IX Header "SCRIPTS" .Vb 11 \& browse_images \& browse_jpeg \& browse_records \& delete_file \& lc_filename \& long_listem \& menu_ls \& order \& perl_man \& pick \& pick_file .Ve .SH "AUTHOR" .IX Header "AUTHOR" .Vb 1 \& Tim Maher .Ve .SH "MAINTAINER" .IX Header "MAINTAINER" .Vb 2 \& Martin Thurn \& mthurn@cpan.org .Ve .SH "ACKNOWLEDGEMENTS" .IX Header "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. .PP \&\fIThe Damian\fR also gave useful tips during the module's development, for which I'm grateful. .PP I \fIdefinitely\fR wouldn't have ever written this module, if I hadn't found myself writing a chapter on \fILooping\fR for my upcoming \&\fBManning Publications\fR 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! .PP I hope you find this module as useful as I do! 8\-} .PP For more examples of how this loop can be used in Perl programs, watch for my upcoming book, \fIMinimal Perl: for Shell Users and Programmers\fR (see ) in early fall, 2003. .SH "SEE ALSO" .IX Header "SEE ALSO" .Vb 1 \& man ksh # on UNIX or UNIX\-like systems \& \& man bash # on UNIX or UNIX\-like systems .Ve .SH "DON'T SEE ALSO" .IX Header "DON'T SEE ALSO" \&\fBperldoc \-f select\fR, which has nothing to do with this module (the names just happen to match up). .SH "VERSION" .IX Header "VERSION" This document describes version 0.08. .SH "LICENSE" .IX Header "LICENSE" Copyright (C) 2002\-2003, Timothy F. Maher. All rights reserved. .PP This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself.