1IO::Prompter(3)       User Contributed Perl Documentation      IO::Prompter(3)
2
3
4

NAME

6       IO::Prompter - Prompt for input, read it, clean it, return it.
7

VERSION

9       This document describes IO::Prompter version 0.005001
10

SYNOPSIS

12           use IO::Prompter;
13
14           while (prompt -num, 'Enter a number') {
15               say "You entered: $_";
16           }
17
18           my $passwd
19               = prompt 'Enter your password', -echo=>'*';
20
21           my $selection
22               = prompt 'Choose wisely...', -menu => {
23                       wealth => [ 'moderate', 'vast', 'incalculable' ],
24                       health => [ 'hale', 'hearty', 'rude' ],
25                       wisdom => [ 'cosmic', 'folk' ],
26                 }, '>';
27

CAVEATS

29       1.  Several features of this module are known to have problems under
30           Windows. If using that platform, you may have more success (and
31           less distress) by trying IO::Prompt::Tiny, IO::Prompt::Simple, or
32           IO::Prompt::Hooked first.
33
34       2.  By default the prompt() subroutine does not return a string; it
35           returns an object with overloaded string and boolean conversions.
36           This object always evaluates true in boolean contexts, unless the
37           read operation actually failed. This means that the object
38           evaluates true even when the input value is zero or an empty
39           string. See "Returning raw data" to turn off this (occasionally
40           counter-intuitive) behaviour.
41

DESCRIPTION

43       IO::Prompter exports a single subroutine, "prompt", that prints a
44       prompt (but only if the program's selected input and output streams are
45       connected to a terminal), then reads some input, then chomps it, and
46       finally returns an object representing that text.
47
48       The prompt() subroutine expects zero-or-more arguments.
49
50       Any argument that starts with a hyphen ("-") is treated as a named
51       option (many of which require an associated value, that may be passed
52       as the next argument). See "Summary of options" and "Options reference"
53       for details of the available options.
54
55       Any other argument that is a string is treated as (part of) the prompt
56       to be displayed. All such arguments are concatenated together before
57       the prompt is issued. If no prompt string is provided, the string '> '
58       is used instead.
59
60       Normally, when prompt() is called in either list or scalar context, it
61       returns an opaque object that autoconverts to a string. In scalar
62       boolean contexts this return object evaluates true if the input
63       operation succeeded. In list contexts, if the input operation fails
64       prompt() returns an empty list instead of a return object. This allows
65       failures in list context to behave correctly (i.e. be false).
66
67       If you particularly need a list-context call to prompt() to always
68       return a value (i.e. even on failure), prefix the call with "scalar":
69
70           # Only produces as many elements
71           # as there were successful inputs...
72           my @data = (
73               prompt(' Name:'),
74               prompt('  Age:'),
75               prompt('Score:'),
76           );
77
78           # Always produces exactly three elements
79           # (some of which may be failure objects)...
80           my @data = (
81               scalar prompt(' Name:'),
82               scalar prompt('  Age:'),
83               scalar prompt('Score:'),
84           );
85
86       In void contexts, prompt() still requests input, but also issues a
87       warning about the general uselessness of performing an I/O operation
88       whose results are then immediately thrown away.  See "Useful useless
89       uses of prompt()" for an exception to this.
90
91       The prompt() function also sets $_ if it is called in a boolean context
92       but its return value is not assigned to a variable. Hence, it is
93       designed to be a drop-in replacement for "readline" or "<>".
94

INTERFACE

96       All the options for prompt() start with a hyphen ("-").  Most have both
97       a short and long form. The short form is always the first letter of the
98       long form.
99
100       Most options have some associated value. For short-form options, this
101       value is specified as a string appended to the option itself. The
102       associated value for long-form options is always specified as a
103       separated argument, immediately following the option (typically
104       separated from it by a "=>").
105
106       Note that this implies that short-form options may not be able to
107       specify every possible associated value (for example, the short-form
108       "-d" option cannot specify defaults with values 'efault' or '$%^!').
109       In such cases, just use the long form of the option (for example:
110       "-def => 'efault'" or "-default=>'$%^!'").
111
112   Summary of options
113       Note: For options preceded by an asterisk, the short form is actually a
114       Perl file operator, and hence cannot be used by itself.  Either use the
115       long form of these options, or bundle them with another option, or add
116       a "no-op" to them.
117
118           Short   Long
119           form    form               Effect
120           =====   =============      ======================================
121
122           -a      -argv              Prompt for @ARGV data if !@ARGV
123
124                   -cancel=>SPEC      Immediately fail if input char smartmatches value
125
126                   -comp[lete]=>SPEC  Complete input on <TAB>, as specified
127
128           -dSTR   -def[ault]=>STR    What to return if only <ENTER> typed
129                   -DEF[AULT]=>STR    (as above, but skip any -must checking)
130
131         * -e[STR] -echo=>STR         Echo string for each character typed
132
133                   -echostyle=>SPEC   What colour/style to echo input in
134
135         * -f      -filenames         Input should be name of a readable file
136
137                   -fail=>VALUE       Return failure if completed input smartmatches value
138
139                   -guar[antee]=>SPEC Only allow the specified words to be entered
140
141           -h[STR] -hist[ory][=>SPEC] Specify the history set this call belongs to
142
143                   -in=>HANDLE        Read from specified handle
144
145           -i      -integer[=>SPEC]   Accept only valid integers (that smartmatch SPEC)
146
147           -k      -keyletters        Accept only keyletters (as specified in prompt)
148
149         * -l      -line              Don't autochomp
150
151                   -menu=>SPEC        Specify a menu of responses to be displayed
152
153                   -must=>HASHREF     Specify requirements/constraints on input
154
155                   -monitor=>SUBREF   Specify a sub to be called on every character input
156
157           -n      -num[ber][=>SPEC]  Accept only valid numbers (that smartmatch SPEC)
158
159                   -out=>HANDLE       Prompt to specified handle
160
161                   -prefill=>STR      Start with the specified string pre-entered
162
163                   -prompt=>STR       Specify prompt explicitly
164
165         * -rSTR   -ret[urn]=>STR     After input, echo this string instead of <CR>
166
167         * -s -1   -sing[le]          Return immediately after first key pressed
168
169                   -stdio             Use STDIN and STDOUT for prompting
170
171                   -style=>SPEC       What colour/style to display the prompt text in
172
173           -tNUM   -time[out]=>NUM    Specify a timeout on the input operation
174
175           -v      -verb[atim]        Return the input string (no context sensitivity)
176
177                   -void              Don't complain in void context
178
179         * -w      -wipe              Clear screen
180                   -wipefirst         Clear screen on first prompt() call only
181
182         * -y      -yes    [=> NUM]   Return true if [yY] entered, false otherwise
183           -yn     -yesno  [=> NUM]   Return true if [yY] entered, false if [nN]
184           -Y      -Yes    [=> NUM]   Return true if Y entered, false otherwise
185           -YN     -YesNo  [=> NUM]   Return true if Y entered, false if N
186
187         * -_                         No-op (handy for bundling ambiguous short forms)
188
189   Automatic options
190       Any of the options listed above (and described in detail below) can be
191       automatically applied to every call to prompt() in the current lexical
192       scope, by passing them (via an array reference) as the arguments to a
193       "use IO::Prompter" statement.
194
195       For example:
196
197           use IO::Prompter;
198
199           # This call has no automatically added options...
200           my $assent = prompt "Do you wish to take the test?", -yn;
201
202           {
203               use IO::Prompter [-yesno, -single, -style=>'bold'];
204
205               # These three calls all have: -yesno, -single, -style=>'bold' options
206               my $ready = prompt 'Are you ready to begin?';
207               my $prev  = prompt 'Have you taken this test before?';
208               my $hints = prompt 'Do you want hints as we go?';
209           }
210
211           # This call has no automatically added options...
212           scalar prompt 'Type any key to start...', -single;
213
214       The current scope's lexical options are always prepended to the
215       argument list of any call to prompt() in that scope.
216
217       To turn off any existing automatic options for the rest of the current
218       scope, use:
219
220           use IO::Prompter [];
221
222   Prebound options
223       You can also ask IO::Prompter to export modified versions of prompt()
224       with zero or more options prebound. For example, you can request an
225       ask() subroutine that acts exactly like prompt() but has the "- yn"
226       option pre-specified, or a pause() subroutine that is prompt() with a
227       "canned" prompt and the "-echo", "-single", and "-void" options.
228
229       To specify such subroutines, pass a single hash reference when loading
230       the module:
231
232           use IO::Prompter {
233               ask     => [-yn],
234               pause   => [-prompt=>'(Press any key to continue)', -echo, -single, -void],
235           }
236
237       Each key will be used as the name of a separate subroutine to be
238       exported, and each value must be an array reference, containing the
239       arguments that are to be automatically supplied.
240
241       The resulting subroutines are simply lexically scoped wrappers around
242       prompt(), with the specified arguments prepended to the normal argument
243       list, equivalent to something like:
244
245           my sub ask {
246               return prompt(-yn, @_);
247           }
248
249           my sub pause {
250               return prompt(-prompt=>'(Press any key to continue)', -echo, -single, -void, @_);
251           }
252
253       Note that these subroutines are lexically scoped, so if you want to use
254       them throughtout a source file, they should be declared in the
255       outermost scope of your program.
256
257   Options reference
258       Specifying what to prompt
259
260           "-prompt => STRING"
261
262           "-pSTRING"
263
264       By default, any argument passed to prompt() that does not begin with a
265       hyphen is taken to be part of the prompt string to be displayed before
266       the input operation. Moreover, if no such string is specified in the
267       argument list, the function supplies a default prompt ('> ')
268       automatically.
269
270       The "-prompt" option allows you to specify a prompt explicitly, thereby
271       enabling you to use a prompt that starts with a hyphen:
272
273           my $input
274               = prompt -prompt=>'-echo';
275
276       or to disable prompting entirely:
277
278           my $input
279               = prompt -prompt => "";
280
281       Note that the use of the "-prompt" option doesn't override other string
282       arguments, it merely adds its argument to the collective prompt.
283
284       Prompt prettification
285
286       If the specified prompt ends in a non-whitespace character, prompt()
287       adds a single space after it, to better format the output. On the other
288       hand, if the prompt ends in a newline, prompt() removes that character,
289       to keep the input position on the same line as the prompt.
290
291       You can use that second feature to override the first, if necessary.
292       For example, if you wanted your prompt to look like:
293
294           Load /usr/share/dict/_
295
296       (where the _ represents the input cursor), then a call like:
297
298           $filename = prompt 'Load /usr/share/dict/';
299
300       would not work because it would automatically add a space, producing:
301
302           Load /usr/share/dict/ _
303
304       But since a terminal newline is removed, you could achieve the desired
305       effect with:
306
307           $filename = prompt "Load /usr/share/dict/\n";
308
309       If for some reason you do want a newline at the end of the prompt (i.e.
310       with the input starting on the next line) just put two newlines at the
311       end of the prompt. Only the very last one will be removed.
312
313       Specifying how the prompt looks
314
315           "-style  => SPECIFICATION"
316
317       If the "Term::ANSIColor" module is available, this option can be used
318       to specify the colour and styling (e.g. bold, inverse, underlined,
319       etc.)  in which the prompt is displayed.
320
321       You can can specify that styling as a single string:
322
323           prompt 'next:' -style=>'bold red on yellow';
324
325       or an array of styles:
326
327           prompt 'next:' -style=>['bold', 'red', 'on_yellow'];
328
329       The range of styles and colour names that the option understands is
330       quite extensive. All of the following work as expected:
331
332           prompt 'next:' -style=>'bold red on yellow';
333
334           prompt 'next:' -style=>'strong crimson on gold';
335
336           prompt 'next:' -style=>'highlighted vermilion, background of cadmium';
337
338           prompt 'next:' -style=>'vivid russet over amber';
339
340           prompt 'next:' -style=>'gules fort on a field or';
341
342       However, because "Term::ANSIColor" sometmes maps everything back to the
343       standard eight ANSI text colours and seven ANSI text styles, all of the
344       above may also be rendered identically. See that module's documentation
345       for details.
346
347       If "Term::ANSIColor" is not available, this option is silently ignored.
348
349       Please bear in mind that up to 10% of people using your interface will
350       have some form of colour vision impairment, so its always a good idea
351       to differentiate information by style and colour, rather than by colour
352       alone. For example:
353
354           if ($dangerous_action) {
355               prompt 'Really proceed?', -style=>'bold red underlined';
356           }
357           else {
358               prompt 'Proceed?', -style=>'green';
359           }
360
361       Also bear in mind that (even though "-style" does support the 'blink'
362       style) up to 99% of people using your interface will have Flashing Text
363       Tolerance Deficiency. Just say "no".
364
365       Specifying where to prompt
366
367           "-out => FILEHANDLE"
368
369           "-in => FILEHANDLE"
370
371           "-stdio"
372
373       The "-out" option (which has no short form) is used to specify where
374       the prompt should be written to. If this option is not specified,
375       prompts are written to the currently "select"-ed filehandle. The most
376       common usage is:
377
378           prompt(out => *STDERR)
379
380       The "-in" option (which also has no short form) specifies where the
381       input should be read from. If this option is not specified, input is
382       read from the *ARGV filehandle. The most common usage is:
383
384           prompt(in => *STDIN)
385
386       in those cases where *ARGV has been opened to a file, but you still
387       wish to interact with the terminal (assuming *STDIN is opened to that
388       terminal).
389
390       The "-stdio" option (which again has no short form) is simply a
391       shorthand for: "-in => *STDIN, -out => *STDOUT". This is particularly
392       useful when there are arguments on the commandline, but you don't want
393       prompt to treat those arguments as filenames for magic *ARGV reads.
394
395       Specifying how long to wait for input
396
397           "-timeout => N"
398
399           "-tN"
400
401       Normally, the prompt() function simply waits for input. However, you
402       can use this option to specify a timeout on the read operation.  If no
403       input is received within the specified N seconds, the call to prompt()
404       either returns the value specified by the "-default" option (if any),
405       or else an object indicating the read failed.
406
407       Note that, if the short form is used, N must be an integer. If the long
408       form is used, N may be an integer or floating point value.
409
410       You can determine whether an input operation timed out, even if a
411       default value was returned, by calling the timedout() method on the
412       object returned by prompt():
413
414           if (prompt('Continue?', -y1, -timeout=>60) && !$_->timedout) {
415               ...
416           }
417
418       If a time-out occurred, the return value of timedout() is a string
419       describing the timeout, such as:
420
421           "timed out after 60 seconds"
422
423       Prefilling the input
424
425       "-prefill => STRING"
426
427       Normally, the cursor is placed immediately after the prompt in
428       preparation for input. Initially, of course, there is no input.
429
430       However, using the "-prefill" option it is possible to initialize the
431       input buffer with an arbitrary string of text (rather than the usual
432       empty string)...as if that text had already been entered.
433
434       This is useful when a prompt is re-issued so as to allow the user to
435       extend, truncate, or otherwise edit a previous input.
436
437       Providing a menu of responses
438
439       "-menu => SPECIFICATION"
440
441       You can limit the allowable responses to a prompt, by providing a menu.
442
443       A menu is specified using the "-menu" option, and the menu choices are
444       specified as an argument to the option, either as a reference to an
445       array, hash, or string, or else as a literal string.
446
447       If the menu is specified in a hash, prompt() displays the keys of the
448       hash, sorted alphabetically, and with each alternative marked with a
449       single alphabetic character (its "selector key").
450
451       For example, given:
452
453           prompt 'Choose...',
454                  -menu=>{ 'live free'=>1, 'die'=>0, 'transcend'=>-1 },
455                  '>';
456
457       prompt() will display:
458
459           Choose...
460               a. die
461               b. live free
462               c. transcend
463           > _
464
465       It will then only permit the user to enter a valid selector key (in the
466       previous example: 'a', 'b', or 'c'). Once one of the alternatives is
467       selected, prompt() will return the corresponding value from the hash
468       (0, 1, or -1, respectively, in this case).
469
470       Note that the use of alphabetics as selector keys inherently limits the
471       number of usable menu items to 52. See "Numeric menus" for a way to
472       overcome this limitation.
473
474       A menu is treated like a special kind of prompt, so that any other
475       prompt strings in the prompt() call will appear either before or after
476       the menu of choices, depending on whether they appear before or after
477       the menu specification in the call to prompt().
478
479       If an array is used to specify the choices:
480
481           prompt 'Choose...',
482                  -menu=>[ 'live free', 'die', 'transcend' ],
483                  '>';
484
485       then each array element is displayed (in the original array order) with
486       a selector key:
487
488           Choose...
489               a. live free
490               b. die
491               c. transcend
492           > _
493
494       and prompt() returns the element corresponding to the selection (i.e.
495       it returns 'live free' if 'a' is entered, 'die' if 'b' is entered, or
496       'transcend' if 'c' is entered).
497
498       Hence, the difference between using an array and a hash is that the
499       array allows you to control the order of items in the menu, whereas a
500       hash allows you to show one thing (i.e. keys) but have something
501       related (i.e. values) returned instead.
502
503       If the argument after "-menu" is a string or a reference to a string,
504       the option splits the string on newlines, and treats the resulting list
505       as if it were an array of choices. This is useful, for example, to
506       request the user select a filename:
507
508           my $files = `ls`;
509           prompt 'Select a file...', -menu=>$files, '>';
510
511       Numbered menus
512
513       As the previous examples indicate, each menu item is given a unique
514       alphabetic selector key. However, if the "-number" or "-integer" option
515       is specified as well:
516
517           prompt 'Choose...',
518                  -number,
519                  -menu=>{ 'live free'=>1, 'die'=>0, 'transcend'=>-1 },
520                  '>';
521
522       prompt() will number each menu item instead, using consecutive integers
523       as the selector keys:
524
525           Choose...
526               1. die
527               2. live free
528               3. transcend
529           > _
530
531       This allows for an unlimited number of alternatives in a single menu,
532       but prevents the use of "-single" for one-key selection from menus if
533       the menu has more than nine items.
534
535       Hierarchical menus
536
537       If you use a hash to specify a menu, the values of the hash do not have
538       to be strings. Instead, they can be references to nested hashes or
539       arrays.
540
541       This allows you to create hierarchical menus, where a selection at the
542       top level may lead to a secondary menu, etc. until an actual choice is
543       possible. For example, the following call to prompt:
544
545           my $choices = {
546               animates => {
547                   animals => {
548                       felines => [qw<cat lion lynx>],
549                       canines => [qw<dog fox wolf>],
550                       bovines => [qw<cow ox buffalo>],
551                   },
552                   fish => [qw<shark carp trout bream>],
553               },
554               inanimates => {
555                   rocks     => [qw<igneous metamorphic sedimentary>],
556                   languages => [qw<Perl Python Ruby Tcl>],
557               },
558           };
559
560           my $result = prompt -1, 'Select a species...', -menu=>$choices, '> ';
561
562       might result in an interaction like this:
563
564           Select a species...
565           a.  animates
566           b.  inanimates
567           > a
568
569           Select from animates:
570           a.  animals
571           b.  fish
572           > b
573
574           Select from fish:
575           a.  shark
576           b.  carp
577           c.  trout
578           d.  bream
579           > c
580
581       At which point, prompt() would return the string 'trout'.
582
583       Note that you can nest an arbitrary number of hashes, but that each
584       "bottom" level choice has to be either a single string, or an array of
585       strings.
586
587       Navigating hierarchical menus
588
589       Within a hierarchical menu, the user must either select a valid option
590       (by entering the corresponding letter), or else may request that they
591       be taken back up a level in the hierarchy, by entering "<ESC>".
592       Pressing "<ESC>" at the top level of a menu causes the call to prompt()
593       to immediately return with failure.
594
595       Simulating a command-line
596
597           "-argv"
598
599           "-a"
600
601       The prompt() subroutine can be used to request that the user provide
602       command-line arguments interactively. When requested, the input
603       operation is only carried out if @ARGV is empty.
604
605       Whatever the user enters is broken into a list and assigned to @ARGV.
606
607       The input is first "glob"bed for file expansions, and has any
608       environment variables (of the form $VARNAME interpolated). The
609       resulting string is then broken into individual words, except where
610       parts of it contain single or double quotes, the contents of which are
611       always treated as a single string.
612
613       This feature is most useful during development, to allow a program to
614       be run from within an editor, and yet pass it a variety of command-
615       lines. The typical usage is (at the start of a program):
616
617           use IO::Prompter;
618           BEGIN { prompt -argv }
619
620       However, because this pattern is so typical, there is a shortcut:
621
622           use IO::Prompter -argv;
623
624       You can also specify the name with which the program args, are to be
625       prompted, in the usual way (i.e. by providing a prompt):
626
627           use IO::Prompter -argv, 'demo.pl';
628
629       Note, however, the critical difference between that shortcut (which
630       calls "prompt -argv" when the module is loaded) and:
631
632           use IO::Prompter [-argv];
633
634       (which sets "-argv" as an automatic option for every subsequent call to
635       prompt() in the current lexical scope).
636
637       Note too that the "-argv" option also implies "-complete="'filenames'>.
638
639       Input autocompletion
640
641           "-comp[lete] => SPECIFICATION"
642
643       When this option is specified, the prompt() subroutine will complete
644       input using the specified collection of strings. By default, when
645       completion is active, word completion is requested using the "<TAB>"
646       key, but this can be changed by setting the $IO_PROMPTER_COMPLETE_KEY
647       environment variable. Once completion has been initiated, you can use
648       the completion key or else "<CTRL-N>" to advance to the next completion
649       candidate. You can also use "<CTRL-P>" to back up to the previous
650       candidate.
651
652       The specific completion mechanism can be defined either using a
653       subroutine, an array reference, a hash reference, or a special string:
654
655           Specification       Possible completions supplied by...
656
657             sub {...}         ...whatever non-subroutine specification
658                               (as listed below) is returned when the
659                               subroutine is called. The subroutine is passed
660                               the words of the current input text, split on
661                               whitespace, as its argument list.
662
663               [...]           ...the elements of the array
664
665               {...}           ...the keys of the hash
666
667            'filenames'        ...the list of files supplied by globbing the
668                               last whitespace-separated word of the input text
669
670            'dirnames'         ...the list of directories supplied by globbing the
671                               last whitespace-separated word of the input text
672
673       If an array or hash is used, only those elements or keys that begin
674       with the last whitespace-separated word of the current input are
675       offered as completions.
676
677       For example:
678
679           # Complete with the possible commands...
680           my $next_cmd
681               = prompt -complete => \%cmds;
682
683           # Complete with valid usernames...
684           my $user
685               = prompt -complete => \@usernames;
686
687           # Complete with valid directory names...
688           my $file
689               = prompt -complete => 'dirnames';
690
691           # Complete with cmds on the first word, and filenames on the rest...
692           my $cmdline
693               = prompt -complete => sub { @_ <= 1 ? \%cmds : 'filenames' };
694
695       Completing from your own input history
696
697       The prompt() subroutine also tracks previous input and allows you to
698       complete with that instead. No special option is required, as the
699       feature is enabled by default.
700
701       At the start of a prompted input, the user can cycle backwards through
702       previous inputs by pressing "<CTRL-R>" (this can be changed externally
703       by setting the $IO_PROMPTER_HISTORY_KEY environment variable, or
704       internally by assigning a new keyname to
705       $ENV{IO_PROMPTER_HISTORY_KEY}). After the first "<CTRL-R>", subsequent
706       "<CTRL-R>"'s will recall earlier inputs. You can also use "<CTRL-N>"
707       and "<CTRL-P>" (as in user-specified completions) to move back and
708       forth through your input history.
709
710       If the user has already typed some input, the completion mechanism will
711       only show previous inputs that begin with that partial input.
712
713       History sets
714
715       "-h[NAME]"
716       "-hist[ory] [=> NAME]"
717
718       By default, IO::Prompter tracks every call to prompt() within a
719       program, and accumulates a single set of history completions for all of
720       them. That means that, at any prompt, "<CTRL-R>" will take the user
721       back through every previous input, regardless of which call to prompt()
722       originally retrieved it.
723
724       Sometimes that's useful, but sometimes you might prefer that different
725       calls to prompt() retained distinct memories. For example, consider the
726       following input loop:
727
728           while (my $name = prompt 'Name:') {
729               my $grade   = prompt 'Grade:', -integer;
730               my $comment = prompt 'Comment:';
731               ...
732           }
733
734       If you're entering a name, there's no point in prompt() offering to
735       complete it with previous grades or comments. In fact, that's just
736       annoying.
737
738       IO::Prompter allows you to specify that a particular call to prompt()
739       belongs to a particular "history set". Then it completes input history
740       using only the history of those calls belonging to the same history
741       set.
742
743       So the previous example could be improved like so:
744
745           while (my $name = prompt 'Name:', -hNAME) {
746               my $grade   = prompt 'Grade:', -hGRADE, -integer;
747               my $comment = prompt 'Comment:', -hOTHER;
748               ...
749           }
750
751       Now, when prompting for a name, only those inputs in the 'NAME' history
752       set will be offered as history completions. Likewise only previous
753       grades will be recalled when prompting for grades and earlier only
754       comments when requesting comments.
755
756       If you specify the "-h" or "-history" option without providing the name
757       of the required history set, prompt() uses the prompt text itself as
758       the name of the call's history set. So the previous example would work
759       equally well if written:
760
761           while (my $name = prompt 'Name:', -h) {
762               my $grade   = prompt 'Grade:', -h, -integer;
763               my $comment = prompt 'Comment:', -h;
764               ...
765           }
766
767       though now the names of the respective history sets would now be 'Name:
768       ', 'Grade: ', and 'Comment: '. This is by far the more common method of
769       specifying history sets, with explicitly named sets generally only
770       being used when two or more separate calls to prompt() have to share a
771       common history despite using distinct prompts. For example:
772
773           for my $n (1..3) {
774               $address .= prompt "Address (line $n):", -hADDR;
775           }
776
777       If you specify 'NONE' as the history set, the input is not recorded in
778       the history. This is useful when inputting passwords.
779
780       Configuring the autocompletion interaction
781
782       By default, when user-defined autocompletion is requested, the prompt()
783       subroutine determines the list of possible completions, displays it
784       above the prompt, and completes to the longest common prefix. If the
785       completion key is pressed again immediately, the subroutine then
786       proceeds to complete with each possible completion in a cyclic
787       sequence. This is known as "list+longest full" mode.
788
789       On the other hand, when historical completion is requested, prompt()
790       just immediately cycles through previous full inputs. This is known as
791       "full" mode.
792
793       You can change these behaviours by setting the
794       $IO_PROMPTER_COMPLETE_MODES and $IO_PROMPTER_HISTORY_MODES environment
795       variables before the module is loaded (either in your shell, or in a
796       "BEGIN" block before the module is imported).
797
798       Specifically, you can set the individual string values of either of
799       these variables to a whitespace-separated sequence containing any of
800       the following:
801
802           list         List all options above the input line
803
804           longest      Complete to the longest common prefix
805
806           full         Complete with each full match in turn
807
808       For example:
809
810           # Just list options without actually completing...
811           BEGIN{ $ENV{IO_PROMPTER_COMPLETE_MODES} = 'list'; }
812
813           # Just cycle full alternatives on each <TAB>...
814           BEGIN{ $ENV{IO_PROMPTER_COMPLETE_MODES} = 'full'; }
815
816           # For history completion, always start with the
817           # longest common prefix on the first <CTRL-R>,
818           # then just list the alternatives on a subsequent press...
819           BEGIN{ $ENV{IO_PROMPTER_HISTORY_MODES} = 'longest list'; }
820
821       Specifying what to return by default
822
823           "-DEF[AULT] => STRING"
824
825           "-def[ault] => STRING"
826
827           "-dSTRING"
828
829       If a default value is specified, that value will be returned if the
830       user enters an empty string at the prompt (i.e. if they just hit
831       "<ENTER>/<RETURN>" immediately) or if the input operation times out
832       under the "timeout" option.
833
834       Note that the default value is not added to the prompt, unless you do
835       so yourself. A typical usage might therefore be:
836
837           my $frequency
838               = prompt "Enter polling frequency [default: $DEF_FREQ]",
839                        -num, -def=>$DEF_FREQ;
840
841       You can determine if the default value was autoselected (as opposed to
842       the same value being typed in explicitly) by calling the defaulted()
843       method on the object returned by prompt(), like so:
844
845           if ($frequency->defaulted) {
846               say "Using default frequency";
847           }
848
849       If you use the "-must" option any default value must also satisfy all
850       the constraints you specify, unless you use the "-DEFAULT" form, which
851       skips constraint checking when the default value is selected.
852
853       If you use the "-menu" option, the specified default value will be
854       returned immediately "<ENTER>/<RETURN>" is pressed, regardless of the
855       depth you are within the menu. Note that the default value specifies
856       the value to be returned, not the selector key to be entered. The
857       default value does not even have to be one of the menu choices.
858
859       Specifying what to echo on input
860
861           "-echo => STR"
862
863           "-eSTR"
864
865       When this option is specified, the prompt() subroutine will echo the
866       specified string once for each character that is entered. Typically
867       this would be used to shroud a password entry, like so:
868
869           # Enter password silently:
870           my $passwd
871               = prompt 'Password:', -echo=>"";
872
873           # Echo password showing only asterisks:
874           my $passwd
875               = prompt 'Password:', -echo=>"*";
876
877       As a special case, if the "-echo" value contains a slash ("/") and the
878       any of the <-yesno> options is also specified, the substring before the
879       slash is taken as the string to echo for a 'yes' input, and the
880       substring after the slash is echoed for a 'no' input.
881
882       Note that this option is only available when the Term::ReadKey module
883       is installed. If it is used when that module is not available, a
884       warning will be issued.
885
886       Specifying how to echo on input
887
888       "-echostyle => SPECIFICATION"
889
890       The "-echostyle" option works for the text the user types in the same
891       way that the "-style" option works for the prompt.  That is, you can
892       specify the style and colour in which the user's input will be rendered
893       like so:
894
895           # Echo password showing only black asterisks on a red background:
896           my $passwd
897               = prompt 'Password:', -echo=>"*", -echostyle=>'black on red';
898
899       Note that "-echostyle" is completely independent of "-echo":
900
901           # Echo user's name input in bold white:
902           my $passwd
903               = prompt 'Name:', -echostyle=>'bold white';
904
905       The "-echostyle" option requires "Term::ANSIColor", and will be
906       silently ignored if that module is not available.
907
908       Input editing
909
910       When the Term::ReadKey module is available, prompt() also honours a
911       subset of the usual input cursor motion commands:
912
913       "CTRL-B"
914           Move the cursor back one character
915
916       "CTRL-F"
917           Move the cursor forward one character
918
919       "CTRL-A"
920           Move the cursor to the start of the input
921
922       "CTRL-E"
923           Move the cursor to the end of the input
924
925       Specifying when input should fail
926
927           "-fail => VALUE"
928
929           "-fSTRING"
930
931       If this option is specified, the final input value is compared with the
932       associated string or value, by smartmatching just before the call to
933       prompt() returns. If the two match, prompt() returns a failure value.
934       This means that instead of writing:
935
936           while (my $cmd = prompt '>') {
937               last if $cmd eq 'quit';
938               ...
939           }
940
941       you can just write:
942
943           while (my $cmd = prompt '>', -fail=>'quit') {
944               ...
945           }
946
947       Specifying when input should fail immediately
948
949           "-cancel => VALUE"
950
951           "-fSTRING"
952
953       If this option is specified, then each individual input character is
954       compared with the associated string or value, by smartmatching during
955       the input process.  If any individual input character matches the
956       string/value, prompt() immediately returns a failure value.
957
958       Note that this is not the same as the behaviour "-fail" option. A
959       "-fail" waits for the entire input to be completed (typically for a
960       RETURN to be entered) and then tests for failure. A "-cancel" tests
961       each input character as it is entered and fails immediately if any
962       input matches the cancellation condition.
963
964       Do, for example, to cancel a prompt whenever an ESCAPE character is
965       entered:
966
967           my $input = prompt '>', -cancel => "\e";
968
969       Note that (as long as Term::ReadKey is available) the cancellation test
970       is performed before any other internal processing, so you can set the
971       cancellation criterion to be any character, including characters like
972       CNTL-A or TAB, which otherwise have special meanings to prompt().
973
974       Note too that the cancellation criterion is tested against each
975       individual character as it is entered, not against the cumulative input
976       so far.  If you need to cancel a call to prompt() based on accumulated
977       input, you need to track that yourself. For example, if your
978       cancellation test is the presence of three consecutive exclamation
979       marks:
980
981           my $input = prompt '>', -cancel => sub ($nextchar) {
982                                       state $input;
983                                       $input .= $nextchar;
984                                       return $input =~ /!!!/;
985                                   };
986
987       Constraining what can be typed
988
989       "-guar[antee] => SPEC"
990
991       This option allows you to control what input users can provide.  The
992       specification can be a regex or a reference to an array or a hash.
993
994       If the specification is a regex, that regex is matched against the
995       input so far, every time an extra character is input. If the regex ever
996       fails to match, the guarantee fails.
997
998       If the specification is an array, the input so far is matched against
999       the same number of characters from the start of each of the (string)
1000       elements of the array. If none of these substrings match the input, the
1001       guarantee fails.
1002
1003       If the specification is a hash, the input so far is matched against the
1004       same number of characters from the start of each key of the hash. If
1005       none of these substrings match the input, the guarantee fails.
1006
1007       If the guarantee fails, the input is rejected (just as the "-must"
1008       option does). However, unlike "-must", "-guarantee" rejects the input
1009       character-by-character as it typed, and before it is even echoed. For
1010       example, if your call to prompt() is:
1011
1012           my $animal = prompt -guarantee=>['cat','dog','cow'];
1013
1014       then at the prompt:
1015
1016           > _
1017
1018       you will only be able to type in 'c' or 'd'. If you typed 'c', then you
1019       would only be able to type 'a' or 'o'. If you then typed 'o', you would
1020       only be able to type 'w'.
1021
1022       In other words, "-guarantee" ensures that you can only type in a valid
1023       input, and simply ignores any typing that would not lead to such an
1024       input.
1025
1026       To help users get the input right, specifying "-guarantee" as an array
1027       or hash reference also automatically specifies a "-complete" option
1028       with the array or hash as its completion list as well. So, whenever a
1029       "-guarantee" is in effect, the user can usually autocomplete the
1030       acceptable inputs.
1031
1032       Note, however, that "-guarantee" can only reject (or autocomplete)
1033       input as it is typed if the Term::ReadKey module is available. If that
1034       module cannot be loaded, "-guarantee" only applies its test after the
1035       "<ENTER>/<RETURN>" key is pressed, and there will be no autocompletion
1036       available.
1037
1038       Constraining input to numbers
1039
1040       "-i"
1041       "-integer [=> SPEC]"
1042       "-n"
1043       "-num[ber] [=> SPEC]"
1044
1045       If any of these options are specified, prompt() will only accept a
1046       valid integer or number as input, and will reprompt until one is
1047       entered.
1048
1049       If you need to restrict the kind of number further (say, to positive
1050       integers), you can supply an extra constraint as an argument to the
1051       long-form option. Any number entered must satisfy this constraint by
1052       successfully smart-matching it. For example:
1053
1054           $rep_count = prompt 'How many reps?', -integer => sub{ $_ > 0 };
1055
1056           $die_roll = prompt 'What did you roll?', -integer => [1..6];
1057
1058           $factor = prompt 'Prime factor:', -integer => \&is_prime;
1059
1060           $score = prompt 'Enter score:', -number => sub{ 0 <= $_ && $_ <= 100 };
1061
1062       If the constraint is specified as a subroutine, the entered number will
1063       be passed to it both as its single argument and in $_.
1064
1065       You cannot pass a scalar value directly as a constraint, except those
1066       strings listed below. If you want a scalar value as a constraint, use a
1067       regex or array reference instead:
1068
1069           # Wrong...
1070           $answer = prompt "What's the ultimate answer?",
1071                             -integer => 42;
1072
1073           # Use this instead...
1074           $answer = prompt "What's the ultimate answer?",
1075                            -integer => qr/^42$/;
1076
1077           # Or this...
1078           $answer = prompt "What's the ultimate answer?",
1079                            -integer => [42];
1080
1081       Only the following strings may be passed directly as scalar value
1082       constraints. They do mot match exactly, but instead act as specifiers
1083       for one or more built-in constraints. You can also pass a string that
1084       contains two or more of them, separated by whitespace, in which case
1085       they must all be satisfied. The specifiers are:
1086
1087       'pos' or 'positive'
1088           The number must be greater than zero
1089
1090       'neg' or 'negative'
1091           The number must be less than zero
1092
1093       'zero'
1094           The number must be equal to zero
1095
1096       'even' or 'odd'
1097           The number must have the correct parity
1098
1099       You can also prepend "non" to any of the above to reverse their
1100       meaning.
1101
1102       For example:
1103
1104           $rep_count = prompt 'How much do you bid?', -number => 'positive';
1105
1106           $step_value = prompt 'Next step:', -integer => 'even nonzero';
1107
1108       Constraining input to filenames
1109
1110       "-f"
1111       "-filenames"
1112
1113       You can tell prompt() to accept only valid filenames, using the
1114       "-filenames" option (or its shortcut: "-f").
1115
1116       This option is equivalent to the options:
1117
1118           -must => {
1119               'File must exist'       => sub { -e },
1120               'File must be readable' => sub { -r },
1121           },
1122           -complete => 'filenames',
1123
1124       In other words "-filenames" requires prompt() to accept only the name
1125       of an existing, readable file, and it also activates filename
1126       completion.
1127
1128       Constraining input to "keyletters"
1129
1130       "-k"
1131       "-key[let[ter]][s]"
1132
1133       A common interaction is to offer the user a range of actions, each of
1134       which is specified by keying a unique letter, like so:
1135
1136           INPUT:
1137           given (prompt '[S]ave, (R)evert, or (D)iscard:', -default=>'S') {
1138               when (/R/i) { revert_file()  }
1139               when (/D/i) { discard_file() }
1140               when (/S/i) { save_file()    }
1141               default     { goto INPUT;    }
1142           }
1143
1144       This can be cleaned up (very slightly) by using a guarantee:
1145
1146           given (prompt '[S]ave, (R)evert, or (D)iscard:', -default=>'S',
1147                         -guarantee=>qr/[SRD]/i
1148           ) {
1149               when (/R/i) { revert_file()  }
1150               when (/D/i) { discard_file() }
1151               default     { save_file()    }
1152           }
1153
1154       However, it's still annoying to have to specify the three key letters
1155       twice (and the default choice three times) within the call to prompt().
1156       So IO::Prompter provides an option that extracts this information
1157       directly from the prompt itself:
1158
1159           given (prompt '[S]ave, (R)evert, or (D)iscard:', -keyletters) {
1160               when (/R/i) { revert_file()  }
1161               when (/D/i) { discard_file() }
1162               default     { save_file()    }
1163           }
1164
1165       This option scans the prompt string and extracts any purely
1166       alphanumeric character sequences that are enclosed in balanced brackets
1167       of any kind (square, angle, round, or curly). It then makes each of
1168       these character sequences a valid input (by implicitly setting the
1169       "-guarantee" option), and adds the first option in square brackets (if
1170       any) as the "-default" value of the prompt.
1171
1172       Note that the key letters don't have to be at the start of a word,
1173       don't have to be a single character, and can be either upper or lower
1174       case.  For example:
1175
1176           my $action = prompt -k, '(S)ave, Save(a)ll, (Ex)it without saving';
1177
1178       Multi-character key letters are often a good choice for options with
1179       serious or irreversible consequences.
1180
1181       A common idiom with key letters is to use the "-single" option as well,
1182       so that pressing any key letter immediately completes the input,
1183       without the user having to also press "<ENTER>/<RETURN>":
1184
1185           given (prompt -k1, '[S]ave, (R)evert, or (D)iscard:') {
1186               when (/R/i) { revert_file()  }
1187               when (/D/i) { discard_file() }
1188               default     { save_file()    }
1189           }
1190
1191       Monitoring input
1192
1193       "-monitor => SUBREF"
1194
1195       This option allows you to specify a subroutine that will be called
1196       after each character is input. This subroutine will be passed two
1197       arguments: a string containing the input so far, and a hash reference
1198       containing various options passed into the call to prompt()
1199       (specifically: "-prompt", "-style", and "-echostyle").
1200
1201       The hashref contains an extra key ("-cursor_pos") whose value is the
1202       current location of the input cursor within the string. This is
1203       typically one character past the end of the string, but see "Input
1204       editing".
1205
1206       The subroutine can perform any actions you choose: set variables,
1207       validate input, print out a response to each input character.
1208
1209       If the subroutine prints anything out that will, of course, mess up the
1210       prompt and input echoing, so in that case the prompt will automatically
1211       be redrawn.  The prompt is also redrawn if the monitor subroutine
1212       throws an exception.
1213
1214       Monitor subroutines are useful for prvoding extra information during an
1215       input process. For example, when prompting for a filepath, as the path
1216       is being typed in you could echo all (partially) matching files with
1217       something like:
1218
1219           my $path = prompt 'File path:',
1220                             -monitor => sub ($path, $opts) {
1221                                            clear_screen();
1222                                            say for glob("$path*");
1223                                         };
1224
1225       Preserving terminal newlines
1226
1227       "-l"
1228       "-line"
1229
1230       The (encapsulated) string returned by prompt() is automatically chomped
1231       by default. To prevent that chomping, specify this option.
1232
1233       Constraining what can be returned
1234
1235       "-must => HASHREF"
1236
1237       This option allows you to specify requirements and constraints on the
1238       input string that is returned by prompt(). These limitations are
1239       specified as the values of a hash.
1240
1241       If the "-must" option is specified, once input is complete every value
1242       in the specified hash is smartmatched against the input text. If any of
1243       them fail to match, the input is discarded, the corresponding hash key
1244       is printed as an error message, and the prompt is repeated.
1245
1246       Note that the values of the constraint hash cannot be single strings or
1247       numbers, except for certain strings (such as 'pos', 'nonzero', or
1248       'even', as described in "Constraining input to numbers").
1249
1250       If you want to constrain the input to a single string or number (a very
1251       unusual requirement), just place the value in an array, or match it
1252       with a regex:
1253
1254           # This doesn't work...
1255           my $magic_word = prompt "What's the magic word?",
1256                                   -must => { 'be polite' => 'please' };
1257
1258           # Use this instead...
1259           my $magic_word = prompt "What's the magic word?",
1260                                   -must => { 'be polite' => ['please'] };
1261
1262           # Or, better still...
1263           my $magic_word = prompt "What's the magic word?",
1264                                   -must => { 'be polite' => qr/please/i };
1265
1266       The "-must" option allows you to test inputs against multiple
1267       conditions and have the appropriate error messages for each displayed.
1268       It also ensures that, when prompt() eventually returns, you are
1269       guaranteed that the input meets all the specified conditions.
1270
1271       For example, suppose the user is required to enter a positive odd prime
1272       number less than 100. You could enforce that with:
1273
1274           my $opnlt100 = prompt 'Enter your guess:',
1275                                 -integer,
1276                                 -must => { 'be odd'                 => 'odd',
1277                                            'be in range'            => [1..100],
1278                                            'It must also be prime:' => \&isprime,
1279                                          };
1280
1281       Note that, if the error message begins with anything except an
1282       uppercase character, the prompt is reissued followed by the error
1283       message in parentheses with the word "must" prepended (where
1284       appropriate).  Otherwise, if the error message does start with an
1285       uppercase character, the prompt is not reissued and the error message
1286       is printed verbatim. So a typical input sequence for the previous
1287       example might look like:
1288
1289           Enter your guess: 101
1290           Enter your guess: (must be in range) 42
1291           It must also be prime: 2
1292           Enter your guess: (must be odd) 7
1293
1294       at which point, the call to prompt() would accept the input and return.
1295
1296       See also the "-guarantee" option, which allows you to constrain inputs
1297       as they are typed, rather than after they are entered.
1298
1299       Changing how returns are echoed
1300
1301       "-r[STR]"
1302       "-ret[urn] [=> STR]"
1303
1304       When "<ENTER>/<RETURN>" is pressed, prompt() usually echoes a carriage
1305       return.  However, if this option is given, prompt() echoes the
1306       specified string instead. If the string is omitted, it defaults to
1307       "\n".
1308
1309       For example:
1310
1311           while (1) {
1312               my $expr = prompt 'Calculate:', -ret=>' = ';
1313               say evaluate($expr);
1314           }
1315
1316       would prompt for something like this:
1317
1318           Calculate: 2*3+4^5_
1319
1320       and when the "<ENTER>/<RETURN>" key is pressed, respond with:
1321
1322           Calculate: 2*3+4^5 = 1030
1323           Calculate: _
1324
1325       The string specified with "-return" is also automatically echoed if the
1326       "-single" option is used, or if an input is cancelled via the "-cancel"
1327       option.  So if you don't want the automatic carriage return that
1328       "-single" mode or "-cancel" supplies, specify "-return=>""".
1329
1330       Single-character input
1331
1332       "-s"
1333       -1
1334       "-sing[le]"
1335
1336       This option causes prompt() to return immediately once any single
1337       character is input. The user does not have to push the
1338       "<ENTER>/<RETURN>" key to complete the input operation. "-single" mode
1339       input is only available if the Term::ReadKey module can be loaded.
1340
1341       By default, prompt() echoes the single character that is entered. Use
1342       the "-echo" option to change or prevent that.
1343
1344           # Let user navigate through maze by single, silent keypresses...
1345           while ($nextdir = prompt "\n", -single, -echo, -guarantee=>qr/[nsew]/) {
1346               move_player($nextdir);
1347           }
1348
1349       Unless echoing has been disabled, by default prompt() also supplies a
1350       carriage return after the input character. Use the "-return" option to
1351       change that behaviour. For example, this:
1352
1353           my $question = <<END_QUESTION;
1354           Bast is the goddess of: (a) dogs  (b) cats  (c) cooking  (d) war?
1355           Your answer:
1356           END_QUESTION
1357
1358           my $response = prompt $question, -1, -return=>' is ', -g=>['a'..'d'];
1359           say $response eq $answer ? 'CORRECT' : 'incorrect';
1360
1361       prompts like this:
1362
1363           Bast is the goddess of: (a) dogs  (b) cats  (c) cooking  (d) war?
1364           Your answer: _
1365
1366       accepts a single character, like so:
1367
1368           Bast is the goddess of: (a) dogs  (b) cats  (c) cooking  (d) war?
1369           Your answer: b_
1370
1371       and completes the line thus:
1372
1373           Bast is the goddess of: (a) dogs  (b) cats  (c) cooking  (d) war?
1374           Your answer: b is CORRECT
1375           _
1376
1377       Returning raw data
1378
1379       "-v"
1380       "-verb[atim]"
1381
1382       Normally, prompt() returns a special object that contains the text
1383       input, the success value, and other information such as whether the
1384       default was selected and whether the input operation timed out.
1385
1386       However, if you prefer to have prompt() just return the input text
1387       string directly, you can specify this option.
1388
1389       Note however that, under "-verbatim", the input is still autochomped
1390       (unless you also specify the "-line" option.
1391
1392       Prompting on a clear screen
1393
1394       "-w"
1395       "-wipe[first]"
1396
1397       If this option is present, prompt() prints 1000 newlines before
1398       printing its prompt, effectively wiping the screen clear of other text.
1399
1400       If the "-wipefirst" variant is used, the wipe will only occur if the
1401       particular call to prompt() is the first such call anywhere in your
1402       program. This is useful if you'd like the screen cleared at the start
1403       of input only, but you're not sure which call to prompt() will happen
1404       first: just use "-wipefirst" on all possible initial calls and only the
1405       actual first call will wipe the screen.
1406
1407       Requesting confirmations
1408
1409       "-y[n]" or "-Y[N]"
1410       "-yes[no]" or "-Yes[No]"
1411       "-yes[no] => COUNT" or "-Yes[No] => COUNT"
1412
1413       This option invokes a special mode that can be used to confirm (or
1414       deny) something. If one of these options is specified, "prompt" still
1415       returns the user's input, but the success or failure of the object
1416       returned now depends on what the user types in.
1417
1418       A true result is returned if 'y' is the first character entered. If the
1419       flag includes an "n" or "N", a false result is returned if 'n' is the
1420       first character entered (and any other input causes the prompt to be
1421       reissued). If the option doesn't contain an "n" or "N", any input
1422       except 'y' is treated as a "no" and a false value is returned.
1423
1424       If the option is capitalized ("-Y" or "-YN"), the first letter of the
1425       input must be likewise a capital (this is a handy means of slowing down
1426       automatic unthinking "y"..."Oh no!" responses to potentially serious
1427       decisions).
1428
1429       This option is most often used in conjunction with the "-single"
1430       option, like so:
1431
1432           $continue = prompt("Continue? ", -yn1);
1433
1434       so that the user can just hit "y" or "n" to continue, without having to
1435       hit "<ENTER>/<RETURN>" as well.
1436
1437       If the optional COUNT argument is supplied, the prompting is repeated
1438       that many times, with increasingly insistent requests for confirmation.
1439       The answer must be "yes" in each case for the final result to be true.
1440       For example:
1441
1442           $rm_star = prompt("Do you want to delete all files? ", -Yes=>3 );
1443
1444       might prompt:
1445
1446           Do you want to delete all files?  Y
1447           Really?  Y
1448           Are you sure?  Y
1449
1450       Bundling short-form options
1451
1452       You can bundle together any number of short-form options, including
1453       those that take string arguments. For example, instead of writing:
1454
1455           if (prompt "Continue? ", -yes, -1, -t10, -dn) {
1456
1457       you could just write:
1458
1459           if (prompt "Continue? ", -y1t10dn) {...}
1460
1461       This often does not improve readability (as the preceding example
1462       demonstrates), but is handy for common usages such as "-y1" ("ask for
1463       confirmation, don't require an "<ENTER>/<RETURN>") or "-vl" ("Return a
1464       verbatim and unchomped string").
1465
1466       Escaping otherwise-magic options
1467
1468           "-_"
1469
1470       The "-_" option exists only to be an explicit no-op. It allows you to
1471       specify short-form options that would otherwise be interpreted as Perl
1472       file operators or other special constructs, simply by prepending or
1473       appending a "_" to them. For example:
1474
1475           my $input
1476               = prompt -l_;  # option -l, not the -l file operator.
1477
1478       The following single-letter options require an underscore to chaperone
1479       them when they're on their own: "-e", "-l", "-r", "-s", "-w", and "-y".
1480       However, an underscore is not required if two or more are bundled
1481       together.
1482
1483   Useful useless uses of prompt()
1484       Normally, in a void context, a call to prompt() issues a warning that
1485       you are doing an input operation whose input is immediately thrown
1486       away.
1487
1488       There is, however, one situation where this useless use of prompt() in
1489       a void context is actually useful:
1490
1491           say $data;
1492           prompt('END OF DATA. Press any key to exit', -echo, -single);
1493           exit;
1494
1495       Here, we're using prompt simply to pause the application after the data
1496       is printed. It doesn't matter what the user types in; the typing itself
1497       is the message (and the message is "move along").
1498
1499       In such cases, the "useless use..." warning can be suppressed using the
1500       "-void" option:
1501
1502           say $data;
1503           prompt('END OF DATA. Press any key to exit', -echo, -single, -void);
1504           exit;
1505
1506   Simulating input
1507       IO::Prompter provides a mechanism with which you can "script" a
1508       sequence of inputs to an application. This is particularly useful when
1509       demonstrating software during a presentation, as you do not have to
1510       remember what to type, or concentrate on typing at all.
1511
1512       If you pass a string as an argument to "use IO::Prompter", the
1513       individual lines of that string are used as successive input lines to
1514       any call to prompt(). So for example, you could specify several sets of
1515       input data, like so:
1516
1517           use IO::Prompter <<END_DATA
1518           Leslie
1519           45
1520           165
1521           Jessie
1522           28
1523           178
1524           Dana
1525           12
1526           120
1527           END_DATA
1528
1529       and then read this data in an input loop:
1530
1531           while (my $name   = prompt 'Name:') {
1532                  my $age    = prompt 'Age:';
1533                  my $height = prompt 'Height:';
1534
1535                  process($name, $age, $height);
1536           }
1537
1538       Because the "use IO::Prompter" supplies input data, the three calls to
1539       prompt() will no longer read data from *ARGV. Instead they will read it
1540       from the supplied input data.
1541
1542       Moreover, each call to prompt() will simulate the typing-in process
1543       automatically. That is, prompt() uses a special input mode where, each
1544       time you press a keyboard letter, it echoes not that character, but
1545       rather the next character from the specified input. The effect is that
1546       you can just type on the keyboard at random, but have the correct input
1547       appear. This greatly increases the convincingness of the simulation.
1548
1549       If at any point, you hit "<ENTER>/<RETURN>" on the keyboard, prompt()
1550       finishes typing in the input for you (using a realistic typing speed),
1551       and returns the input string. So you can also just hit
1552       "<ENTER>/<RETURN>" when the prompt first appears, to have the entire
1553       line of input typed for you.
1554
1555       Alternatively, if you hit "<ESC>" at any point, prompt() escapes from
1556       the simulated input mode for that particular call to prompt(), and
1557       allows you to (temporarily) type text in directly. If you enter only a
1558       single "<ESC>", then prompt() throws away the current line of simulated
1559       input; if you enter two "<ESC>"'s, the simulated input is merely
1560       deferred to the next call to prompt().
1561
1562       All these keyboard behaviours require the Term::ReadKey module to be
1563       available. If it isn't, prompt() falls back on a simpler simulation,
1564       where it just autotypes each entire line for you and pauses at the end
1565       of the line, waiting for you to hit "<ENTER>/<RETURN>" manually.
1566
1567       Note that any line of the simulated input that begins with a <CTRL-D>
1568       or <CTRL-Z> is treated as an input failure (just as if you'd typed that
1569       character as input).
1570

DIAGNOSTICS

1572       All non-fatal diagnostics can be disabled using a "no warnings" with
1573       the appropriate category.
1574
1575       "prompt(): Can't open *ARGV: %s"
1576           (F)  By default, prompt() attempts to read input from
1577                the *ARGV filehandle. However, it failed to open
1578                that filehandle. The reason is specified at the end of
1579                the message.
1580
1581       "prompt(): Missing value for %s (expected %s)"
1582           (F)  A named option that requires an argument was specified,
1583                but no argument was provided after the option. See
1584                "Summary of options".
1585
1586       "prompt(): Invalid value for %s (expected %s)"
1587           (F)  The named option specified expects an particular type
1588                of argument, but found one of an incompatible type
1589                instead. See "Summary of options".
1590
1591       "prompt(): Unknown option %s ignored"
1592           (W misc)  prompt() was passed a string starting with
1593                     a hyphen, but could not parse that string as a
1594                     valid option. The option may have been misspelt.
1595                     Alternatively, if the string was supposed to be
1596                     (part of) the prompt, it will be necessary to use
1597                     the "-prompt" option to specify it.
1598
1599       "prompt(): Unexpected argument (% ref) ignored"
1600           (W reserved)  prompt() was passed a reference to
1601                         an array or hash or subroutine in a position
1602                         where an option flag or a prompt string was
1603                         expected. This may indicate that a string
1604                         variable in the argument list didn't contain
1605                         what was expected, or a reference variable was
1606                         not properly dereferenced. Alternatively, the
1607                         argument may have been intended as the
1608                         argument to an option, but has become
1609                         separated from it somehow, or perhaps the
1610                         option was deleted without removing the
1611                         argument as well.
1612
1613       "Useless use of prompt() in void context"
1614           (W void)  prompt() was called but its return value was
1615                     not stored or used in any way. Since the
1616                     subroutine has no side effects in void context,
1617                     calling it this way achieves nothing. Either make
1618                     use of the return value directly or, if the usage
1619                     is deliberate, put a "scalar" in front of the
1620                     call to remove the void context.
1621
1622       "prompt(): -default value does not satisfy -must constraints"
1623           (W misc)  The "-must" flag was used to specify one or more
1624                     input constraints. The "-default" flag was also
1625                     specified. Unfortunately, the default value
1626                     provided did not satisfy the requirements
1627                     specified by the "-must" flag. The call to
1628                     prompt() will still go ahead (after issuing the
1629                     warning), but the default value will never be
1630                     returned, since the constraint check will reject
1631                     it. It is probably better simply to include the
1632                     default value in the list of constraints.
1633
1634       "prompt(): -keyletters found too many defaults"
1635           (W ambiguous)  The "-keyletters" option was specified,
1636                          but analysis of the prompt revealed two or
1637                          more character sequences enclosed in square
1638                          brackets. Since such sequences are taken to
1639                          indicate a default value, having two or more
1640                          makes the default ambiguous. The prompt
1641                          should be rewritten with no more than one set
1642                          of square brackets.
1643
1644       "Warning: next input will be in plaintext"
1645           (W bareword)  The prompt() subroutine was called with
1646                         the "-echo" flag, but the Term::ReadKey
1647                         module was not available to implement this
1648                         feature. The input will proceed as normal, but
1649                         this warning is issued to ensure that the user
1650                         doesn't type in something secret, expecting it
1651                         to remain hidden, which it won't.
1652
1653       "prompt(): Too many menu items. Ignoring the final %d"
1654           (W misc)  A "-menu" was specified with more than 52 choices.
1655                     Because, by default, menus use upper and lower-
1656                     case alphabetic characters as their selectors,
1657                     there were no available selectors for the extra
1658                     items after the first 52. Either reduce the number
1659                     of choices to 52 or less, or else add the
1660                     "-number" option to use numeric selectors instead.
1661

CONFIGURATION AND ENVIRONMENT

1663       IO::Prompter can be configured by setting any of the following
1664       environment variables:
1665
1666       $IO_PROMPTER_COMPLETE_KEY
1667           Specifies the key used to initiate user-specified completions.
1668           Defaults to <TAB>
1669
1670       $IO_PROMPTER_HISTORY_KEY
1671           Specifies the key used to initiate history completions.  Defaults
1672           to <CTRL-R>
1673
1674       $IO_PROMPTER_COMPLETE_MODES
1675           Specifies the response sequence for user-defined completions.
1676           Defaults to 'list+longest  full'
1677
1678       $IO_PROMPTER_HISTORY_MODES
1679           Specifies the response sequence for history completions.  Defaults
1680           to 'full'.
1681

DEPENDENCIES

1683       Requires the Contextual::Return module.
1684
1685       The module also works much better if Term::ReadKey is available (though
1686       this is not essential).
1687

INCOMPATIBILITIES

1689       This module does not play well with Moose (or more specifically, with
1690       Moose::Exporter) because both of them try to play sneaky games with
1691       Scalar::Util::blessed.
1692
1693       The current solution is to make sure that you load Moose before loading
1694       IO::Prompter. Even just doing this:
1695
1696           use Moose ();
1697           use IO::Prompter;
1698
1699       is sufficient.
1700

BUGS AND LIMITATIONS

1702       No unresolved bugs have been reported.
1703
1704       Please report any bugs or feature requests to
1705       "bug-io-prompter@rt.cpan.org", or through the web interface at
1706       <http://rt.cpan.org>.
1707

AUTHOR

1709       Damian Conway  "<DCONWAY@CPAN.org>"
1710
1712       Copyright (c) 2009, Damian Conway "<DCONWAY@CPAN.org>".  All rights
1713       reserved.
1714
1715       This module is free software; you can redistribute it and/or modify it
1716       under the same terms as Perl itself. See perlartistic.
1717

DISCLAIMER OF WARRANTY

1719       BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
1720       FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
1721       WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER
1722       PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND,
1723       EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1724       WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE
1725       ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH
1726       YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
1727       NECESSARY SERVICING, REPAIR, OR CORRECTION.
1728
1729       IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
1730       WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
1731       REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE
1732       TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR
1733       CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
1734       SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
1735       RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
1736       FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
1737       SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
1738       DAMAGES.
1739
1740
1741
1742perl v5.38.0                      2023-07-22                   IO::Prompter(3)
Impressum