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