Term::UI(3)

๐ŸŒธ NAME ๐ŸŒธ

Okay so this is the Term::UI(3) man page, and honestly? Term::UI is literally Term::ReadLine UI made easy. That's it, that's the vibe. ๐ŸŽ€


โœจ SYNOPSIS โœจ

Bestie, here's the whole thing in action, copy it, love it:

use Term::UI;
use Term::ReadLine;

my $term = Term::ReadLine->new('brand');

my $reply = $term->get_reply(
                prompt => 'What is your favourite colour?',
                choices => [qw|blue red green|],
                default => 'blue',
);

my $bool = $term->ask_yn(
                    prompt => 'Do you like cookies?',
                    default => 'y',
            );

my $string = q[some_command -option --no-foo --quux='this thing'];

my ($options,$munged_input) = $term->parse_options($string);

### don't have Term::UI issue warnings -- default is '1'
$Term::UI::VERBOSE = 0;

### always pick the default (good for non-interactive terms)
### -- default is '0'
$Term::UI::AUTOREPLY = 1;

### Retrieve the entire session as a printable string:
$hist = Term::UI::History->history_as_string;
$hist = $term->history_as_string;

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

Term::UI is a transparent way of eliminating the absolute overhead of having to format a question, then validate the reply, then tell the user their answer wasn't proper, then re-issue the question. So much work, so little time. ๐Ÿ˜ฎโ€๐Ÿ’จ

Instead you literally just hand it the question you want to ask โ€” optionally with the choices the user can pick from, plus a default โ€” and Term::UI will DWYM. Slay.

And for asking a yes-or-no question? There's even a shortcut. Iconic.


๐ŸŒˆ HOW IT WORKS ๐ŸŒˆ

Term::UI places itself at the back of the Term::ReadLine @ISA array, so you can call its functions straight through your term object. Main character energy, honestly. ๐Ÿ‘‘

It uses Term::UI::History to record all interactions with the commandline. You can retrieve that history, or alter the filehandle the interaction is printed to. Peep the Term::UI::History manpage or the SYNOPSIS for the details. ๐Ÿซถ


๐Ÿ’… METHODS ๐Ÿ’…

๐Ÿ’– $reply = $term->get_reply( prompt => 'question?', [choices => \@list, default => $list[0], preput => "text to put as default user input", multi => BOOL, print_me => "extra text to print & record", allow => $ref] );

get_reply asks the user a question, then returns the reply back to the caller. And if the answer is invalid (more on that below, don't worry), the question gets reposed until a satisfactory answer has been entered. Persistence! ๐Ÿ’ช

You've got the option of providing a list of choices the user can pick from with the choices argument. If the answer isn't in the list of choices you presented, the question gets reposed. No sneaky off-list answers, nope. ๐Ÿšซ

If you provide a default answer, that's what gets returned when either $AUTOREPLY is set to true (see the GLOBAL VARIABLES section further below, bestie) or when the user just hits enter. ๐ŸŽ€

The preput argument lets you specify a text that will be inserted into the prompt line as the initial input, which the user may edit, delete or accept. If you supply the empty string as the preput argument then the default value will be preputted. Heads up though: it'll only work if the underlying readline module provides support for it (right now it's supported only by the Term::Readline::Gnu). ๐Ÿ™ˆ

You can indicate that the user is allowed to enter multiple answers by toggling the multi flag. Note that a list of answers will then be returned to you, rather than a simple string. ๐Ÿ‘€

By specifying an allow handler you can yourself validate the answer a user gives. This can be any of the types that the Params::Check allow function allows, so please refer to that manpage for details. ๐Ÿ’œ

Finally, you've got the option of adding a print_me argument, which is simply printed before the prompt. It's printed to the same file handle as the rest of the questions, so you can use this to keep track of a full session of Q&A with the user, and retrieve it later using the Term::UI->history_as_string function. So organized. ๐Ÿ“

See the EXAMPLES section for samples of how to use this function.

๐Ÿ’– $bool = $term->ask_yn( prompt => "your question", [default => (y|1,n|0), print_me => "extra text to print & record"] )

Asks the user a simple "yes" or "no" question, and returns a boolean indicating "true" or "false" to the caller. Short and sweet. โœจ

The default answer will automatically be returned if the user hits enter, or if $AUTOREPLY is set to true. See the GLOBAL VARIABLES section further below. ๐Ÿ”ฅ

Also, you've got the option of adding a print_me argument, which is simply printed before the prompt. It's printed to the same file handle as the rest of the questions, so you can use this to keep track of a full session of Q&A with the user, and retrieve it later using the Term::UI->history_as_string function. Bestie, the receipts. ๐Ÿงพ

See the EXAMPLES section for samples of how to use this function.

๐Ÿ’– ($opts, $munged) = $term->parse_options( STRING );

parse_options will convert all options given from an input string into a hash reference. And if it's called in list context it will also return the part of the input string that it found no options in. Two for one, we love to see it. ๐ŸŽ

Consider this example:

my $str =   q[command --no-foo --baz --bar=0 --quux=bleh ] .
            q[--option="some'thing" -one-dash -single=blah' arg];

my ($options,$munged) =  $term->parse_options($str);

### $options would contain: ###
$options = {
            'foo'       => 0,
            'bar'       => 0,
            'one-dash'  => 1,
            'baz'       => 1,
            'quux'      => 'bleh',
            'single'    => 'blah\'',
            'option'    => 'some\'thing'
};

### and this is the munged version of the input string,
### ie what's left of the input minus the options
$munged = 'command arg';

As you can see, you can use either a single or a double "-" to indicate an option. If you prefix an option with "no-" and don't give it a value, it'll be set to 0. If it has no prefix and no value, it'll be set to 1. Otherwise, it'll be set to its value. Also note that it can deal fine with single/double quoting issues. Quoting drama? Not here. ๐Ÿ’€

๐Ÿ’– $str = $term->history_as_string

A convenience wrapper around Term::UI::History->history_as_string. ๐Ÿซถ

Consult the Term::UI::History man page for details.


๐Ÿ‘‘ GLOBAL VARIABLES ๐Ÿ‘‘

The behaviour of Term::UI can be altered by changing the following global variables:

๐ŸŒŸ $Term::UI::VERBOSE

This controls whether Term::UI will issue warnings and explanations as to why certain things may have failed. If you set it to 0, Term::UI will not output any warnings. The default is 1;

๐ŸŒŸ $Term::UI::AUTOREPLY

This will make every question be answered by the default, and warn if there was no default provided. This is particularly useful if your program is run in non-interactive mode. The default is 0;

๐ŸŒŸ $Term::UI::INVALID

This holds the string that will be printed when the user makes an invalid choice. You can override this string from your program if you, for example, wish to do localization. The default is "Invalid selection, please try again: "

๐ŸŒŸ $Term::UI::History::HISTORY_FH

This is the filehandle all the print statements from this module are being sent to. Please consult the Term::UI::History manpage for details. ๐ŸŽ€

This defaults to *STDOUT.

Okay bestie, that's the whole thing so far โ€” more is coming, don't go anywhere ๐Ÿ’…

๐Ÿ’– EXAMPLES ๐Ÿ’–

Okay bestie, this is the fun part โ€” actual little snippets of Term::UI in the wild. Copy the code exactly, even when the manpage is being a little chaotic ๐Ÿ˜ญโœจ

๐ŸŒธ Basic get_reply sample ๐ŸŒธ

Ask a human an open question about their fave colour:

### ask a user (with an open question) for their favourite colour
$reply = $term->get_reply( prompt => 'Your favourite colour? );

Which would look like:

Your favourite colour?

And $reply holds whatever text they typed. Slay.

๐ŸŽ€ get_reply with choices ๐ŸŽ€

Now give them a menu so they have to pick one:

### now provide a list of choices, so the user has to pick one
$reply = $term->get_reply(
            prompt  => 'Your favourite colour?',
            choices => [qw|red green blue|] );

Which would look like:

  1> red
  2> green
  3> blue

Your favourite colour?

$reply will hold one of the choices presented. If they type something that isn't in the list, Term::UI will re-pose the question โ€” no sneaky extra colours. The string it presents is held in $Term::UI::INVALID (peep GLOBAL VARIABLES for the details).

๐Ÿฆ‹ get_reply with choices and default ๐Ÿฆ‹

Add a sensible default โ€” everyone loves blue!

### provide a sensible default option -- everyone loves blue!
$reply = $term->get_reply(
            prompt  => 'Your favourite colour?',
            choices => [qw|red green blue|],
            default => 'blue' );

Which would look like:

  1> red
  2> green
  3> blue

Your favourite colour? [3]:

See that default answer after the prompt? Iconic. A user can now just hit enter (or set $Term::UI::AUTOREPLY โ€” GLOBAL VARIABLES again) and the sensible answer 'blue' will be returned.

๐Ÿ’… get_reply using print_me & multi ๐Ÿ’…

Let them pick more than one colour and add an intro text:

### allow the user to pick more than one colour and add an
### introduction text
@reply = $term->get_reply(
            print_me    => 'Tell us what colours you like',
            prompt      => 'Your favourite colours?',
            choices     => [qw|red green blue|],
            multi       => 1 );

Which would look like:

Tell us what colours you like
  1> red
  2> green
  3> blue

Your favourite colours?

An answer of 3 2 1 would fill @reply with "blue green red". Cute.

๐Ÿ”ฅ get_reply & allow ๐Ÿ”ฅ

Pose an open question but do a custom verification on the answer โ€” the question loop only exits if the answer matches the allow handler:

### pose an open question, but do a custom verification on
### the answer, which will only exit the question loop, if
### the answer matches the allow handler.
$reply = $term->get_reply(
            prompt  => "What is the magic number?",
            allow   => 42 );

Unless the user now enters 42, the question will be re-posed over and over again. You can use more sophisticated allow handlers โ€” even subroutines can be used. The allow handler is implemented using Params::Check's allow function, so check its manpage for the details. No cap.

๐Ÿ“ an elaborate ask_yn sample ๐Ÿ“

Ask if they like cookies, default to a sensible 'yes', and inform them first what cookies are:

### ask a user if he likes cookies. Default to a sensible 'yes'
### and inform him first what cookies are.
$bool = $term->ask_yn( prompt   => 'Do you like cookies?',
                       default  => 'y',
                       print_me => 'Cookies are LOVELY!!!' );

Would print:

Cookies are LOVELY!!!
Do you like cookies? [Y/n]:

If a user then simply hits enter, agreeing with the default, $bool would be set to "true". (Simply hitting 'y' would also return "true". Hitting 'n' would return "false".) Clean yes/no energy.

We could later retrieve this interaction by printing out the Q&A history as follows:

print $term->history_as_string;

Which would then print:

Cookies are LOVELY!!!
Do you like cookies? [Y/n]:  y

There's a chance we're doing this non-interactively, because a console is missing, the user indicated he just wanted the defaults, etc.

In this case, simply setting $Term::UI::AUTOREPLY to true will return from every question with the default answer set for the question. Do note: if AUTOREPLY is true, and no default is set, Term::UI will warn about this and return undef.

๐Ÿ”— See Also ๐Ÿ”—

  • Params::Check
  • Term::ReadLine
  • Term::UI::History

๐Ÿ› BUG REPORTS ๐Ÿ›

Please report bugs or other issues to <bug-term-ui@rt.cpan.org<gt>. Yes, bestie, that's exactly how the page writes it โ€” angle brackets and all ๐Ÿ˜ญ

๐Ÿ‘‘ AUTHOR ๐Ÿ‘‘

This module by Jos Boumans <kane@cpan.org>.

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


Okay, that's the whole page, bestie. The source/version footer vibe is perl v5.42.0, dated 2021-08-07, from Term::UI(3) โ€” slay and bye ๐Ÿ’…๐Ÿ’–

๐Ÿ“ฆ where this page comes from