SEARCH
NEW RPMS
DIRECTORIES
ABOUT
FAQ
VARIOUS
BLOG
DONATE




YUM REPOSITORY

 
 

Query

Section: User Contributed Perl Documentation (3)
Updated: 1996-10-22
Index 

NAME

Term::Query - Table-driven query routine. 

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;" 

DESCRIPTION

 

query

The query subroutine fulfills the need for a generalizedquestion-response subroutine, with programmatic defaulting, validation,condition and error checking.

Given $prompt and $flags, and possibly additional arguments,depending upon the characters in $flags, query issues a prompt toSTDOUT and solicits input from STDIN. The input is validated against aset of test criteria as configured by the characters in $flags; ifany of the tests fail, an error message is noted, and the query isreattempted.

When STDIN is not a tty (not interactive), prompts are not issued, anderrors cause a return rather than attempting to obtain more input.This non-interactive behaviour can be disabled by setting the variable$Foce_Interactive as below:

    $Term::Query::Force_Interactive = 1;

When $Force_Interactive is a non-null, non-zero value, querywill issue prompts, error messages, and ask for additional inputeven when the input is not interactive. 

query_table

The query_table subroutine performs multiple queries, by invokingquery, setting associated variables with the results of each query.Prompts, flags, and other arguments for each query are given in anarray, called a query table, which is passed to the query_tablesubroutine by reference. 

query_table_set_defaults

The query_table_set_defaults subroutine causes any variables named inthe given query table array to be assigned their correspondingdefault values, if any. This is a non-interactive subroutine. 

query_table_process

A general interface to processing a query table is available with thequery_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 &querysubis invoked for each query in the query table.

The query_table and query_table_set_defaults subroutines both usequery_table_process to perform their functions. 

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, aflags string, and an array of arguments. Note that the syntax usedabove uses "[ ... ]" to denote a Perl 5 anonymous array, not anoptional set of arguments. Of course, if there are no arguments for aparticular query, the corresponding anonymous array can be the nullstring or zero.

The query table design is such that a query table can be created with aset of variables, their defaults, value constraints, and help strings,and it can be used to both initialize the variables' values and tointeractively set their new values. The query_table_set_defaultssubroutine performs the former, while query_table does the latter. 

Flag Characters

With typical usage, given $prompt and $flags, query prints$prompt and then waits for input from the user. The handling of theresponse 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 orprocessing of the input, and do not require additional arguments. Otherflags require that subsequent arguments to the query subroutine begiven. The arguments must be given in the same order as theircorresponding flag characters.

The ordering of the flags in the $flags argument is important --- itdetermines the ordering of the tests. For example, if both the a andm flags are given as "am", then this indicates that an aftersubroutine call should be performed first, followed by a regularexpression match test.

All tests are applied in the order given in the $flags until aparticular test fails. When a test fails, an error message is generatedand the input is reattempted, except in the case of the I flag. 

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. Thisoption is only meaningful when there is no default input (see the dflag character below).
s
Strip and squeeze the input. Leading and trailing blanks areeliminated, and embedded whitespace is ``squeezed'' to single blankcharacters. This flag is implied by the k and K flags.
H
Do not treat input of ? as a request for help. This disablesautomatic help, unless implemented with the after (a flag)subroutine.
 

Flag Characters With Arguments

The following flag characters indicate the presence of an argument toquery. The arguments must occur in the same order as theircorresponding flag characters. For example, if both the V and hflags are given as "Vh", then the first argument must be thevariable name, and the next the help string, in that order.
a \&after
The next argument is the after subroutine, to be invoked after theinput has been solicited. This feature provides for an ``open ended''input validation, completely at the control of the user of the Querymodule. The after subroutine is invoked in this manner:

  &$after( \$input );

If the after sub returns an "undef", then query processing stopswith an immediate "undef" return value.

If the after sub returns a null or zero value, then the input isrejected and resolicted. No error messages are displayed except the``Please try again.'' message.

Since the after sub has the reference to the $input variable, itis 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 anyinput is attempted. If the before sub returns a non-null, non-zerovalue, the current query will be attempted. If a null or zero value isreturned, the current query will be abandoned, with a null return.

This feature, used in a query table, allows for selective queries tobe programmed by using before subs on the optional queries. Forexample, 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 attemptingany input.

d $default
The next argument is the default input. This string is usedinstead of an empty response from the user. The default valuecan be a scalar value, a reference to a scalar value, or areference to a subroutine, which will be invoked for its resultonly if a default value is needed (no input is given).
h $help_string
The next argument is the help string, which is printed inresponse to an input of "?". In order to enter a ? asactual text, it must be prefixed with a backslash: ``\''.
k \@array
The next argument is a reference to an array of allowable keywords. Theinput is matched against the array elements in a case-insensitivemanner, with unambiguous abbreviations allowed. This flag implies thes flag.

The matching can be made case-sensitive by setting the followingvariable 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 Inthis case, for the input to be unacceptable, it must match exactly,case-insensitive, one of the array elements. This flag implies the sflag.

The k option is useful for soliciting new, unique keywords to agrowing 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 whichthe input will be matched.
I $reference
The next argument is the input: either a simple scalar value, or areference 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.

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 theinput, and wish to use the validation features of "query".

It is also useful to embed a query definition in a query table whichdoes not actually perform a query, but instead does a variableassignment 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 inputis solicited from the input. In other words, the J flag sets aone-time only input reference. Think of it as jumping into thequery loop with an initial input.
V variable_name_or_ref
The next argument is the variable name or reference to receive thevalidated input as its value. This option, and its correspondingvariable name, would normally be present on all entries used withquery_table in order to retain to the values resulting from eachquery.

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

 

Details

The query processing proceeds basically in the same order as defined bythe flags argument, with some exceptions. For example, the beforesubroutine is always performed prior to input.

There are implicit precedences in the ordering of some of the flagtests. Generally, flags have their corresponding tests performed inthe same order as the given flags. Some flag tests, however, requirethat other flags' tests be performed beforehand in order to beeffective. For example, when given the k flag and an s flag,stripping the input would only be effective if the strip were done onthe input before testing the input against the keyword table. In otherwords, the s flag has precedence over the k flag. If the usersupplies the flags string as "ks", the effective ordering wouldstill be "sk".

The table below indicates the precedences of the flag tests:

  Given Flag       Flags With Higher Precedence  ==========       ================================  i (int)          s (strip), d (default), h (help)  k (key)          s (strip), d (default), h (help)  K (nonkey)       s (strip), d (default), h (help)  l (maxlen)                  d (default), h (help)  m (match)                   d (default), h (help)  n (numeric)      s (strip), d (default), h (help)  N (no)           s (strip), d (default), h (help)  r (required)                d (default), h (help)  s (strip)                   d (default), h (help)  Y (yes)          s (strip), d (default), h (help)

Except for the implied precedence indicated in the table above, theordering of the flag tests proceeds in the same order as givenin the flags argument.

Excepting the precedences above, query processing proceeds generally asdescribed below.

*
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, withoutprompting, from the associated reference. If the reference type is"CODE", then it is invoked and the resulting return value is used asthe input. Otherwise the reference is evaluated in a scalar context andused as the input. The J flag test is only done once, on the firstentry into the input loop.
*
In the absence either the I or J flags, "query" will issue thegiven prompt and obtain input from STDIN. If an EOF occurs, an "undef"value will result.
*
The input is examined for ``null'' input (that is, the empty string), andprocessing quits in this case. Since most input is obtained fromSTDIN, a null input indicates an end-of-file (EOF). If the input isnot null, a terminating newline is removed, and the input testingcontinues. At this point, an empty input string does not indicate anEOF.
*
If the s, k, or K flags were given, the input is trimmed ofleading and trailing blanks, and all whitespace is ``squeezed'' to singleblanks.
*
If the input is an empty response, and there is a default input (dflag), use it instead.
*
Unless the H flag is given, if the input is the character "?"with nothing else, then print some helpful information. If the user hadsupplied a help string, it is printed, otherwise the message:

You are being asked "$prompt"

is displayed. Also, some information about the expected response,according to any given flag characters, is displayed. Finally, the useris returned to the prompt, and given another opportunity to enter aresponse.

*
If input is required (indicated by the r flag), and if the inputis empty, produce an error message, and query again.
*
If there was a a flag, the corresponding after subroutine isinvoked with the input reference as its argument. If the subroutinereturns a non-null, non-zero value, the input succeeds, otherwise itfails. It is up to the after subroutine to display any appropriateerror messages.
*
If the query was flagged Y or N, match the input against thepattern:

    /^(y(es?)?|no?)$/i

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

*
If an integer response is required (i flagged), check for integerinput. If not, print an error, and query again. A successful integerinput is returned.
*
If a numeric response is required (n flagged), check for propernumeric input (either integer or real format). Errors produce awarning, and another query.
*
If the query was given a keyword table (flagged with k), the inputis matched against the allowable keyword list. If an exact match isfound, the keyword is returned as the input. Failing an exact match, anabbreviation search is performed against the keywords. If a singlematch is found, it is returned as the input. If no match is found, anerror message is produced, and the user is returned to the query to tryagain. Otherwise, the input was ambiguous, an error noted showing thematches, and the user is queried again.

The matching is case-insensitive or not, according to the value of thevariable $Query::Case_sensitive, which is nil, by default. Thevariable may be set by the user to change the matching fromcase-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 matchesany keywords exactly, an error is noted, and the query is performedagain.

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

*
If the query was m flagged with a Perl regular expression pattern,then the input is matched against the pattern. Failures are noted withan error message, and the query reattempted.
*
If the query was l flagged with a maximum input length, the length ofthe input is checked against the maximum. A length violation is notedwith an error message and the user is queried again.
*
If the query has a variable defined with the V flag, the variable isassigned 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 leveloutside of the Query.pm module.

*
Finally, having passed whatever conditions were flagged, the input isreturned to the user.
 

EXAMPLE

The following are typical usage samples:
*
To perform a simple ``yes'' or ``no'' query, with ``no'' as the defaultanswer:

 $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 fieldname, 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 keywordarrays. If 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. 

AUTHOR

Copyright (C) 1995 Alan K. Stebbens <aksAATThub.ucsb.edu>

This program is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe 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 ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See theGNU General Public License for more details.

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

DIAGNOSTICS

Input is required.
Issued when an empty response is given, and there is no default input.
Please answer with 'yes' or 'no', or enter '?' for help.
Issued for Y or N flagged queries, and the input is notreconizeable.
Please enter an integer number.
Printed when non-integer input is given for i flagged queries.
Please enter a number, real or integer.
Printed when non-numeric input is given for n flagged queries.
The input '$input' is ambiguous; it matches the following:
Issued in response to k flagged queries with input which matches morethan one of the allowed keywords.
The input '$input' fails to match any of the allowed keywords:
Printed when input to a k flagged query does not match any of thekeywords.
The input '%s' matches a disallowed keyword '%s'.
Printed when the input matches one of the unacceptable keywords given ona K flagged query.
'%s' fails to match '%s'
This results from input failing to match the regular expression given ona m flagged query.
Input is %d characters too long; cannot exceed %d characters.
The length of the input exceeded the maximum length given with the lflag argument.
Please try again, or enter '?' for help.
query: The k flag needs an array reference.
The next argument in the argument list to query wasn't an arrayreference.
query: The K flag needs an array reference.
The next argument in the argumentlist to query wasn't an arrayreference.
 

BUGS

 

POD ERRORS

Hey! The above document had some coding errors, which are explained below:
Around line 1353:
You forgot a '=back' before '=head1'


 

Index

NAME
SYNOPSIS
DESCRIPTION
query
query_table
query_table_set_defaults
query_table_process
Query Table
Flag Characters
Flag Characters Without Arguments
Flag Characters With Arguments
Details
EXAMPLE
ENVIRONMENT
DEPENDENCIES
FILES
AUTHOR
DIAGNOSTICS
BUGS
POD ERRORS

This document was created byman2html,using the manual pages.