IO::Prompter(3pm)

πŸ’– IO::Prompter(3pm) πŸ’–

User Contributed Perl Documentation β€” yep bestie, you're in the 3pm part of the manual, and this is the module that makes your terminal prompts stop being ugly and start being iconic. πŸ’…βœ¨


🏷️ NAME

IO::Prompter β€” Prompt for input, read it, clean it, return it.

That's it. That's the whole vibe. It asks, it listens, it tidies up, it hands you the goods. slay 🌈

πŸ”’ VERSION

This document describes IO::Prompter version 0.005004.

🌟 SYNOPSIS

use IO::Prompter;

while (prompt -num, 'Enter a number') {
    say "You entered: $_";
}

my $passwd
    = prompt 'Enter your password', -echo=>'*';

my $selection
    = prompt 'Choose wisely...', -menu => {
            wealth => [ 'moderate', 'vast', 'incalculable' ],
            health => [ 'hale', 'hearty', 'rude' ],
            wisdom => [ 'cosmic', 'folk' ],
      }, '>';

Okay look at this honestly. A while loop that just works because $_ is already holding the input, a password field that masks itself with *, and a whole interactive menu of responses. It's giving "I read the docs so you don't have to" energy. πŸ¦‹πŸŽ€

😭 CAVEATS

Bestie. I need you to actually read these. Both of them. They will bite you and I will not be surprised. 🫢
  1. Several features of this module are known to have problems under Windows. If you're using that platform, you may have more success (and less distress) by trying IO::Prompt::Tiny, IO::Prompt::Simple, or IO::Prompt::Hooked first.
  2. By default the prompt() subroutine does not return a string; it returns an object with overloaded string and boolean conversions. This object always evaluates true in boolean contexts, unless the read operation actually failed. This means that the object evaluates true even when the input value is zero or an empty string. See "Returning raw data" to turn off this (occasionally counter-intuitive) behaviour.

So yes, 0 is truthy. Yes, "" is truthy. It's an object, it's doing object things, and it's lowkey chaotic if you forget. πŸ’€


πŸ“– DESCRIPTION

IO::Prompter exports a single subroutine, prompt, that prints a prompt (but only if the program's selected input and output streams are connected to a terminal), then reads some input, then chomps it, and finally returns an object representing that text. That's the entire life cycle. It's a whole three-act play in one function call. ✨

The prompt() subroutine expects zero-or-more arguments.

Any argument that starts with a hyphen (-) is treated as a named option (many of which require an associated value, that may be passed as the next argument). See "Summary of options" and "Options reference" for details of the available options. πŸ‘‘

Any other argument that is a string is treated as (part of) the prompt to be displayed. All such arguments are concatenated together before the prompt is issued. If no prompt string is provided, the string '> ' is used instead. So if you just call prompt() with nothing, you get '> ' and honestly? It's a look. πŸ’…

Normally, when prompt() is called in either list or scalar context, it returns an opaque object that autoconverts to a string. In scalar boolean contexts this return object evaluates true if the input operation succeeded. In list contexts, if the input operation fails prompt() returns an empty list instead of a return object. This allows failures in list context to behave correctly (i.e. be false). 🧚

If you particularly need a list-context call to prompt() to always return a value (i.e. even on failure), prefix the call with scalar:

# Only produces as many elements
# as there were successful inputs...
my @data = (
    prompt(' Name:'),
    prompt('  Age:'),
    prompt('Score:'),
);

# Always produces exactly three elements
# (some of which may be failure objects)...
my @data = (
    scalar prompt(' Name:'),
    scalar prompt('  Age:'),
    scalar prompt('Score:'),
);

See the difference?? scalar is the "I need exactly three slots filled no matter what" move. Main character energy only. πŸ’œ

In void contexts, prompt() still requests input, but also issues a warning about the general uselessness of performing an I/O operation whose results are then immediately thrown away. See "Useful useless uses of prompt()" for an exception to this. (Yes, there's literally a section about useless uses being useful. We love a self-aware module.) πŸ“

The prompt() function also sets $_ if it is called in a boolean context but its return value is not assigned to a variable. Hence, it is designed to be a drop-in replacement for readline or <>. Which is why that while loop in the synopsis just works, iykyk. πŸ”₯


πŸ”Œ INTERFACE

All the options for prompt() start with a hyphen (-). Most have both a short and long form. The short form is always the first letter of the long form.

Most options have some associated value. For short-form options, this value is specified as a string appended to the option itself. The associated value for long-form options is always specified as a separated argument, immediately following the option (typically separated from it by a =>).

Note that this implies that short-form options may not be able to specify every possible associated value (for example, the short-form -d option cannot specify defaults with values 'efault' or '$%^!'). In such cases, just use the long form of the option (for example: -def => 'efault' or -default=>'$%^!'). Short forms are a vibe, not a cage. πŸ¦‹

πŸ“‹ Summary of options

Note: For options preceded by an asterisk, the short form is actually a Perl file operator, and hence cannot be used by itself. Either use the long form of these options, or bundle them with another option, or add a "no-op" to them.
  • -a, -argv β€” Prompt for @ARGV data if !@ARGV
  • -cancel=>SPEC β€” Immediately fail if input char smartmatches value
  • -comp[lete]=>SPEC β€” Complete input on <TAB>, as specified
  • -dSTR, -def[ault]=>STR β€” What to return if only <ENTER> typed
  • -DEF[AULT]=>STR β€” (as above, but skip any -must checking)
  • * -e[STR], -echo=>STR β€” Echo string for each character typed
  • -echostyle=>SPEC β€” What colour/style to echo input in
  • * -f, -filenames β€” Input should be name of a readable file
  • -fail=>VALUE β€” Return failure if completed input smartmatches value
  • -guar[antee]=>SPEC β€” Only allow the specified words to be entered
  • -h[STR], -hist[ory][=>SPEC] β€” Specify the history set this call belongs to
  • -in=>HANDLE β€” Read from specified handle
  • -indent=>NUM/STR β€” Indent each line of prompt by NUM cols or with STR
  • -i, -integer[=>SPEC] β€” Accept only valid integers (that smartmatch SPEC)
  • -k, -keyletters β€” Accept only keyletters (as specified in prompt)
  • * -l, -line β€” Don't autochomp
  • -menu=>SPEC β€” Specify a menu of responses to be displayed
  • -must=>HASHREF β€” Specify requirements/constraints on input
  • -monitor=>SUBREF β€” Specify a sub to be called on every character input
  • -n, -num[ber][=>SPEC] β€” Accept only valid numbers (that smartmatch SPEC)
  • -out=>HANDLE β€” Prompt to specified handle
  • -prefill=>STR β€” Start with the specified string pre-entered
  • -prompt=>STR β€” Specify prompt explicitly
  • * -rSTR, -ret[urn]=>STR β€” After input, echo this string instead of <CR>
  • * -s, -1, -sing[le] β€” Return immediately after first key pressed
  • -stdio β€” Use STDIN and STDOUT for prompting
  • -style=>SPEC β€” What colour/style to display the prompt text in
  • -tNUM, -time[out]=>NUM β€” Specify a timeout on the input operation
  • -v, -verb[atim] β€” Return the input string (no context sensitivity)
  • -void β€” Don't complain in void context
  • * -w, -wipe β€” Clear screen
  • -wipefirst β€” Clear screen on first prompt() call only
  • * -y, -yes [=> NUM] β€” Return true if [yY] entered, false otherwise
  • -yn, -yesno [=> NUM] β€” Return true if [yY] entered, false if [nN]
  • -Y, -Yes [=> NUM] β€” Return true if Y entered, false otherwise
  • -YN, -YesNo [=> NUM] β€” Return true if Y entered, false if N
  • * -_ β€” No-op (handy for bundling ambiguous short forms)

πŸͺ„ Automatic options

Any of the options listed above (and described in detail below) can be automatically applied to every call to prompt() in the current lexical scope, by passing them (via an array reference) as the arguments to a use IO::Prompter statement.

For example:

use IO::Prompter;

# This call has no automatically added options...
my $assent = prompt "Do you wish to take the test?", -yn;

{
    use IO::Prompter [-yesno, -single, -style=>'bold'];

    # These three calls all have: -yesno, -single, -style=>'bold' options
    my $ready = prompt 'Are you ready to begin?';
    my $prev  = prompt 'Have you taken this test before?';
    my $hints = prompt 'Do you want hints as we go?';
}

# This call has no automatically added options...
scalar prompt 'Type any key to start...', -single;

The current scope's lexical options are always prepended to the argument list of any call to prompt() in that scope. Free options, no copying and pasting, we stan. πŸ’–

To turn off any existing automatic options for the rest of the current scope, use:

use IO::Prompter [];

🎁 Prebound options

You can also ask IO::Prompter to export modified versions of prompt() with zero or more options prebound. For example, you can request an ask() subroutine that acts exactly like prompt() but has the -yn option pre-specified, or a pause() subroutine that is prompt() with a "canned" prompt and the -echo, -single, and -void options.

To specify such subroutines, pass a single hash reference when loading the module:

use IO::Prompter {
    ask     => [-yn],
    pause   => [-prompt=>'(Press any key to continue)', -echo, -single, -void],
}

Each key will be used as the name of a separate subroutine to be exported, and each value must be an array reference, containing the arguments that are to be automatically supplied.

The resulting subroutines are simply lexically scoped wrappers around prompt(), with the specified arguments prepended to the normal argument list, equivalent to something like:

my sub ask {
    return prompt(-yn, @_);
}

my sub pause {
    return prompt(-prompt=>'(Press any key to continue)', -echo, -single, -void, @_);
}

Note that these subroutines are lexically scoped, so if you want to use them throughtout a source file, they should be declared in the outermost scope of your program. (Yes, "throughtout" is spelled exactly like that in the original. Character for character. No cap. πŸ’€)

βš™οΈ Options reference

πŸ“ Specifying what to prompt

  • -prompt => STRING
  • -pSTRING

By default, any argument passed to prompt() that does not begin with a hyphen is taken to be part of the prompt string to be displayed before the input operation. Moreover, if no such string is specified in the argument list, the function supplies a default prompt ('> ') automatically.

The -prompt option allows you to specify a prompt explicitly, thereby enabling you to use a prompt that starts with a hyphen:

my $input
    = prompt -prompt=>'-echo';

or to disable prompting entirely:

my $input
    = prompt -prompt => "";

Note that the use of the -prompt option doesn't override other string arguments, it merely adds its argument to the collective prompt. Additive, not bossy. Queen behavior. πŸ‘‘

πŸ’… Prompt prettification

okay so real quick, if your prompt ends with a character that isn’t whitespace, prompt() is gonna add one single space after it, because it wants the output to look cute. but if your prompt ends with a newline, prompt() removes that newline so the input cursor stays right on the same line as the prompt. the way that ✨ formatting logic ✨ goes.

You can use that second thing to override the first if you need. Like, say you want your prompt to look like:

Load /usr/share/dict/_

(where _ is the input cursor). Then a call like:

$filename = prompt 'Load /usr/share/dict/';

wouldn’t work, bestie β€” it adds the space automatically, so you’d get:

Load /usr/share/dict/ _

But because a terminal newline gets removed, you can get the desired effect with:

$filename = prompt "Load /usr/share/dict/\n";

If you actually want a newline at the end of the prompt, like the input starts on the next line, just put two newlines at the end. Only the very last one gets removed. periodt πŸ’…


✨ Prompt position ✨

Sometimes when you’re doing a series of nested prompts, it’s lowkey useful to indent different prompts to different depths, so users can understand how the requested inputs relate to each other. Example:

Enter a new ID:
    Enter person's full name:
        Enter person's preferred name:
    Enter person's age:
    Enter person's status:

Enter a new ID:

To make that style easier, call prompt() with the -indent option. It expects either an integer (number of space characters to prepend to each output line) or a string (which is simply prepended to the prompt). Example to achieve the sequence shown earlier:

my $ID     = prompt( -indent=>0, 'Enter a new ID:');
my $name   = prompt( -indent=>4, 'Enter person's full name:');
my $pfname = prompt( -indent=>8, 'Enter person's preferred name:');
my $age    = prompt( -indent=>4, 'Enter person's age:');
my $status = prompt( -indent=>4, 'Enter person's status:');

Alternatively, specify the exact string to be prepended to each prompt by passing -indent anything other than an integer. Example:

use utf8;
my $ID     = prompt( -indent=>'', "Enter a new ID:");
my $name   = prompt( -indent=>'  ┣━━━ ', "Enter person's full name:");
my $pfname = prompt( -indent=>'  ┃      ┗━━━ ', "Enter person's preferred name:");
my $age    = prompt( -indent=>'  ┣━━━ ', "Enter person's age:");
my $status = prompt( -indent=>'  ┗━━━ ', "Enter person's status:");

...which would prompt with something like:

Enter a new ID:
  ┣━━━ Enter person's full name:
  ┃      ┗━━━ Enter person's preferred name:
  ┣━━━ Enter person's age:
  ┗━━━ Enter person's status:

Note that using -indent instead of just prepending the indent directly to the prompt means -indent gets applied to every line of a multiline prompt or menu, and also to any constraint-induced reprompts. iconic.


🎨 Specifying how the prompt looks 🎨

-style => SPECIFICATION

If Term::ANSIColor is available, this option specifies the colour and styling (bold, inverse, underlined, etc.) the prompt displays in.

You can specify styling as a single string:

prompt 'next:' -style=>'bold red on yellow';

or an array of styles:

prompt 'next:' -style=>['bold', 'red', 'on_yellow'];

The range of styles and colour names is extensive. All of these work as expected:

prompt 'next:' -style=>'bold red on yellow';

prompt 'next:' -style=>'strong crimson on gold';

prompt 'next:' -style=>'highlighted vermilion, background of cadmium';

prompt 'next:' -style=>'vivid russet over amber';

prompt 'next:' -style=>'gules fort on a field or';

But because Term::ANSIColor sometimes maps everything back to the standard eight ANSI text colours and seven ANSI text styles, all of the above may also be rendered identically. See that module's docs for details.

If Term::ANSIColor is not available, this option is silently ignored.

Please remember: up to 10% of people using your interface will have some form of colour vision impairment, so it’s always a good idea to differentiate info by style and colour, not colour alone. Example:

if ($dangerous_action) {
    prompt 'Really proceed?', -style=>'bold red underlined';
}
else {
    prompt 'Proceed?', -style=>'green';
}

Also remember: even though -style does support the 'blink' style, up to 99% of people using your interface will have Flashing Text Tolerance Deficiency. Just say "no". πŸ’€


πŸ“ Specifying where to prompt πŸ“

-out => FILEHANDLE

-in => FILEHANDLE

-stdio

The -out option (no short form) says where the prompt gets written. If you don’t specify it, prompts go to the currently select-ed filehandle. Most common usage:

prompt(out => *STDERR)

The -in option (also no short form) says where input should be read from. If not specified, input is read from the *ARGV filehandle. Most common usage:

prompt(in => *STDIN)

for those cases where *ARGV has been opened to a file but you still want to interact with the terminal (assuming *STDIN is opened to that terminal).

The -stdio option (again no short form) is just shorthand for: -in => *STDIN, -out => *STDOUT. Super useful when there are arguments on the commandline but you don’t want prompt treating those arguments as filenames for magic *ARGV reads.


⏳ Specifying how long to wait for input ⏳

-timeout => N

-tN

Normally, prompt() just waits for input. But you can use this option to set a timeout on the read operation. If no input arrives within the specified N seconds, the call to prompt() either returns the value specified by the -default option (if any), or else an object indicating the read failed.

Note: if the short form is used, N must be an integer. If the long form is used, N may be an integer or floating point value.

You can check whether an input operation timed out, even if a default value was returned, by calling the timedout() method on the object returned by prompt():

if (prompt('Continue?', -y1, -timeout=>60) && !$_->timedout) {
    ...
}

If a time-out occurred, the return value of timedout() is a string describing the timeout, like:

"timed out after 60 seconds"

✍️ Prefilling the input ✍️

-prefill => STRING

Normally, the cursor is placed right after the prompt, ready for input. Initially, there’s no input.

But with -prefill, you can initialize the input buffer with an arbitrary string of text instead of the usual empty string β€” as if that text had already been entered.

This is useful when a prompt is re-issued so the user can extend, truncate, or otherwise edit a previous input.


🍽️ Providing a menu of responses 🍽️

-menu => SPECIFICATION

You can limit allowable responses to a prompt by providing a menu.

A menu is specified using -menu, and the menu choices are the option's argument: a reference to an array, hash, or string, or else a literal string.

If the menu is a hash, prompt() displays the hash’s keys, sorted alphabetically, with each alternative marked by a single alphabetic character (its "selector key").

Example:

prompt 'Choose...',
       -menu=>{ 'live free'=>1, 'die'=>0, 'transcend'=>-1 },
       '>';

prompt() will display:

Choose...
    a. die
    b. live free
    c. transcend
> _

Then it only lets the user enter a valid selector key (in the example: 'a', 'b', or 'c'). Once an alternative is selected, prompt() returns the corresponding hash value (0, 1, or -1, respectively, in this case).

You can control sort order by prefixing one or more keys with an alphabetic control character (i.e. "\cA" to "\cZ"). The entire keys will still be sorted alphabetically, but the leading control characters will always sort before any other characters, and will then be automatically removed from the keys before they are displayed in the menu.

Example:

prompt 'Choose...',
       -menu=>{ "\cX live free"=>1,
                "\cY die"=>0,
                "\cZ transcend"=>-1 },
       '>';

prompt() will display:

Choose...
    a. live free
    b. die
    c. transcend
> _

Note that using alphabetics as selector keys inherently limits the number of usable menu items to 52. See "Numeric menus" for a way to overcome this limitation.

A menu is treated like a special kind of prompt, so any other prompt strings in the prompt() call appear either before or after the menu of choices, depending on whether they appear before or after the menu specification in the call to prompt().

If an array specifies the choices:

prompt 'Choose...',
       -menu=>[ 'live free', 'die', 'transcend' ],
       '>';

then each array element is displayed (in the original array order) with a selector key:

Choose...
    a. live free
    b. die
    c. transcend
> _

and prompt() returns the element corresponding to the selection (i.e. it returns 'live free' if 'a' is entered, 'die' if 'b' is entered, or 'transcend' if 'c' is entered).

So the difference between array and hash: array lets you control menu order, while hash lets you show one thing (the keys) but return something related (the values) instead.

If the argument after -menu is a string or a reference to a string, the option splits the string on newlines and treats the resulting list as if it were an array of choices. Useful, for example, to ask the user to select a filename:

my $files = `ls`;
prompt 'Select a file...', -menu=>$files, '>';

πŸ”’ Numbered menus πŸ”’

✨ Hierarchical menus ✨

okay so like we said, each menu item gets its own lil unique alphabetic selector key. BUT 🌟 if you also pass the -number or -integer option:

prompt 'Choose...',
       -number,
       -menu=>{ 'live free'=>1, 'die'=>0, 'transcend'=>-1 },
       '>';

then prompt() will number each menu item instead, using consecutive integers as the selector keys:

Choose...
    1. die
    2. live free
    3. transcend
> _

This means you can have literally unlimited alternatives in one single menu πŸ’… but β€” big caveat bestie 😭 β€” it prevents you from using -single for one-key selection from menus if the menu has more than nine items.


So if you use a hash to specify a menu, the values of that hash do NOT have to be strings. They can be references to nested hashes or arrays instead. ✨

Which means β€” hierarchical menus!!! 🌈 A selection at the top level can lead you to a secondary menu, and so on and so on, until an actual choice is finally possible. For example, this call to prompt:

my $choices = {
    animates => {
        animals => {
            felines => [qw<cat lion lynx>],
            canines => [qw<dog fox wolf>],
            bovines => [qw<cow ox buffalo>],
        },
        fish => [qw<shark carp trout bream>],
    },
    inanimates => {
        rocks     => [qw<igneous metamorphic sedimentary>],
        languages => [qw<Perl Python Ruby Tcl>],
    },
};

my $result = prompt -1, 'Select a species...', -menu=>$choices, '> ';

might result in an interaction like this:

Select a species...
a.  animates
b.  inanimates
> a

Select from animates:
a.  animals
b.  fish
> b

Select from fish:
a.  shark
b.  carp
c.  trout
d.  bream
> c

At which point, prompt() would return the string 'trout'. 🐟 slay.

Note that you can nest an arbitrary number of hashes, but that each "bottom" level choice has to be either a single string, or an array of strings. No cap 🧒


Within a hierarchical menu, the user has to either:

  • select a valid option (by entering the corresponding letter), or
  • request that they be taken back up a level in the hierarchy, by entering <ESC>.

And pressing <ESC> at the top level of a menu causes the call to prompt() to immediately return with failure. 🫠


πŸŽ€ Simulating a command-line πŸŽ€

  • -argv
  • -a

The prompt() subroutine can be used to request that the user provide command-line arguments interactively. When you ask for this, the input operation is only carried out if @ARGV is empty. πŸ‘‘

Whatever the user enters gets broken into a list and assigned to @ARGV.

The input is first globbed for file expansions, and has any environment variables (of the form $VARNAME) interpolated. The resulting string is then broken into individual words β€” except where parts of it contain single or double quotes, the contents of which are always treated as a single string. periodt.

This feature is most useful during development, to let a program be run from within an editor, and yet pass it a variety of command-lines. The typical usage is (at the start of a program):

use IO::Prompter;
BEGIN { prompt -argv }

However, because this pattern is so typical, there's a shortcut:

use IO::Prompter -argv;

You can also specify the name with which the program args are to be prompted, in the usual way (i.e. by providing a prompt):

use IO::Prompter -argv, 'demo.pl';

Note, however, the critical difference between that shortcut (which calls prompt -argv when the module is loaded) and:

use IO::Prompter [-argv];

(which sets -argv as an automatic option for every subsequent call to prompt() in the current lexical scope).

⚠️ Note too that the -argv option also implies -complete='filenames'.

πŸ”₯ Input autocompletion πŸ”₯

  • -comp[lete] => SPECIFICATION

When this option is specified, the prompt() subroutine will complete input using the specified collection of strings. By default, when completion is active, word completion is requested using the <TAB> key, but this can be changed by setting the $IO_PROMPTER_COMPLETE_KEY environment variable. Once completion has been initiated, you can use the completion key or else <CTRL-N> to advance to the next completion candidate. You can also use <CTRL-P> to back up to the previous candidate. πŸ’…

The specific completion mechanism can be defined either using a subroutine, an array reference, a hash reference, or a special string:

  • sub {...} β€” the possible completions are supplied by... whatever non-subroutine specification (as listed below) is returned when the subroutine is called. The subroutine is passed the words of the current input text, split on whitespace, as its argument list.
  • [...] β€” ...the elements of the array.
  • {...} β€” ...the keys of the hash.
  • 'filenames' β€” ...the list of files supplied by globbing the last whitespace-separated word of the input text.
  • 'dirnames' β€” ...the list of directories supplied by globbing the last whitespace-separated word of the input text.

If an array or hash is used, only those elements or keys that begin with the last whitespace-separated word of the current input are offered as completions. ✨

For example:

# Complete with the possible commands...
my $next_cmd
    = prompt -complete => \%cmds;

# Complete with valid usernames...
my $user
    = prompt -complete => \@usernames;

# Complete with valid directory names...
my $file
    = prompt -complete => 'dirnames';

# Complete with cmds on the first word, and filenames on the rest...
my $cmdline
    = prompt -complete => sub { @_ <= 1 ? \%cmds : 'filenames' };

🌸 Completing from your own input history 🌸

The prompt() subroutine also tracks previous input and allows you to complete with that instead. No special option is required, bestie β€” the feature is enabled by default. 🫢

At the start of a prompted input, the user can cycle backwards through previous inputs by pressing <CTRL-R> (this can be changed externally by setting the $IO_PROMPTER_HISTORY_KEY environment variable, or internally by assigning a new keyname to $ENV{IO_PROMPTER_HISTORY_KEY}). After the first <CTRL-R>, subsequent <CTRL-R>'s will recall earlier inputs. You can also use <CTRL-N> and <CTRL-P> (as in user-specified completions) to move back and forth through your input history. πŸ”

If the user has already typed some input, the completion mechanism will only show previous inputs that begin with that partial input. no cap.


πŸ‘‘ History sets πŸ‘‘

  • -h[NAME]
  • -hist[ory] [=> NAME]

By default, IO::Prompter tracks every call to prompt() within a program, and accumulates a single set of history completions for all of them. That means that, at any prompt, <CTRL-R> will take the user back through every previous input, regardless of which call to prompt() originally retrieved it. 😭

Sometimes that's useful, but sometimes you might prefer that different calls to prompt() retained distinct memories. For example, consider the following input loop:

while (my $name = prompt 'Name:') {
    my $grade   = prompt 'Grade:', -integer;
    my $comment = prompt 'Comment:';
    ...
}

If you're entering a name, there's no point in prompt() offering to complete it with previous grades or comments. In fact, that's just annoying. πŸ™ˆ

IO::Prompter allows you to specify that a particular call to prompt() belongs to a particular "history set". Then it completes input history using only the history of those calls belonging to the same history set. πŸ’–

So the previous example could be improved like so:

while (my $name = prompt 'Name:', -hNAME) {
    my $grade   = prompt 'Grade:', -hGRADE, -integer;
    my $comment = prompt 'Comment:', -hOTHER;
    ...
}

Now, when prompting for a name, only those inputs in the 'NAME' history set will be offered as history completions. Likewise only previous grades will be recalled when prompting for grades and earlier only comments when requesting comments. ✨

If you specify the -h or -history option without providing the name of the required history set, prompt() uses the prompt text itself as the name of the call's history set. So the previous example would work equally well if written:

while (my $name = prompt 'Name:', -h) {
    my $grade   = prompt 'Grade:', -h, -integer;
    my $comment = prompt 'Comment:', -h;
    ...
}

though now the names of the respective history sets would now be 'Name: ', 'Grade: ', and 'Comment: '. This is by far the more common method of specifying history sets, with explicitly named sets generally only being used when two or more separate calls to prompt() have to share a common history despite using distinct prompts. For example:

for my $n (1..3) {
    $address .= prompt "Address (line $n):", -hADDR;
}

If you specify 'NONE' as the history set, the input is not recorded in the history. This is useful when inputting passwords. πŸ”’ (iconic behaviour tbh)


🧚 Configuring the autocompletion interaction 🧚

By default, when user-defined autocompletion is requested, the prompt() subroutine determines the list of possible completions, displays it above the prompt, and completes to the longest common prefix. If the completion key is pressed again immediately, the subroutine then proceeds to complete with each possible completion in a cyclic sequence. This is known as "list+longest full" mode.

On the other hand, when historical completion is requested, prompt() just immediately cycles through previous full inputs. This is known as "full" mode.

You can change these behaviours by setting the $IO_PROMPTER_COMPLETE_MODES and $IO_PROMPTER_HISTORY_MODES environment variables before the module is loaded (either in your shell, or in a BEGIN block before the module is imported).

Specifically, you can set the individual string values of either of these variables to a whitespace-separated sequence containing any of the following:

  • list β€” List all options above the input line.
  • longest β€” Complete to the longest common prefix.
  • full β€” Complete with each full match in turn.

For example:

# Just list options without actually completing...
BEGIN{ $ENV{IO_PROMPTER_COMPLETE_MODES} = 'list'; }
           # Just cycle full alternatives on each <TAB>...
           BEGIN{ $ENV{IO_PROMPTER_COMPLETE_MODES} = 'full'; }

           # For history completion, always start with the
           # longest common prefix on the first <CTRL-R>,
           # then just list the alternatives on a subsequent press...
           BEGIN{ $ENV{IO_PROMPTER_HISTORY_MODES} = 'longest list'; }

✨ Specifying what to return by default ✨

bestie, if you want a default value to slide in when the user gives you absolutely nothing, here's the move:

  • -DEF[AULT] => STRING
  • -def[ault] => STRING
  • -dSTRING

If a <pink>default value</pink> is specified, that value will be returned if the user enters an empty string at the prompt (i.e. if they just hit <ENTER>/<RETURN> immediately) or if the input operation times out under the timeout option.

lowkey important: the default value is not added to the prompt, unless you do so yourself. A typical usage might therefore be:
my $frequency
    = prompt "Enter polling frequency [default: $DEF_FREQ]",
             -num, -def=>$DEF_FREQ;

You can determine if the default value was autoselected (as opposed to the same value being typed in explicitly) by calling the defaulted() method on the object returned by prompt(), like so:

if ($frequency->defaulted) {
    say "Using default frequency";
}

If you use the -must option any default value must also satisfy all the constraints you specify, unless you use the -DEFAULT form, which skips constraint checking when the default value is selected.

If you use the -menu option, the specified default value will be returned immediately <ENTER>/<RETURN> is pressed, regardless of the depth you are within the menu. Note that the default value specifies the value to be returned, not the selector key to be entered. The default value does not even have to be one of the menu choices.


🌸 Specifying what to echo on input 🌸

  • -echo => STR
  • -eSTR

When this option is specified, the prompt() subroutine will echo the specified string once for each character that is entered. Typically this would be used to shroud a password entry, like so:

# Enter password silently:
my $passwd
    = prompt 'Password:', -echo=>"";

# Echo password showing only asterisks:
my $passwd
    = prompt 'Password:', -echo=>"*";

As a special case, if the -echo value contains a slash ("/") and any of the -yesno options is also specified, the substring before the slash is taken as the string to echo for a 'yes' input, and the substring after the slash is echoed for a 'no' input.

ngl, this option is only available when the Term::ReadKey module is installed. If it is used when that module is not available, a warning will be issued.

πŸ’… Specifying how to echo on input πŸ’…

  • -echostyle => SPECIFICATION

The -echostyle option works for the text the user types in the same way that the -style option works for the prompt. That is, you can specify the style and colour in which the user's input will be rendered like so:

# Echo password showing only black asterisks on a red background:
my $passwd
    = prompt 'Password:', -echo=>"*", -echostyle=>'black on red';

Note that -echostyle is completely independent of -echo:

# Echo user's name input in bold white:
my $passwd
    = prompt 'Name:', -echostyle=>'bold white';

The -echostyle option requires Term::ANSIColor, and will be silently ignored if that module is not available.


πŸŽ€ Input editing πŸŽ€

When the Term::ReadKey module is available, prompt() also honours a subset of the usual input cursor motion commands:

  • CTRL-B β€” Move the cursor back one character
  • CTRL-F β€” Move the cursor forward one character
  • CTRL-A β€” Move the cursor to the start of the input
  • CTRL-E β€” Move the cursor to the end of the input

😭 Specifying when input should fail 😭

  • -fail => VALUE
  • -fSTRING

If this option is specified, the final input value is compared with the associated string or value, by smartmatching just before the call to prompt() returns. If the two match, prompt() returns a failure value. This means that instead of writing:

while (my $cmd = prompt '>') {
    last if $cmd eq 'quit';
    ...
}

you can just write:

while (my $cmd = prompt '>', -fail=>'quit') {
    ...
}

🫢 Specifying when input should fail immediately 🫢

  • -cancel => VALUE
  • -fSTRING

If this option is specified, then each individual input character is compared with the associated string or value, by smartmatching during the input process. If any individual input character matches the string/value, prompt() immediately returns a failure value.

Note that this is not the same as the behaviour -fail option. A -fail waits for the entire input to be completed (typically for a RETURN to be entered) and then tests for failure. A -cancel tests each input character as it is entered and fails immediately if any input matches the cancellation condition.

Do, for example, to cancel a prompt whenever an ESCAPE character is entered:

my $input = prompt '>', -cancel => "\e";

Note that (as long as Term::ReadKey is available) the cancellation test is performed before any other internal processing, so you can set the cancellation criterion to be any character, including characters like CNTL-A or TAB, which otherwise have special meanings to prompt().

Note too that the cancellation criterion is tested against each individual character as it is entered, not against the cumulative input so far. If you need to cancel a call to prompt() based on accumulated input, you need to track that yourself. For example, if your cancellation test is the presence of three consecutive exclamation marks:

my $input = prompt '>', -cancel => sub ($nextchar) {
                            state $input;
                            $input .= $nextchar;
                            return $input =~ /!!!/;
                        };

πŸ”₯ Constraining what can be typed πŸ”₯

  • -guar[antee] => SPEC

This option allows you to control what input users can provide. The specification can be a regex or a reference to an array or a hash.

If the specification is a regex, that regex is matched against the input so far, every time an extra character is input. If the regex ever fails to match, the guarantee fails.

If the specification is an array, the input so far is matched against the same number of characters from the start of each of the (string) elements of the array. If none of these substrings match the input, the guarantee fails.

If the specification is a hash, the input so far is matched against the same number of characters from the start of each key of the hash. If none of these substrings match the input, the guarantee fails.

If the guarantee fails, the input is rejected (just as the -must option does). However, unlike -must, -guarantee rejects the input character-by-character as it typed, and before it is even echoed. For example, if your call to prompt() is:

my $animal = prompt -guarantee=>['cat','dog','cow'];

then at the prompt:

> _

you will only be able to type in 'c' or 'd'. If you typed 'c', then you would only be able to type 'a' or 'o'. If you then typed 'o', you would only be able to type 'w'.

In other words, -guarantee ensures that you can only type in a valid input, and simply ignores any typing that would not lead to such an input.

To help users get the input right, specifying -guarantee as an array or hash reference also automatically specifies a -complete option with the array or hash as its completion list as well. So, whenever a -guarantee is in effect, the user can usually autocomplete the acceptable inputs.

Note, however, that -guarantee can only reject (or autocomplete) input as it is typed if the Term::ReadKey module is available. If that module cannot be loaded, -guarantee only applies its test after the <ENTER>/<RETURN> key is pressed, and there will be no autocompletion available.


🌈 Constraining input to numbers 🌈

  • -i
  • -integer [=> SPEC]
  • -n
  • -num[ber] [=> SPEC]

If any of these options are specified, prompt() will only accept a valid integer or number as input, and will reprompt until one is entered.

If you need to restrict the kind of number further (say, to positive integers), you can supply an extra constraint as an argument to the long-form option. Any number entered must satisfy this constraint by successfully smart-matching it. For example:

$rep_count = prompt 'How many reps?', -integer => sub{ $_ > 0 };

$die_roll = prompt 'What did you roll?', -integer => [1..6];

$factor = prompt 'Prime factor:', -integer => \&is_prime;

$score = prompt 'Enter score:', -number => sub{ 0 <= $_ && $_ <= 100 };

If the constraint is specified as a subroutine, the entered number will be passed to it both as its single argument and in $_.

You cannot pass a scalar value directly as a constraint, except those strings listed below. If you want a scalar value as a constraint, use a regex or array reference instead:

# Wrong...
$answer = prompt "What's the ultimate answer?",
                  -integer => 42;

# Use this instead...
$answer = prompt "What's the ultimate answer?",
                 -integer => qr/^42$/;

# Or this...
$answer = prompt "What's the ultimate answer?",
                 -integer => [42];

Only the following strings may be passed directly as scalar value constraints. They do not match exactly, but instead act as specifiers for one or more built-in constraints. You can also pass a string that contains two or more of them, separated by whitespace, in which case they must all be satisfied. The specifiers are:

  • 'pos' or 'positive' β€” The number must be greater than zero
  • 'neg' or 'negative' β€” The number must be less than zero
  • 'zero' β€” The number must be equal to zero
  • 'even' or 'odd' β€” The number must have the correct parity

You can also prepend "non" to any of the above to reverse their meaning.

For example:

$rep_count = prompt 'How much do you bid?', -number => 'positive';

$step_value = prompt 'Next step:', -integer => 'even nonzero';

πŸ¦‹ Constraining input to filenames πŸ¦‹

  • -f
  • -filenames

You can tell prompt() to accept only valid filenames, using the -filenames option (or its shortcut: -f).

This option is equivalent to the options:

-must => {
    'File must exist'       => sub { -e },
    'File must be readable' => sub { -r },
},
-complete => 'filenames',

In other words, -filenames means prompt() will only accept the name of a file that already exists and is readable β€” no ghost files, bestie β€” and it also switches on filename completion while it's at it. πŸ’…

πŸŽ€ Constraining input to "keyletters"

πŸ”‘ -k, -key[let[ter]][s]

Okay so a super common interaction is offering the user a menu of actions, each one picked by hitting a unique letter, like this:

INPUT:
given (prompt '[S]ave, (R)evert, or (D)iscard:', -default=>'S') {
    when (/R/i) { revert_file()  }
    when (/D/i) { discard_file() }
    when (/S/i) { save_file()    }
    default     { goto INPUT;    }
}

That's lowkey clunky, and you can clean it up (very slightly) with a guarantee:

given (prompt '[S]ave, (R)evert, or (D)iscard:', -default=>'S',
              -guarantee=>qr/[SRD]/i
) {
    when (/R/i) { revert_file()  }
    when (/D/i) { discard_file() }
    default     { save_file()    }
}

But honestly? Still annoying having to type those three key letters twice (and the default choice three times) inside the prompt() call. So IO::Prompter gives you an option that just... extracts all of that straight out of the prompt itself:

given (prompt '[S]ave, (R)evert, or (D)iscard:', -keyletters) {
    when (/R/i) { revert_file()  }
    when (/D/i) { discard_file() }
    default     { save_file()    }
}

Obsessed. Here's the tea on how it works: this option scans the prompt string and pulls out any purely alphanumeric character sequences that are enclosed in balanced brackets of any kind β€” square, angle, round, or curly, she doesn't discriminate. Then it makes each of those sequences a valid input (by implicitly setting the -guarantee option), and it adds the first option in square brackets (if there is one) as the -default value of the prompt. Iconic behaviour, no notes.

Also bestie, note that the key letters don't have to sit at the start of a word, don't have to be a single character, and can be upper or lower case. Like:

my $action = prompt -k, '(S)ave, Save(a)ll, (Ex)it without saving';

Multi-character key letters are often a great choice for options with serious or irreversible consequences. πŸ‘€

And a common idiom with key letters is to pair them with -single, so that pressing any key letter immediately completes the input and the user never has to hit ENTER/RETURN:

given (prompt -k1, '[S]ave, (R)evert, or (D)iscard:') {
    when (/R/i) { revert_file()  }
    when (/D/i) { discard_file() }
    default     { save_file()    }
}

πŸ‘€ Monitoring input

πŸ“‘ -monitor => SUBREF

This option lets you hand over a subroutine that gets called after every single character is input. She gets passed two arguments: a string containing the input so far, and a hash reference containing various options that were passed into the call to prompt() β€” specifically -prompt, -style, and -echostyle.

That hashref also carries an extra key, -cursor_pos, whose value is the current location of the input cursor within the string. Usually that's one character past the end of the string, but go read "Input editing" if you want the full lore.

The subroutine can do literally whatever you want: set variables, validate input, print out a response to every character the user types. Main character energy, truly.

Just know that if the subroutine prints anything out, that will of course mess up the prompt and the input echoing β€” so in that case the prompt gets automatically redrawn. The prompt is also redrawn if the monitor subroutine throws an exception.

Monitor subroutines are so useful for providing extra information during an input process. For example, when you're prompting for a filepath, as the path gets typed in you could echo all the (partially) matching files with something like:

my $path = prompt 'File path:',
                  -monitor => sub ($path, $opts) {
                                 clear_screen();
                                 say for glob("$path*");
                              };

🧡 Preserving terminal newlines

⏎ -l

⏎ -line

The (encapsulated) string returned by prompt() gets automatically chomped by default. To stop that chomping from happening, specify this option. That's it, that's the whole thing. 🫢

🚧 Constraining what can be returned

πŸ›‚ -must => HASHREF

This option lets you set requirements and constraints on the input string that comes back out of prompt(). You write those limitations as the values of a hash.

If -must is specified, then once input is complete, every value in that hash gets smartmatched against the input text. If any of them fail to match, the input is discarded, the corresponding hash key gets printed as an error message, and the prompt is repeated. So rude to the user, but so protective of your program. πŸ’€

Heads up: the values of the constraint hash can't just be single strings or numbers β€” except for certain strings, like 'pos', 'nonzero', or 'even', as described in "Constraining input to numbers".

So if you want to constrain the input to a single string or number (a very unusual requirement, ngl), just drop the value in an array, or match it with a regex:

# This doesn't work...
my $magic_word = prompt "What's the magic word?",
                        -must => { 'be polite' => 'please' };

# Use this instead...
my $magic_word = prompt "What's the magic word?",
                        -must => { 'be polite' => ['please'] };

# Or, better still...
my $magic_word = prompt "What's the magic word?",
                        -must => { 'be polite' => qr/please/i };

The -must option lets you test inputs against multiple conditions and have the appropriate error message shown for each one. It also guarantees that when prompt() finally returns, the input you're holding meets all of those conditions. Chef's kiss. ✨

For example, say the user has to enter a positive odd prime number less than 100. You could enforce that with:

my $opnlt100 = prompt 'Enter your guess:',
                      -integer,
                      -must => { 'be odd'                 => 'odd',
                                 'be in range'            => [1..100],
                                 'It must also be prime:' => \&isprime,
                               };

Okay now here's the important bit about how error messages get shown: if the error message begins with anything except an uppercase character, the prompt is reissued followed by the error message in parentheses, with the word "must" prepended (where appropriate). Otherwise β€” if the error message does start with an uppercase character β€” the prompt is not reissued and the error message gets printed verbatim. So a typical input sequence for the example above might look like:

Enter your guess: 101
Enter your guess: (must be in range) 42
It must also be prime: 2
Enter your guess: (must be odd) 7

...at which point the call to prompt() would accept the input and return. Slay. πŸŽ‰

See also the -guarantee option, which lets you constrain inputs as they're typed, instead of after they're entered. Different vibe, same goal.

πŸ’¬ Changing how returns are echoed

πŸ” -r[STR]

πŸ” -ret[urn] [=> STR]

When ENTER/RETURN gets pressed, prompt() usually echoes a carriage return. But if this option is given, prompt() echoes the string you specified instead. And if the string is omitted, it defaults to "\n".

For example:

while (1) {
    my $expr = prompt 'Calculate:', -ret=>' = ';
    say evaluate($expr);
}

would prompt for something like this:

Calculate: 2*3+4^5_

and when the ENTER/RETURN key is pressed, it responds with:

Calculate: 2*3+4^5 = 1030
Calculate: _

Okay and the string you set with -return is also automatically echoed if the -single option is used, or if an input gets cancelled via the -cancel option. So if you don't want that automatic carriage return that -single mode or -cancel supplies, specify -return=>"". Periodt.

⌨️ Single-character input

🎯 -s

🎯 -1

🎯 -sing[le]

This option makes prompt() return immediately the moment any single character is input. The user never has to push ENTER/RETURN to complete the input operation. Fyi though, -single mode input is only available if the Term::ReadKey module can be loaded.

By default, prompt() echoes the single character that gets entered. Use the -echo option to change that or prevent it entirely.

# Let user navigate through maze by single, silent keypresses...
while ($nextdir = prompt "\n", -single, -echo, -guarantee=>qr/[nsew]/) {
    move_player($nextdir);
}

Unless echoing has been disabled, prompt() also supplies a carriage return after the input character by default. Use the -return option to change that behaviour. For example, this:

my $question = <<END_QUESTION;
Bast is the goddess of: (a) dogs  (b) cats  (c) cooking  (d) war?
Your answer:
END_QUESTION

my $response = prompt $question, -1, -return=>' is ', -g=>['a'..'d'];
say $response eq $answer ? 'CORRECT' : 'incorrect';

prompts like this:

Bast is the goddess of: (a) dogs  (b) cats  (c) cooking  (d) war?
Your answer: _

accepts a single character, like so:

Bast is the goddess of: (a) dogs  (b) cats  (c) cooking  (d) war?
Your answer: b_

and completes the line thus:

Bast is the goddess of: (a) dogs  (b) cats  (c) cooking  (d) war?
Your answer: b is CORRECT
_

πŸ“¦ Returning raw data

πŸ—ƒοΈ -v

πŸ—ƒοΈ -verb[atim]

Normally, prompt() returns a special object that holds the text input, the success value, and other information like whether the default was selected and whether the input operation timed out. Very ✨encapsulated✨ of her.

But if you'd rather have prompt() just hand you the input text string directly, you can specify this option. No wrapper, no frills, just the goods.

Do note though that under -verbatim, the input is still autochomped (unless you also specify the -line option). So watch out for that.

🧼 Prompting on a clear screen

🌊 -w

🌊 -wipe[first]

If this option is present, prompt() prints 1000 newlines before printing its prompt, effectively wiping the screen clear of other text. Dramatic? Yes. Effective? Also yes. πŸ’…

If the -wipefirst variant is used, the wipe will only happen if this particular call to prompt() is the first such call anywhere in your program. This is useful if you want the screen cleared at the start of input only, but you're not sure which call to prompt() will actually happen first β€” just slap -wipefirst on all the possible initial calls and only the actual first call will wipe the screen. Multitasking queen. πŸ‘‘

βœ… Requesting confirmations

πŸ™‹ -y[n] or -Y[N]

πŸ™‹ -yes[no] or -Yes[No]

πŸ™‹ -yes[no] => COUNT or -Yes[No] => COUNT

This option invokes a special mode that can be used to confirm (or deny) something. If one of these options is specified, prompt still returns the user's input, but the success or failure of the object returned now depends on what the user types in.

A true result comes back if y is the very first character entered. If the flag has an n or an N in it, then a false result comes back if n is the first character entered (and literally any other input makes the prompt get reissued, like, it's waiting for you to commit πŸ’…). And if the option doesn't contain an n or N at all? Then every input except y counts as a "no", and you get a false value.

If the option is capitalized (-Y or -YN), then the first letter of the input has to be capitalized too β€” and bestie, this is the whole point: it's a handy means of slowing down automatic unthinking "y"…"Oh no!" responses to potentially serious decisions. 🫣 The shift key is your last line of defence.

This option is most often used in conjunction with the -single option, like so:

$continue = prompt("Continue? ", -yn1);

so that the user can just hit y or n to continue, without having to hit <ENTER>/<RETURN> as well. Slay, efficiency. ⭐

If the optional COUNT argument is supplied, the prompting is repeated that many times, with increasingly insistent requests for confirmation. The answer must be yes in each case for the final result to be true. For example:

$rm_star = prompt("Do you want to delete all files? ", -Yes=>3 );

might prompt:

Do you want to delete all files?  Y
Really?  Y
Are you sure?  Y

Three chances to change your mind, no cap. 😭

πŸŽ€ Bundling short-form options πŸŽ€

You can bundle together any number of short-form options, including those that take string arguments. For example, instead of writing:

if (prompt "Continue? ", -yes, -1, -t10, -dn) {

you could just write:

if (prompt "Continue? ", -y1t10dn) {...}

This often does not improve readability (as the preceding example demonstrates πŸ’€), but is handy for common usages such as -y1 ("ask for confirmation, don't require an <ENTER>/<RETURN>") or -vl ("Return a verbatim and unchomped string").

✨ Escaping otherwise-magic options ✨

  • -_ β€” the -_ option exists only to be an explicit no-op. It allows you to specify short-form options that would otherwise be interpreted as Perl file operators or other special constructs, simply by prepending or appending a _ to them. So it's basically a little chaperone for your options, fr fr.

For example:

my $input
    = prompt -l_;  # option -l, not the -l file operator.

The following single-letter options require an underscore to chaperone them when they're on their own: -e, -l, -r, -s, -w, and -y. However, an underscore is not required if two or more are bundled together. πŸ¦‹

πŸ’œ Useful useless uses of prompt() πŸ’œ

Normally, in a void context, a call to prompt() issues a warning that you are doing an input operation whose input is immediately thrown away.

There is, however, one situation where this useless use of prompt() in a void context is actually useful:

say $data;
prompt('END OF DATA. Press any key to exit', -echo, -single);
exit;

Here, we're using prompt simply to pause the application after the data is printed. It doesn't matter what the user types in; the typing itself is the message (and the message is "move along"). Iconic, honestly. ✨

In such cases, the "useless use…" warning can be suppressed using the -void option:

say $data;
prompt('END OF DATA. Press any key to exit', -echo, -single, -void);
exit;

🌈 Simulating input 🌈

IO::Prompter provides a mechanism with which you can "script" a sequence of inputs to an application. This is particularly useful when demonstrating software during a presentation, as you do not have to remember what to type, or concentrate on typing at all. Main character energy, and your hands are free. πŸ‘‘

If you pass a string as an argument to use IO::Prompter, the individual lines of that string are used as successive input lines to any call to prompt(). So for example, you could specify several sets of input data, like so:

use IO::Prompter <<END_DATA
Leslie
45
165
Jessie
28
178
Dana
12
120
END_DATA

and then read this data in an input loop:

while (my $name   = prompt 'Name:') {
       my $age    = prompt 'Age:';
       my $height = prompt 'Height:';

       process($name, $age, $height);
}

Because the use IO::Prompter supplies input data, the three calls to prompt() will no longer read data from *ARGV. Instead they will read it from the supplied input data.

Moreover, each call to prompt() will simulate the typing-in process automatically. That is, prompt() uses a special input mode where, each time you press a keyboard letter, it echoes not that character, but rather the next character from the specified input. The effect is that you can just type on the keyboard at random, but have the correct input appear. This greatly increases the convincingness of the simulation. ✨ It's giving. πŸ¦‹

If at any point, you hit <ENTER>/<RETURN> on the keyboard, prompt() finishes typing in the input for you (using a realistic typing speed), and returns the input string. So you can also just hit <ENTER>/<RETURN> when the prompt first appears, to have the entire line of input typed for you.

Alternatively, if you hit <ESC> at any point, prompt() escapes from the simulated input mode for that particular call to prompt(), and allows you to (temporarily) type text in directly. If you enter only a single <ESC>, then prompt() throws away the current line of simulated input; if you enter two <ESC>'s, the simulated input is merely deferred to the next call to prompt().

All these keyboard behaviours require the Term::ReadKey module to be available. If it isn't, prompt() falls back on a simpler simulation, where it just autotypes each entire line for you and pauses at the end of the line, waiting for you to hit <ENTER>/<RETURN> manually.

Note that any line of the simulated input that begins with a CTRL-D or CTRL-Z is treated as an input failure (just as if you'd typed that character as input). πŸ™ˆ

🩺 DIAGNOSTICS 🩺

All non-fatal diagnostics can be disabled using a no warnings with the appropriate category.

  • prompt(): Can't open *ARGV: %s
    • (F) By default, prompt() attempts to read input from the *ARGV filehandle. However, it failed to open that filehandle. The reason is specified at the end of the message.
  • prompt(): Missing value for %s (expected %s)
    • (F) A named option that requires an argument was specified, but no argument was provided after the option. See "Summary of options".
  • prompt(): Invalid value for %s (expected %s)
    • (F) The named option specified expects an particular type of argument, but found one of an incompatible type instead. See "Summary of options".
  • prompt(): Unknown option %s ignored
    • (W misc) prompt() was passed a string starting with a hyphen, but could not parse that string as a valid option. The option may have been misspelt. Alternatively, if the string was supposed to be (part of) the prompt, it will be necessary to use the -prompt option to specify it.
  • prompt(): Unexpected argument (% ref) ignored
    • (W reserved) prompt() was passed a reference to an array or hash or subroutine in a position where an option flag or a prompt string was expected. This may indicate that a string variable in the argument list didn't contain what was expected, or a reference variable was not properly dereferenced. Alternatively, the argument may have been intended as the argument to an option, but has become separated from it somehow, or perhaps the option was deleted without removing the argument as well.
  • Useless use of prompt() in void context
    • (W void) prompt() was called but its return value was not stored or used in any way. Since the subroutine has no side effects in void context, calling it this way achieves nothing. Either make use of the return value directly or, if the usage is deliberate, put a scalar in front of the call to remove the void context.
  • prompt(): -default value does not satisfy -must constraints
    • (W misc) The -must flag was used to specify one or more input constraints. The -default flag was also specified. Unfortunately, the default value provided did not satisfy the requirements specified by the -must flag. The call to prompt() will still go ahead (after issuing the warning), but the default value will never be returned, since the constraint check will reject it. It is probably better simply to include the default value in the list of constraints.
  • prompt(): -keyletters found too many defaults
    • (W ambiguous) The -keyletters option was specified, but analysis of the prompt revealed two or more character sequences enclosed in square brackets. Since such sequences are taken to indicate a default value, having two or more makes the default ambiguous. The prompt should be rewritten with no more than one set of square brackets.
  • Warning: next input will be in plaintext
    • (W bareword) The prompt() subroutine was called with the -echo flag, but the Term::ReadKey module was not available to implement this feature. The input will proceed as normal, but this warning is issued to ensure that the user doesn't type in something secret, expecting it to remain hidden, which it won't. 😬 Bestie, don't type your password here.
  • prompt(): Too many menu items. Ignoring the final %d
    • (W misc) A -menu was specified with more than 52 choices. Because, by default, menus use upper and lower-case alphabetic characters as their selectors, there were no available selectors for the extra items after the first 52. Either reduce the number of choices to 52 or less, or else add the -number option to use numeric selectors instead.

✨ CONFIGURATION AND ENVIRONMENT ✨

Okay so bestie, IO::Prompter is super configurable and it does it the easy way β€” through environment variables. Set any of these and the module picks them up automatically. No config files, no setup, just vibes 🫢

  • $IO_PROMPTER_COMPLETE_KEY β€” this is the key that kicks off user-specified completions. Defaults to <TAB> πŸ’…
  • $IO_PROMPTER_HISTORY_KEY β€” the key that kicks off history completions. Defaults to <CTRL-R> πŸŽ€
  • $IO_PROMPTER_COMPLETE_MODES β€” the response sequence for user-defined completions. Defaults to 'list+longest full'
  • $IO_PROMPTER_HISTORY_MODES β€” the response sequence for history completions. Defaults to 'full'

🌈 DEPENDENCIES

  • It requires the Contextual::Return module. Non-negotiable, it's giving essential πŸ’–
  • The module also works much better if Term::ReadKey is available β€” though this is not essential. So like, it's fine without it, but it thrives with it ✨

πŸ’€ INCOMPATIBILITIES

Bestie this one's important. This module does not play well with Moose β€” or more specifically, with Moose::Exporter. The reason is truly iconic: both of them try to play sneaky games with Scalar::Util::blessed. Two queens, one scalpel 😭

The current solution is literally just to make sure you load Moose before you load IO::Prompter. Even just doing this:

use Moose ();
use IO::Prompter;

is sufficient. That's it. That's the fix. Order matters, no cap πŸŽ€


πŸ¦‹ BUGS AND LIMITATIONS

No unresolved bugs have been reported. Periodt πŸ’…

Please report any bugs or feature requests to bug-io-prompter@rt.cpan.org, or through the web interface at <http://rt.cpan.org>. She's listening, she wants the feedback 🫢


πŸ‘‘ AUTHOR

Damian Conway <DCONWAY@CPAN.org>


Copyright (c) 2009, Damian Conway <DCONWAY@CPAN.org>. All rights reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic. So like, go off, remix it, we love that for you πŸ’–


πŸ™ˆ DISCLAIMER OF WARRANTY

Okay so legally I have to say this in the exact big scary way, so here it is, unedited, and yes it's all caps because that's the law being loud:

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

Translation: it's free, it's as-is, be nice, back up your data 🫢


and that's a wrap on IO::Prompter(3pm) β€” curated for perl v5.40.1, dated 2025-09-21, part 7 of 7, out of seven, we did it bestie πŸ’–βœ¨πŸŽ€

πŸ“¦ where this page comes from