Query(3pm)

πŸ“¦
version 2.0 Β· 2 versions
  • 2.0 Β· debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 2.0 Β· ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– Term::Query πŸ’–

okay bestie, pull up a chair and a lil snack because we're reading the Query(3pm) page together, from the User Contributed Perl Documentation. it's giving "old-school Perl module that does way more than you think", and honestly? it ate. πŸ’…


✨ NAME ✨

Term::Query β€” a table-driven query routine. that's it, that's the name, no notes. πŸŽ€


πŸ¦‹ SYNOPSIS πŸ¦‹

"use Term::Query"
                 "qw( query query_table query_table_set_defaults
                 query_table_process );"

"$result = query $prompt, $flags, [ $optional_args ];"

"$ok = query_table \@array;"

"query_table_set_defaults \@array;"

"$ok = query_table_process \@array, \&flagsub, \&querysub;"

look at those quotes. iconic behaviour honestly. 🌈


πŸ‘‘ DESCRIPTION πŸ‘‘

πŸ’œ query

the query subroutine is here to fulfill the need for a generalized question-response subroutine, and it comes with programmatic defaulting, validation, condition and error checking. so basically it's the whole package. 🫢

you hand it $prompt and $flags, and possibly some additional arguments depending on what characters are chillin' in $flags. then query issues a prompt to STDOUT and solicits input from STDIN. that input gets validated against a set of test criteria as configured by the characters in $flags. if any of the tests fail, an error message is noted, and the query is reattempted. we try again, bestie. we always try again. 😭

important vibe check: when STDIN is not a tty (aka not interactive), prompts are not issued, and errors cause a return rather than attempting to obtain more input.

you can disable that non-interactive behaviour by setting the variable $Foce_Interactive as below:

$Term::Query::Force_Interactive = 1;

when $Force_Interactive is a non-null, non-zero value, query will issue prompts, error messages, and ask for additional input even when the input is not interactive. πŸ’€

(yeah, the page spells it $Foce_Interactive in one spot and $Force_Interactive in the next. not me noticing. anyway, moving on. πŸ™ˆ)

🧚 query_table

the query_table subroutine performs multiple queries by invoking query, and it sets associated variables with the results of each query. the prompts, flags, and other arguments for each query are given in an array β€” called a query table β€” which is passed to the query_table subroutine by reference. slay.

🌸 query_table_set_defaults

the query_table_set_defaults subroutine causes any variables named in the given query table array to be assigned their corresponding default values, if any. this is a non-interactive subroutine. no chatting, just assigning. ✨

πŸŽ€ query_table_process

a general interface to processing a query table is available with the query_table_process subroutine. it accepts a query table array, and two subroutine references: a &flagsub and a &querysub. the &flagsub is invoked on each each flag character given in the $flags argument of the query table (see below). the &querysub is invoked for each query in the query table. πŸ¦‹

the query_table and query_table_set_defaults subroutines both use query_table_process to perform their functions. main character energy all the way down. πŸ‘‘

πŸ“ Query Table

the format of the query table array passed to query_table, query_table_set_defaults, and query_table_process subroutines is:

 @array = ( $prompt1, $flags1, [ $arglist1, ... ],
            $prompt2, $flags2, [ $arglist2, ... ],
            ...
            $promptN, $flagsN, [ $arglistN, ... ] );

in English: there are three items per query β€” a prompt string, a flags string, and an array of arguments. ⭐

heads up, bestie: the syntax used above uses [ ... ] to denote a Perl 5 anonymous array, not an optional set of arguments. don't let it gaslight you.

of course, if there are no arguments for a particular query, the corresponding anonymous array can be the null string or zero. easy.

the query table design is such that a query table can be created with a set of variables, their defaults, value constraints, and help strings, and it can be used to both initialize the variables' values and to interactively set their new values. the query_table_set_defaults subroutine performs the former, while query_table does the latter. two jobs, one table, we love efficiency. πŸ’œ

🌈 Flag Characters

with typical usage, given $prompt and $flags, query prints $prompt and then waits for input from the user. the handling of the response depends upon the flag characters given in the $flags string. 🫢

the flag characters indicate the type of input, how to process it, acceptable values, etc. some flags simply indicate the type or processing of the input, and do not require additional arguments. other flags require that subsequent arguments to the query subroutine be given. the arguments must be given in the same order as their corresponding flag characters. πŸ‘‘

the ordering of the flags in the $flags argument is important β€” it determines the ordering of the tests. for example, if both the a and m flags are given as "am", then this indicates that an after subroutine call should be performed first, followed by a regular expression match test. order matters, periodt. πŸ’…

all tests are applied in the order given in the $flags until a particular test fails. when a test fails, an error message is generated and the input is reattempted, except in the case of the I flag. noted. πŸ“

✨ Flag Characters Without Arguments ✨

  • i β€” the input must be an integer. πŸ”’
  • n β€” the input must be a number, real or integer.
  • Y β€” the input is a "yes" or "no", with a default answer of "yes". βœ…
  • N β€” the input is a "yes" or "no", with a default answer of "no". πŸ™…
  • r β€” some input is required; an empty response will be refused. this option is only meaningful when there is no default input (see the d flag character below).
  • s β€” strip and squeeze the input. leading and trailing blanks are eliminated, and embedded whitespace is "squeezed" to single blank characters. this flag is implied by the k and K flags. 🧹
  • H β€” do not treat input of ? as a request for help. this disables automatic help, unless implemented with the after (a flag) subroutine. πŸ™ˆ

πŸ’– Flag Characters With Arguments πŸ’–

the following flag characters indicate the presence of an argument to query. the arguments must occur in the same order as their corresponding flag characters. for example, if both the V and h flags are given as "Vh", then the first argument must be the variable name, and the next the help string, in that order. πŸŽ€

  • a \&after β€” the next argument is the after subroutine, to be invoked after the input has been solicited. this feature provides for an "open ended" input validation, completely at the control of the user of the Query module. the after subroutine is invoked in this manner:
&$after( \$input );

if the after sub returns an "undef", then query processing stops with an immediate "undef" return value.

if the after sub returns a null or zero value, then the input is rejected and resolicted. no error messages are displayed except the "Please try again." message.

since the after sub has the reference to the $input variable, it is free to change the value of input indirectly; ie:

$$input = $some_new_value;
  • b \&before β€” the next argument is the before subroutine, to be invoked before any input is attempted. if the before sub returns a non-null, non-zero value, the current query will be attempted. if a null or zero value is returned, the current query will be abandoned, with a null return.

this feature, used in a query table, allows for selective queries to be programmed by using before subs on the optional queries. for example, using the following anonymous sub as the b flag argument:

sub { $> == 0; }

will cause the corresponding query to only be issued for the "root" user. πŸ‘‘

the ordering of the b flag in the $flags argument is unimportant, since, by definition, this test is always performed before attempting any input. πŸ¦‹

  • d $default β€” the next argument is the default input. this string is used instead of an empty response from the user. the default value can be a scalar value, a reference to a scalar value, or a reference to a subroutine, which will be invoked for its result only if a default value is needed (no input is given). ⭐
  • h $help_string β€” the next argument is the help string, which is printed in response to an input of "?". in order to enter a ? as actual text, it must be prefixed with a backslash: "\?". πŸ†˜
  • k \@array β€” the next argument is a reference to an array of allowable keywords. the input is matched against the array elements in a case-insensitive manner, with unambiguous abbreviations allowed. this flag implies the s flag.

the matching can be made case-sensitive by setting the following variable prior to the invocation of query:

$Query::Case_sensitive = 1;

by default, this variable is null. πŸŽ€

  • K \@array β€” the next argument is a reference to an array of disallowed keywords. in this case, for the input to be unacceptable, it must match exactly, case-insensitive, one of the array elements. this flag implies the s flag.

the k option is useful for soliciting new, unique keywords to a growing list. adding new fields to a database, for example. πŸ—‚οΈ

the matching can be made case-sensitive by setting the $Query::Case_sensitive variable (see above).

  • l $maxlen β€” the next argument specifies the maximum length of the input. πŸ“
  • m $regular_expression β€” the next argument specifies a regular expression pattern against which the input will be matched. πŸ”
  • I $reference β€” the next argument is the input: either a simple scalar value, or a reference to a value, such as a "SCALAR" variable reference (eg: "\$somevar"), or a "CODE" reference (eg: "sub {..}"). in any case, the resulting value is used as input instead of reading from STDIN.
fr fr pay attention: if the input returned by the reference does not match other constraints, additional input is not attempted. an error message is noted, and an "undef" return is taken.

this option is handy for applications which have already acquired the input, and wish to use the validation features of "query". πŸ’…

it is also useful to embed a query definition in a query table which does not actually perform a query, but instead does a variable assignment dynamically, using the I reference value. ✨

  • J $reference β€” the next argument is the input reference, as with the I flag, except that if the input fails any of the constraints, additional input is solicited from the input. in other words, the J flag sets a one-time only input reference. think of it as jumping into the query loop with an initial input. πŸƒβ€β™€οΈπŸ’¨
  • V variable_name_or_ref β€” the next argument is the variable name or reference to receive the validated input as its value. this option, and its corresponding variable name, would normally be present on all entries used with query_table in order to retain to the values resulting from each query.

the value can either be a string representing the variable name, or a reference to a variable, eg: "\$some_var". 🫢

✨ Details ✨

okay so the tea is: query runs its checks basically in the same order you listed the flags in the flags argument β€” with some exceptions. Like, the before subroutine is always done before input. always. no skipping. πŸ’…

There are also sneaky implicit precedences in the ordering of some flag tests. Generally, each flag's test happens in the same order as the given flags. But some flag tests need other flags' tests to run first to even be effective. Example bestie: when you give the k flag and an s flag, stripping the input would only work if the strip happens on the input before testing it against the keyword table. In other words, s has precedence over k. So if you hand over the flags string as "ks", the effective ordering is still "sk". the math is mathing ✨

Here's the precedence chart of the flag tests:

  • i (int) β€” flags with higher precedence: s (strip), d (default), h (help)
  • k (key) β€” flags with higher precedence: s (strip), d (default), h (help)
  • K (nonkey) β€” flags with higher precedence: s (strip), d (default), h (help)
  • l (maxlen) β€” flags with higher precedence: d (default), h (help)
  • m (match) β€” flags with higher precedence: d (default), h (help)
  • n (numeric) β€” flags with higher precedence: s (strip), d (default), h (help)
  • N (no) β€” flags with higher precedence: s (strip), d (default), h (help)
  • r (required) β€” flags with higher precedence: d (default), h (help)
  • s (strip) β€” flags with higher precedence: d (default), h (help)
  • Y (yes) β€” flags with higher precedence: s (strip), d (default), h (help)

Other than the implied precedence in the chart above, the ordering of the flag tests goes in the same order as given in the flags argument. fr fr.

So, aside from those precedences, query processing goes generally like this:

  • If the b flag was given, the "before" subroutine is invoked as a "pre-input" test. If the sub returns a 0, empty string, or undef, the query is abandoned. Otherwise, processing continues.
  • If the I or J flags were given, then input is obtained, without prompting, from the associated reference. If the reference type is "CODE", then it gets invoked and the resulting return value is used as the input. Otherwise the reference is evaluated in a scalar context and used as the input. The J flag test is only done once, on the first entry into the input loop. one and done 🫢
  • In the absence of either the I or J flags, "query" will issue the given prompt and get input from STDIN. If an EOF happens, an "undef" value is the result.
  • The input gets examined for "null" input (aka the empty string), and processing quits in that case. Since most input comes from STDIN, a null input means an end-of-file (EOF). If the input is not null, a terminating newline is removed, and the input testing continues. At this point, an empty input string does not mean an EOF. important distinction bestie.
  • If the s, k, or K flags were given, the input gets trimmed of leading and trailing blanks, and all whitespace is "squeezed" to single blanks.
  • If the input is an empty response, and there's a default input (the d flag), use that instead.
  • Unless the H flag is given, if the input is the character "?" with nothing else, then some helpful info gets printed. If the user supplied a help string, that gets printed; otherwise the message:
You are being asked "$prompt"

is displayed. Also, some info about the expected response β€” according to any given flag characters β€” is displayed. Finally, the user gets sent back to the prompt, and gets another opportunity to enter a response.

  • If input is required (that's the r flag), and if the input is empty, produce an error message, and query again.
  • If there was an a flag, the corresponding after subroutine is invoked with the input reference as its argument. If the subroutine returns a non-null, non-zero value, the input succeeds; otherwise it fails. It's up to the after subroutine to display any appropriate error messages.
  • If the query was flagged Y or N, match the input against the pattern:
/^(y(es?)?|no?)$/i

If the match fails, print an error message, and query again. When the match succeeds, replace the input with the complete word "yes" or "no";

  • If an integer response is required (i flagged), check for integer input. If it's not an integer, print an error, and query again. A successful integer input is returned.
  • If a numeric response is required (n flagged), check for proper numeric input (either integer or real format). Errors produce a warning, and another query.
  • If the query was given a keyword table (flagged with k), the input is matched against the allowable keyword list. If an exact match is found, the keyword is returned as the input. Failing an exact match, an abbreviation search is performed against the keywords. If a single match is found, it's returned as the input. If no match is found, an error message is produced, and the user gets returned to the query to try again. Otherwise, the input was ambiguous β€” an error gets noted showing the matches, and the user is queried again.

The matching is case-insensitive or not, according to the value of the variable $Query::Case_sensitive, which is nil by default. The variable may be set by the user to change the matching from case-insensitive to case-sensitive.

  • If the query was given an unacceptable keyword list (flagged with K), the input is compared against the unacceptable keywords. If it matches any keywords exactly, an error is noted, and the query is performed again.

The matching is case-insensitive by default. Set the variable $Query::Case_sensitive to a non-null, non-zero value to make the keyword matching case-sensitive.

  • If the query was m flagged with a Perl regular expression pattern, then the input is matched against the pattern. Failures get noted with an error message, and the query reattempted.
  • If the query was l flagged with a maximum input length, the length of the input is checked against the maximum. A length violation gets noted with an error message and the user is queried again.
  • If the query has a variable defined with the V flag, the variable is assigned the input string. This is always done last, after and only if all tests are successful. πŸ‘‘

If the variable is a string name and not qualified with a package name (ie: $foo::variable), then the variable is qualified at the level outside of the Query.pm module.

  • Finally, having passed whatever conditions were flagged, the input is returned to the user. slay. ✨

🌸 EXAMPLE 🌸

Here are some typical usage samples:

  • To perform a simple "yes" or "no" query, with "no" as the default answer:
$ans = &query("Do you wish to quit? (yn)",'N');
  • An equivalent alternative is:
query "Do you wish to quit? (yn)", 'NV', \$ans;
  • To perform the same query, with some supplied helpful information:
$ans = &query("Do you wish to quit? (yn)",'Nh',<<'EOF');
You are being asked if you wish to quit.  If you answer "yes",
then all changes will be lost.  An answer of "no", will allow
you to return to continue making changes.
EOF
  • To solicit an integer input:
$mode = &query("Please enter the file mode:",'idh','644',<<'EOF');
Please enter the 3 digit numeric file mode; if you are unsure
of how the file mode is used, please see the man page for "chmod".
EOF
  • To solicit one of several keywords:
@keys = split(' ','SGI DEC IBM Sun HP Apple');
$vendor = &query('Please enter a vendor:','rkd',\@keys,'SGI');
  • To solicit a new, unique keyword to be used as a database field name, with a regexp pattern to check it against:
@fields = split(' ','Index Vendor Title'); # existing fields
$newfield = &query('New field name:','rKm',\@fields,'^\w+$');

🌈 ENVIRONMENT 🌈

  • COLUMNS β€” This variable is used to control the width of output when listing the keyword arrays. If it's not defined, 80 is used by default.

🧚 DEPENDENCIES 🧚

  • Carp.pm β€” Used to produce usage error messages.
  • Array::PrintCols::print_cols β€” Used to produce displays of the keyword arrays.

πŸŽ€ FILES πŸŽ€

None. that's it bestie, nothing here πŸ’€


πŸ‘‘ AUTHOR πŸ‘‘

Copyright (C) 1995 Alan K. Stebbins <aks@hub.ucsb.edu>

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.


okay so this is the part where the page talks back to you β€” every single way query can yell at your input, plus the very dramatic BUGS section. buckle up πŸ’–

πŸ’… DIAGNOSTICS πŸ’…

  • Input is required. β€” you hit enter on an empty response and there's no default input to fall back on. bestie it's giving nothing, and Query is not impressed. 😭
  • Please answer with 'yes' or 'no', or enter '?' for help. β€” this one shows up on Y or N flagged queries when your input just isn't reconizeable as a yes or a no. (yes, that's the spelling in the actual message, i don't make the rules 🫢)
  • Please enter an integer number. β€” printed the moment you give non-integer input to an i flagged query. whole numbers only, no decimals, no vibes. πŸ”’
  • Please enter a number, real or integer. β€” printed when you give non-numeric input to an n flagged query. real or integer, either is slay, but it has to be a number. ✨
  • The input '$input' is ambiguous; it matches the following: β€” issued in response to k flagged queries when your input matches more than one of the allowed keywords. the $input gets substituted in, and it lists out what it matched. πŸ’€
  • The input '$input' fails to match any of the allowed keywords: β€” printed when the input to a k flagged query matches none of the keywords. zero. nada. not one. πŸ™ˆ
  • The input '%s' matches a disallowed keyword '%s'. β€” printed when your input matches one of the unacceptable keywords you handed over on a K flagged query. you had ONE job. πŸ‘‘
  • '%s' fails to match '%s' β€” this one is the result of input failing to match the regular expression given on an m flagged query. regex said no. 🧚
  • Input is %d characters too long; cannot exceed %d characters. β€” your input's length blew past the maximum length you gave with the l flag argument. too much main character energy for the box it's in. 🌸
  • Please try again, or enter '?' for help. β€” yeah. this one just stands there on its own, offering you a second chance and a little help. πŸ₯Ί
  • query: The k flag needs an array reference. β€” the next argument in the argument list to query wasn't an array reference. it needed an array ref, it got something else, and it's telling you directly. πŸ”₯
  • query: The K flag needs an array reference. β€” the next argument in the argumentlist to query wasn't an array reference. same situation, capital-K flavour. (yes, "argumentlist" is one word here β€” that's genuinely how it's written, no cap.) πŸ’œ

😳 BUGS 😳

not a single bug listed. the section is literally just vibes and a blank space. iconic of it, honestly β€” no known bugs documented, nothing to warn you about, the page just closes the curtain. πŸŽ€


and that's the whole page, bestie!! πŸ¦‹ this was Query(3pm) from perl v5.34.0, dated 2022-06-17 β€” go forth, prompt your users, and slay responsibly πŸ’–βœ¨πŸŽ€πŸ«Ά