home *** CD-ROM | disk | FTP | other *** search
/ Chip 2000 May / Chip_2000-05_cd1.bin / zkuste / Perl / ActivePerl-5.6.0.613.msi / 䆊䌷䈹䈙䏵-䞅䞆䞀㡆䞃䄦䠥 / _90479853a21c3e4895035c24e86c1fd0 < prev    next >
Text File  |  2000-03-23  |  53KB  |  951 lines

  1.  
  2. <HTML>
  3. <HEAD>
  4. <TITLE>Getopt::Tabular - table-driven argument parsing for Perl 5</TITLE>
  5. <LINK REL="stylesheet" HREF="../../../Active.css" TYPE="text/css">
  6. <LINK REV="made" HREF="mailto:">
  7. </HEAD>
  8.  
  9. <BODY>
  10. <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
  11. <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
  12. <STRONG><P CLASS=block> Getopt::Tabular - table-driven argument parsing for Perl 5</P></STRONG>
  13. </TD></TR>
  14. </TABLE>
  15.  
  16. <A NAME="__index__"></A>
  17. <!-- INDEX BEGIN -->
  18.  
  19. <UL>
  20.  
  21.     <LI><A HREF="#name">NAME</A></LI><LI><A HREF="#supportedplatforms">SUPPORTED PLATFORMS</A></LI>
  22.  
  23.     <LI><A HREF="#synopsis">SYNOPSIS</A></LI>
  24.     <LI><A HREF="#description">DESCRIPTION</A></LI>
  25.     <LI><A HREF="#features">FEATURES</A></LI>
  26.     <LI><A HREF="#basic operation">BASIC OPERATION</A></LI>
  27.     <LI><A HREF="#option table entries">OPTION TABLE ENTRIES</A></LI>
  28.     <LI><A HREF="#option types">OPTION TYPES</A></LI>
  29.     <UL>
  30.  
  31.         <LI><A HREF="#argumentdriven option types">Argument-driven option types</A></LI>
  32.         <LI><A HREF="#constantvalued option types">Constant-valued option types</A></LI>
  33.         <LI><A HREF="#other option types">Other option types</A></LI>
  34.     </UL>
  35.  
  36.     <LI><A HREF="#error handling">ERROR HANDLING</A></LI>
  37.     <LI><A HREF="#help text">HELP TEXT</A></LI>
  38.     <LI><A HREF="#spoof mode">SPOOF MODE</A></LI>
  39.     <LI><A HREF="#author">AUTHOR</A></LI>
  40.     <LI><A HREF="#bugs">BUGS</A></LI>
  41. </UL>
  42. <!-- INDEX END -->
  43.  
  44. <HR>
  45. <P>
  46. <H1><A NAME="name">NAME</A></H1>
  47. <P>Getopt::Tabular - table-driven argument parsing for Perl 5</P>
  48. <P>
  49. <HR>
  50. <H1><A NAME="supportedplatforms">SUPPORTED PLATFORMS</A></H1>
  51. <UL>
  52. <LI>Linux</LI>
  53. <LI>Solaris</LI>
  54. <LI>Windows</LI>
  55. </UL>
  56. <HR>
  57. <H1><A NAME="synopsis">SYNOPSIS</A></H1>
  58. <PRE>
  59.     use Getopt::Tabular;</PRE>
  60. <P>(or)</P>
  61. <PRE>
  62.     use Getopt::Tabular qw/GetOptions 
  63.                            SetHelp SetHelpOption 
  64.                            SetError GetError/;</PRE>
  65. <PRE>
  66.     ...</PRE>
  67. <PRE>
  68.     &Getopt::Tabular::SetHelp (long_help, usage_string);</PRE>
  69. <PRE>
  70.     @opt_table = (
  71.                   [section_description, "section"],
  72.                   [option, type, num_values, option_data, help_string],
  73.                   ...
  74.                  );
  75.     &GetOptions (\@opt_table, \@ARGV [, \@newARGV]) || exit 1;</PRE>
  76. <P>
  77. <HR>
  78. <H1><A NAME="description">DESCRIPTION</A></H1>
  79. <P><STRONG>Getopt::Tabular</STRONG> is a Perl 5 module for table-driven argument parsing,
  80. vaguely inspired by John Ousterhout's Tk_ParseArgv.  All you really need
  81. to do to use the package is set up a table describing all your
  82. command-line options, and call &GetOptions with three arguments: a
  83. reference to your option table, a reference to <CODE>@ARGV</CODE> (or something
  84. like it), and an optional third array reference (say, to <CODE>@newARGV</CODE>).
  85. &GetOptions will process all arguments in <CODE>@ARGV</CODE>, and copy any
  86. leftover arguments (i.e. those that are not options or arguments to some
  87. option) to the <CODE>@newARGV</CODE> array.  (If the <CODE>@newARGV</CODE> argument is not
  88. supplied, <CODE>GetOptions</CODE> will replace <CODE>@ARGV</CODE> with the stripped-down
  89. argument list.)  If there are any invalid options, <CODE>GetOptions</CODE> will
  90. print an error message and return 0.</P>
  91. <P>Before I tell you all about why Getopt::Tabular is a wonderful thing, let me
  92. explain some of the terminology that will keep popping up here.</P>
  93. <DL>
  94. <DT><STRONG><A NAME="item_argument">argument</A></STRONG><BR>
  95. <DD>
  96. any single word appearing on the command-line, i.e. one element of the
  97. <CODE>@ARGV</CODE> array.
  98. <P></P>
  99. <DT><STRONG><A NAME="item_option">option</A></STRONG><BR>
  100. <DD>
  101. an argument that starts with a certain sequence of characters; the default
  102. is ``-''.  (If you like GNU-style options, you can change this to ``--''.)  In
  103. most Getopt::Tabular-based applications, options can come anywhere on the
  104. command line, and their order is unimportant (unless one option overrides a
  105. previous option).  Also, Getopt::Tabular will allow any non-ambiguous
  106. abbreviation of options.
  107. <P></P>
  108. <DT><STRONG><A NAME="item_option_argument">option argument</A></STRONG><BR>
  109. <DD>
  110. (or <EM>value</EM>) an argument that immediately follows certain types of
  111. options.  For instance, if <CODE>-foo</CODE> is a scalar-valued integer option, and
  112. <CODE>-foo 3</CODE> appears on the command line, then <CODE>3</CODE> will be the argument to
  113. <CODE>-foo</CODE>.
  114. <P></P>
  115. <DT><STRONG><A NAME="item_option_type">option type</A></STRONG><BR>
  116. <DD>
  117. controls how <CODE>GetOptions</CODE> deals with an option and the arguments that
  118. follow it.  (Actually, for most option types, the type interacts with the
  119. <A HREF="#item_num_values"><CODE>num_values</CODE></A> field, which determines whether the option is scalar- or
  120. vector-valued.  This will be fully explained in due course.)
  121. <P></P></DL>
  122. <P>
  123. <HR>
  124. <H1><A NAME="features">FEATURES</A></H1>
  125. <P>Now for the advertising, i.e. why Getopt::Tabular is a good thing.</P>
  126. <UL>
  127. <LI>
  128. Command-line arguments are carefully type-checked, both by pattern and
  129. number---e.g. if an option requires two integers, GetOptions makes sure
  130. that exactly two integers follow it!
  131. <P></P>
  132. <LI>
  133. The valid command-line arguments are specified in a data structure
  134. separate from the call to GetOptions; this makes it easier to have very
  135. long lists of options, and to parse options from multiple sources (e.g. the
  136. command line, an environment variable, and a configuration file).
  137. <P></P>
  138. <LI>
  139. Getopt::Tabular can intelligently generate help text based on your option
  140. descriptions.
  141. <P></P>
  142. <LI>
  143. The type system is extensible, and if you can define your desired argument
  144. type using a single Perl regular expression then it's particularly easy to
  145. extend.
  146. <P></P>
  147. <LI>
  148. To make your program look smarter, options can be abbreviated and come in
  149. any order.
  150. <P></P>
  151. <LI>
  152. <PRE>
  153.  You can parse options in a "spoof" mode that has no side-effects -- this
  154. is useful for making a validation pass over the command line without
  155. actually doing anything.</PRE>
  156. </UL>
  157. <P>In general, I have found that Getopt::Tabular tends to encourage programs
  158. with long lists of sophisticated options, leading to great flexibility,
  159. intelligent operation, and the potential for insanely long command lines.</P>
  160. <P>
  161. <HR>
  162. <H1><A NAME="basic operation">BASIC OPERATION</A></H1>
  163. <P>The basic operation of Getopt::Tabular is driven by an <EM>option table</EM>,
  164. which is just a list of <EM>option descriptions</EM> (otherwise known as option
  165. table entries, or just entries).  Each option description tells
  166. <CODE>GetOptions</CODE> everything it needs to know when it encounters a particular
  167. option on the command line.  For instance,</P>
  168. <PRE>
  169.     ["-foo", "integer", 2, \@Foo, "set the foo values"]</PRE>
  170. <P>means that whenever <CODE>-foo</CODE> is seen on the command line, <CODE>GetOptions</CODE> is
  171. to make sure that the next two arguments are integers, and copy them into
  172. the caller's <CODE>@Foo</CODE> array.  (Well, really into the <CODE>@Foo</CODE> array where the
  173. option table is defined.  This is almost always the same as <CODE>GetOptions</CODE>'
  174. caller, though.)</P>
  175. <P>Typically, you'll group a bunch of option descriptions together like
  176. this:</P>
  177. <PRE>
  178.     @options = 
  179.         (["-range", "integer", 2, \@Range, 
  180.           "set the range of allowed values"],
  181.          ["-file", "string", 1, \$File,
  182.            "set the output file"],
  183.          ["-clobber", "boolean", 0, \$Clobber,
  184.            "clobber existing files"], 
  185.          ...
  186.         );</PRE>
  187. <P>and then call <CODE>GetOptions</CODE> like this:</P>
  188. <PRE>
  189.     &GetOptions (\@options, \@ARGV) || exit 1;</PRE>
  190. <P>which replaces <CODE>@ARGV</CODE> with a new array containing all the arguments
  191. left-over after options and their arguments have been removed.  You can
  192. also call <CODE>GetOptions</CODE> with three arguments, like this:</P>
  193. <PRE>
  194.     &GetOptions (\@options, \@ARGV, \@newARGV) || exit 1;</PRE>
  195. <P>in which case <CODE>@ARGV</CODE> is untouched, and <CODE>@newARGV</CODE> gets the leftover
  196. arguments.</P>
  197. <P>In case of error, <CODE>GetOptions</CODE> prints enough information for the user to
  198. figure out what's going wrong.  If you supply one, it'll even print out a
  199. brief usage message in case of error.  Thus, it's enough to just <A HREF="../../../lib/Pod/perlfunc.html#item_exit"><CODE>exit 1</CODE></A>
  200. when <CODE>GetOptions</CODE> indicates an error by returning 0.</P>
  201. <P>Detailed descriptions of the contents of an option table entry are given
  202. next, followed by the complete run-down of available types, full details on
  203. error handling, and how help text is generated.</P>
  204. <P>
  205. <HR>
  206. <H1><A NAME="option table entries">OPTION TABLE ENTRIES</A></H1>
  207. <P>The fields in the option table control how arguments are parsed, so it's
  208. important to understand each one in turn.  First, the format of entries in
  209. the table is fairly rigid, even though this isn't really necessary with
  210. Perl.  It's done that way to make the Getopt::Tabular code a little easier;
  211. the drawback is that some entries will have unused values (e.g. the
  212. <A HREF="#item_num_values"><CODE>num_values</CODE></A> field is never used for boolean options, but you still have
  213. to put something there as a place-holder).  The fields are as follows:</P>
  214. <DL>
  215. <DT><STRONG>option</STRONG><BR>
  216. <DD>
  217. This is the option name, e.g. ``-verbose'' or ``-some_value''.  For most option
  218. types, this is simply an option prefix followed by text; for boolean
  219. options, however, it can be a little more complicated.  (The exact rules
  220. are discussed under <A HREF="#option types">OPTION TYPES</A>.)  And yes, even though you tell
  221. Getopt::Tabular the valid option prefixes, you still have to put one onto
  222. the option names in the table.
  223. <P></P>
  224. <DT><STRONG><A NAME="item_type">type</A></STRONG><BR>
  225. <DD>
  226. The option type decides what action will be taken when this option is seen
  227. on the command line, and (if applicable) what sort of values will be
  228. accepted for this option.  There are three broad classes of types: those
  229. that imply copying data from the command line into some variable in the
  230. caller's space; those that imply copying constant data into the caller's
  231. space without taking any more arguments from the command line; and those
  232. that imply some other action to be taken.  The available option types are
  233. covered in greater detail below (see <A HREF="#option types">OPTION TYPES</A>), but briefly:
  234. <CODE>string</CODE>, <CODE>integer</CODE>, and <CODE>float</CODE> all imply copying values from the
  235. command line to a variable; <CODE>constant</CODE>, <A HREF="#item_boolean"><CODE>boolean</CODE></A>, <A HREF="#item_copy"><CODE>copy</CODE></A>,
  236. <A HREF="#item_arrayconst"><CODE>arrayconst</CODE></A>, and <A HREF="#item_hashconst"><CODE>hashconst</CODE></A> all imply copying some pre-defined data
  237. into a variable; <A HREF="#item_call"><CODE>call</CODE></A> and <A HREF="#item_eval"><CODE>eval</CODE></A> allow the execution of some arbitrary
  238. subroutine or chunk of code; and <A HREF="#item_help"><CODE>help</CODE></A> options will cause <CODE>GetOptions</CODE>
  239. to print out all available help text and return 0.
  240. <P></P>
  241. <DT><STRONG><A NAME="item_num_values">num_values</A></STRONG><BR>
  242. <DD>
  243. for <CODE>string</CODE>, <CODE>integer</CODE>, and <CODE>float</CODE> options, this determines whether
  244. the option is a scalar (<STRONG>num_values</STRONG> = 1) or vector (<STRONG>num_values</STRONG> > 1)
  245. option.  (Note that whether the option is scalar- or vector-valued has an
  246. important influence on what you must supply in the <STRONG>option_data</STRONG> field!)
  247. For <CODE>constant</CODE>, <A HREF="#item_copy"><CODE>copy</CODE></A>, <A HREF="#item_arrayconst"><CODE>arrayconst</CODE></A>, and <A HREF="#item_hashconst"><CODE>hashconst</CODE></A> option types,
  248. <STRONG>num_values</STRONG> is a bit of a misnomer: it actually contains the value (or a
  249. reference to it, if array or hash) to be copied when the option is
  250. encountered.  For <A HREF="#item_call"><CODE>call</CODE></A> options, <STRONG>num_values</STRONG> can be used to supply
  251. extra arguments to the called subroutine.  In any case, though, you can
  252. think of <STRONG>num_values</STRONG> as an input value.  For <A HREF="#item_boolean"><CODE>boolean</CODE></A> and <A HREF="#item_eval"><CODE>eval</CODE></A>
  253. options, <STRONG>num_values</STRONG> is ignored and should be <A HREF="../../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A> or 0.
  254. <P></P>
  255. <DT><STRONG><A NAME="item_option_data">option_data</A></STRONG><BR>
  256. <DD>
  257. For <CODE>string</CODE>, <CODE>integer</CODE>, <CODE>float</CODE>, <A HREF="#item_boolean"><CODE>boolean</CODE></A>, <CODE>constant</CODE>, <A HREF="#item_copy"><CODE>copy</CODE></A>,
  258. <A HREF="#item_arrayconst"><CODE>arrayconst</CODE></A>, and <A HREF="#item_hashconst"><CODE>hashconst</CODE></A> types, this must be a reference to the
  259. variable into which you want <CODE>GetOptions</CODE> to copy the appropriate thing.
  260. The ``appropriate thing'' is either the <A HREF="#item_argument"><CODE>argument(s)</CODE></A> following the option, the
  261. constant supplied as <STRONG>num_values</STRONG>, or 1 or 0 (for boolean options).
  262. <P>For <A HREF="#item_boolean"><CODE>boolean</CODE></A>, <CODE>constant</CODE>, <A HREF="#item_copy"><CODE>copy</CODE></A>, and scalar-valued <CODE>string</CODE>,
  263. <CODE>integer</CODE>, and <CODE>float</CODE> options, this must be a scalar reference.  For
  264. vector-valued <CODE>string</CODE>, <CODE>integer</CODE>, and <CODE>float</CODE> options (<STRONG>num_values</STRONG> >
  265. 1), and for <A HREF="#item_arrayconst"><CODE>arrayconst</CODE></A> options, this must be an array reference.  For
  266. <A HREF="#item_hashconst"><CODE>hashconst</CODE></A> options, this must be a hash reference.</P>
  267. <P>Finally, <STRONG>option_data</STRONG> is also used as an input value for <A HREF="#item_call"><CODE>call</CODE></A> and
  268. <A HREF="#item_eval"><CODE>eval</CODE></A> options: for <A HREF="#item_call"><CODE>call</CODE></A>, it should be a subroutine reference, and for
  269. <A HREF="#item_eval"><CODE>eval</CODE></A> options, it should be a string containing valid Perl code to
  270. evaluate when the option is seen.  The subroutine called by a <A HREF="#item_call"><CODE>call</CODE></A>
  271. option should take at least two arguments: a string, which is the actual
  272. option that triggered the call (because the same subroutine could be tied
  273. to many options), and an array reference, which contains all command line
  274. arguments after that option.  (Further arguments can be supplied in the
  275. <STRONG>num_values</STRONG> field.)  The subroutine may freely modify this array, and
  276. those modifications will affect the behaviour of <CODE>GetOptions</CODE> afterwards.</P>
  277. <P>The chunk of code passed to an <A HREF="#item_eval"><CODE>eval</CODE></A> option is evaluated in the package
  278. from which <CODE>GetOptions</CODE> is called, and does not have access to any
  279. internal Getopt::Tabular data.</P>
  280. <P></P>
  281. <DT><STRONG><A NAME="item_help_string">help_string</A></STRONG><BR>
  282. <DD>
  283. (optional) a brief description of the option.  Don't worry about formatting
  284. this in any way; when <CODE>GetOptions</CODE> has to print out your help, it will do so
  285. quite nicely without any intervention.  If the help string is not defined,
  286. then that option will not be included in the option help text.  (However,
  287. you could supply an empty string -- which is defined -- to make <CODE>GetOptions</CODE>
  288. just print out the option name, but nothing else.)
  289. <P></P>
  290. <DT><STRONG><A NAME="item_arg_desc">arg_desc</A></STRONG><BR>
  291. <DD>
  292. (optional) an even briefer description of the values that you expect to
  293. follow your option.  This is mainly used to supply place-holders in the help
  294. string, and is specified separately so that <CODE>GetOptions</CODE> can act fairly
  295. intelligently when formatting a help message.  See <A HREF="#help text">HELP TEXT</A> for more
  296. information.
  297. <P></P></DL>
  298. <P>
  299. <HR>
  300. <H1><A NAME="option types">OPTION TYPES</A></H1>
  301. <P>The option type field is the single-most important field in the table, as
  302. the type for an option <CODE>-foo</CODE> determines (along with <STRONG>num_values</STRONG>) what
  303. action <CODE>GetOptions</CODE> takes when it sees <CODE>-foo</CODE> on the command line: how many
  304. following arguments become <CODE>-foo</CODE>'s arguments, what regular expression
  305. those arguments must conform to, or whether some other action should be
  306. taken.</P>
  307. <P>As mentioned above, there are three main classes of argument types:</P>
  308. <DL>
  309. <DT><STRONG><A NAME="item_argument%2Ddriven_options">argument-driven options</A></STRONG><BR>
  310. <DD>
  311. These are options that imply taking one or more option arguments from
  312. the command line after the option itself is taken.  The arguments are
  313. then copied into some variable supplied (by reference) in the option
  314. table entry.
  315. <P></P>
  316. <DT><STRONG><A NAME="item_constant%2Dvalued_options">constant-valued options</A></STRONG><BR>
  317. <DD>
  318. These are options that have a constant value associated with them; when
  319. the option is seen on the command line, that constant is copied to some
  320. variable in the caller's space.  (Both the constant and the value are
  321. supplied in the option table entry.)  Constants can be scalars, arrays,
  322. or hashes.
  323. <P></P>
  324. <DT><STRONG><A NAME="item_other_options">other options</A></STRONG><BR>
  325. <DD>
  326. These imply some other action to be taken, usually supplied as a string
  327. to <A HREF="#item_eval"><CODE>eval</CODE></A> or a subroutine to call.
  328. <P></P></DL>
  329. <P>
  330. <H2><A NAME="argumentdriven option types">Argument-driven option types</A></H2>
  331. <DL>
  332. <DT><STRONG><A NAME="item_string%2C_integer%2C_float">string, integer, float</A></STRONG><BR>
  333. <DD>
  334. These are the option types that imply ``option arguments'', i.e. arguments
  335. after the option that will be consumed when that option is encountered on
  336. the command line and copied into the caller's space via some reference.
  337. For instance, if you want an option <CODE>-foo</CODE> to take a single string as
  338. an argument, with that string being copied to the scalar variable
  339. <CODE>$Foo</CODE>, then you would have this entry in your option table:
  340. <PRE>
  341.     ["-foo", "string", 1, \$Foo]</PRE>
  342. <P>(For conciseness, I've omitted the <STRONG>help_string</STRONG> and <STRONG>argdesc</STRONG> entries
  343. in all of the example entries in this section.  In reality, you should
  344. religiously supply help text in order to make your programs easier to
  345. use and easier to maintain.)</P>
  346. <P>If <STRONG>num_values</STRONG> is some <EM>n</EM> greater than one, then the <STRONG>option_data</STRONG>
  347. field must be an <EM>array</EM> reference, and <EM>n</EM> arguments are copied from
  348. the command line into that array.  (The array is clobbered each time
  349. <CODE>-foo</CODE> is encountered, not appended to.)  In this case, <CODE>-foo</CODE> is
  350. referred to as a <EM>vector-valued</EM> option, as it must be followed by a
  351. fixed number of arguments.  (Eventually, I plan to add <EM>list-valued</EM>
  352. options, which take a variable number of arguments.)  For example an
  353. option table like</P>
  354. <PRE>
  355.     ["-foo", "string", 3, \@Foo]</PRE>
  356. <P>would result in the <CODE>@Foo</CODE> array being set to the three strings
  357. immediately following any <CODE>-foo</CODE> option on the command line.</P>
  358. <P>The only difference between <STRONG>string</STRONG>, <STRONG>integer</STRONG>, and <STRONG>float</STRONG> options is
  359. how picky <CODE>GetOptions</CODE> is about the <CODE>value(s)</CODE> it will accept.  For
  360. <STRONG>string</STRONG> options, anything is OK; for <STRONG>integer</STRONG> options, the values must
  361. look like integers (i.e., they must match <CODE>/[+-]?\d+/</CODE>); for <STRONG>float</STRONG>
  362. options, the values must look like C floating point numbers (trust me, you
  363. don't want to see the regexp for this).  Note that since string options
  364. will accept anything, they might accidentally slurp up arguments that are
  365. meant to be further options, if the user forgets to put the correct string.
  366. For instance, if <CODE>-foo</CODE> and <CODE>-bar</CODE> are both scalar-valued string options,
  367. and the arguments <CODE>-foo -bar</CODE> are seen on the command-line, then ``-bar''
  368. will become the argument to <CODE>-foo</CODE>, and never be processed as an option
  369. itself.  (This could be construed as either a bug or a feature.  If you
  370. feel really strongly that it's a bug, then complain and I'll consider doing
  371. something about it.)</P>
  372. <P>If not enough arguments are found that match the required regular
  373. expression, <CODE>GetOptions</CODE> prints to standard error a clear and useful error
  374. message, followed by the usage summary (if you supplied one), and returns
  375. 0.  The error messages look something like ``-foo option must be followed by
  376. an integer'', or ``-foo option must be followed by 3 strings'', so it really
  377. is enough for your program to <A HREF="../../../lib/Pod/perlfunc.html#item_exit"><CODE>exit 1</CODE></A> without printing any further
  378. message.</P>
  379. <P></P>
  380. <DT><STRONG><A NAME="item_User%2Ddefined_patterns">User-defined patterns</A></STRONG><BR>
  381. <DD>
  382. Since the three option types described above are defined by nothing more
  383. than a regular expression, it's easy to define your own option types.  For
  384. instance, let's say you want an option to accept only strings of upper-case
  385. letters.  You could then call <CODE>&Getopt::Tabular::AddPatternType</CODE> as
  386. follows:
  387. <PRE>
  388.     &Getopt::Tabular::AddPatternType
  389.       ("upperstring", "[A-Z]+", "uppercase string")</PRE>
  390. <P>Note that the third parameter is optional, and is only supplied to make
  391. error messages clearer.  For instance, if you now have a scalar-valued
  392. option <CODE>-zap</CODE> of type <CODE>upperstring</CODE>:</P>
  393. <PRE>
  394.    ["-zap", "upperstring", 1, \$Zap]</PRE>
  395. <P>and the user gets it wrong and puts an argument that doesn't consist of
  396. all uppercase letters after <CODE>-zap</CODE>, then <CODE>GetOptions</CODE> will complain
  397. that ``-zap option must be followed by an uppercase string''.  If you
  398. hadn't supplied the third argument to <CODE>&AddType</CODE>, then the error
  399. message would have been the slightly less helpful ``-zap option must be
  400. followed by an upperstring''.  Also, you might have to worry about how
  401. <CODE>GetOptions</CODE> pluralizes your description: in this case, it will simply
  402. add an ``s'', which works fine much of the time, but not always.
  403. Alternately, you could supply a two-element list containing the singular
  404. and plural forms:</P>
  405. <PRE>
  406.     &Getopt::Tabular::AddPatternType
  407.       ("upperstring", "[A-Z]+", 
  408.         ["string of uppercase letters", "strings of uppercase letters"])</PRE>
  409. <P>So, if <CODE>-zap</CODE> instead expects three <CODE>upperstring</CODE>s, and the user
  410. goofs, then the error message would be (in the first example) ``-zap
  411. option must be followed by 3 uppercase strings'' or ``-zap option must be
  412. followed by three strings of uppercase letters'' (second example).</P>
  413. <P>Of course, if you don't intend to have vector-valued options of your new
  414. type, pluralization hardly matters.  Also, while it might seem that this
  415. is a nice stab in the direction of multi-lingual support, the error
  416. messages are still hard-coded to English in other places.  Maybe in the
  417. next version...</P>
  418. <P></P></DL>
  419. <P>
  420. <H2><A NAME="constantvalued option types">Constant-valued option types</A></H2>
  421. <DL>
  422. <DT><STRONG><A NAME="item_boolean">boolean</A></STRONG><BR>
  423. <DD>
  424. For <STRONG>boolean</STRONG> options, <STRONG>option_data</STRONG> must be a scalar reference;
  425. <STRONG>num_values</STRONG> is ignored (you can just set it to <A HREF="../../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A> or 0).
  426. Booleans are slightly weird in that every boolean option implies <EM>two</EM>
  427. possible arguments that will be accepted on the command line, called the
  428. positive and negative alternatives.  The positive alternative (which is
  429. what you specify as the option name) results in a true value, while the
  430. negative alternative results in false.  Most of the time, you can let
  431. <CODE>GetOptions</CODE> pick the negative alternative for you: it just inserts
  432. ``no'' after the option prefix, so ``-clobber'' becomes ``-noclobber''.  (More
  433. precisely, <CODE>GetOptions</CODE> tests all option prefixes until one of them
  434. matches at the beginning of the option name.  It then inserts ``no''
  435. between this prefix and the rest of the string.  So, if you want to
  436. support both GNU-style options (like <CODE>--clobber</CODE>) and one-hyphen
  437. options (<CODE>-c</CODE>), be sure to give ``--'' <EM>first</EM> when setting the option
  438. patterns with <CODE>&SetOptionPatterns</CODE>.  Otherwise, the negative
  439. alternative to ``--clobber'' will be ``-no-clobber'', which might not be
  440. what you wanted.)  Sometimes, though, you want to explicitly specify the
  441. negative alternative.  This is done by putting both alternatives in the
  442. option name, separated by a vertical bar, e.g. ``-verbose|-quiet''.
  443. <P>For example, the above two examples might be specified as</P>
  444. <PRE>
  445.     ["-clobber", "boolean", undef, \$Clobber],
  446.     ["-verbose|-quiet", "boolean", undef, \$Verbose],...);</PRE>
  447. <P>If <CODE>-clobber</CODE> is seen on the command line, <CODE>$Clobber</CODE> will be set to 1;
  448. if <CODE>-noclobber</CODE> is seen, then <CODE>$Clobber</CODE> will be set to 0.  Likewise,
  449. <CODE>-verbose</CODE> results in <CODE>$Verbose</CODE> being set to 1, and <CODE>-quiet</CODE> will set
  450. <CODE>$Verbose</CODE> to 0.</P>
  451. <P></P>
  452. <DT><STRONG><A NAME="item_const">const</A></STRONG><BR>
  453. <DD>
  454. For <STRONG>const</STRONG> options, put a scalar value (<EM>not</EM> reference) in
  455. <STRONG>num_values</STRONG>, and a scalar reference in <STRONG>option_data</STRONG>.  For example:
  456. <PRE>
  457.     ["-foo", "const", "hello there", \$Foo]</PRE>
  458. <P>On encountering <CODE>-foo</CODE>, <CODE>GetOptions</CODE> will copy ``hello there'' to <CODE>$Foo</CODE>.</P>
  459. <P></P>
  460. <DT><STRONG><A NAME="item_arrayconst">arrayconst</A></STRONG><BR>
  461. <DD>
  462. For <STRONG>arrayconst</STRONG> options, put an array reference (input) (<EM>not</EM> an array
  463. value) in <STRONG>num_values</STRONG>, and another array reference (output) in
  464. <STRONG>option_data</STRONG>.  For example:
  465. <PRE>
  466.     ["-foo", "arrayconst", [3, 6, 2], \@Foo]</PRE>
  467. <P>On encountering <CODE>-foo</CODE>, <CODE>GetOptions</CODE> will copy the array <CODE>(3,6,2)</CODE> into
  468. <CODE>@Foo</CODE>.</P>
  469. <P></P>
  470. <DT><STRONG><A NAME="item_hashconst">hashconst</A></STRONG><BR>
  471. <DD>
  472. For <STRONG>hashconst</STRONG> options, put a hash reference (input) (<EM>not</EM> a hash
  473. value) in <STRONG>num_values</STRONG>, and another hash reference (output) in
  474. <STRONG>option_data</STRONG>.  For example:
  475. <PRE>
  476.     ["-foo", "hashconst", { "Perl"   => "Larry Wall",
  477.                             "C"      => "Dennis Ritchie",
  478.                             "Pascal" => "Niklaus Wirth" },
  479.      \%Inventors]</PRE>
  480. <P>On encountering <CODE>-foo</CODE>, <CODE>GetOptions</CODE> will copy into <CODE>%Inventors</CODE> a hash
  481. relating various programming languages to the culprits primarily
  482. responsible for their invention.</P>
  483. <P></P>
  484. <DT><STRONG><A NAME="item_copy">copy</A></STRONG><BR>
  485. <DD>
  486. <STRONG>copy</STRONG> options act just like <STRONG>const</STRONG> options, except when
  487. <STRONG>num_values</STRONG> is undefined.  In that case, the option name itself will
  488. be copied to the scalar referenced by <STRONG>option_data</STRONG>, rather than the
  489. <A HREF="../../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A> value that would be copied under these circumstances with a
  490. <STRONG>const</STRONG> option.  This is useful when one program accepts options that
  491. it simply passes to a sub-program; for instance, if <EM>prog1</EM> calls
  492. <EM>prog2</EM>, and <EM>prog2</EM> might be run with the -foo option, then
  493. <EM>prog1</EM>'s argument table might have this option:
  494. <PRE>
  495.     ["-foo", "copy", undef, \$Foo, 
  496.      "run prog2 with the -foo option"]</PRE>
  497. <P>and later on, you would run <EM>prog2</EM> like this:</P>
  498. <PRE>
  499.     system ("prog2 $Foo ...");</PRE>
  500. <P>That way, if <CODE>-foo</CODE> is never seen on <EM>prog1</EM>'s command line, <CODE>$Foo</CODE> will
  501. be untouched, and will expand to the empty string when building the command
  502. line for <EM>prog2</EM>.</P>
  503. <P>If <STRONG>num_values</STRONG> is anything other than <A HREF="../../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A>, then <STRONG>copy</STRONG> options
  504. behave just like <STRONG>constant</STRONG> options.</P>
  505. <P></P></DL>
  506. <P>
  507. <H2><A NAME="other option types">Other option types</A></H2>
  508. <DL>
  509. <DT><STRONG><A NAME="item_call">call</A></STRONG><BR>
  510. <DD>
  511. For <STRONG>call</STRONG> options, <STRONG>option_data</STRONG> must be a reference to a subroutine.
  512. The subroutine will be called with at least two arguments: a string
  513. containing the option that triggered the call (because the same
  514. subroutine might be activated by many options), a reference to an array
  515. containing all remaining command-line arguments after the option, and
  516. other arguments specified using the <STRONG>num_values</STRONG> field.  (To be used
  517. for this purpose, <STRONG>num_values</STRONG> must be an array reference; otherwise,
  518. it is ignored.)  For example, you might define a subroutine
  519. <PRE>
  520.     sub process_foo
  521.     {
  522.        my ($opt, $args, $dest) = @_;</PRE>
  523. <PRE>
  524.        $$dest = shift @$args;    # not quite right! (see below)
  525.     }</PRE>
  526. <P>with a corresponding option table entry:</P>
  527. <PRE>
  528.     ["-foo", "call", [\$Foo], \&process_foo]</PRE>
  529. <P>and then <CODE>-foo</CODE> would act just like a scalar-valued string option that
  530. copies into <CODE>$Foo</CODE>.  (Well, <EM>almost</EM> ... read on.)</P>
  531. <P>A subtle point that might be missed from the above code: the value returned
  532. by <CODE>&process_foo</CODE> <EM>does</EM> matter: if it is false, then <CODE>GetOptions</CODE> will
  533. return 0 to its caller, indicating failure.  To make sure that the user
  534. gets a useful error message, you should supply one by calling <CODE>SetError</CODE>;
  535. doing so will prevent <CODE>GetOptions</CODE> from printing out a rather mysterious
  536. (to the end user, at least) message along the lines of ``subroutine call
  537. failed''.  The above example has two subtle problems: first, if the argument
  538. following <CODE>-foo</CODE> is an empty string, then <CODE>process_foo</CODE> will return
  539. the empty string---a false value---thus causing <CODE>GetOptions</CODE> to fail
  540. confusingly.  Second, if there no arguments after <CODE>-foo</CODE>, then
  541. <CODE>process_foo</CODE> will return <A HREF="../../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A>---again, a false value, causing
  542. <CODE>GetOptions</CODE> to fail.</P>
  543. <P>To solve these problems, we have to define the requirements for the
  544. <CODE>-foo</CODE> option a little more rigorously.  Let's say that any string
  545. (including the empty string) is valid, but that there must be something
  546. there.  Then <CODE>process_foo</CODE> is written as follows:</P>
  547. <PRE>
  548.     sub process_foo
  549.     {
  550.        my ($opt, $args, $dest) = @_;</PRE>
  551. <PRE>
  552.        $$dest = shift @$args;
  553.        (defined $$dest) && return 1;
  554.        &Getopt::Tabular::SetError 
  555.          ("bad_foo", "$opt option must be followed by a string");
  556.        return 0;
  557.     }</PRE>
  558. <P>The <CODE>SetError</CODE> routine actually takes two arguments: an error class and
  559. an error message.  This is explained fully in the <A HREF="#error handling">ERROR HANDLING</A>
  560. section, below.  And, if you find yourself writing a lot of routines
  561. like this, <CODE>SetError</CODE> is optionally exported from <CODE>Getopt::Tabular</CODE>,
  562. so you can of course import it into your main package like this:</P>
  563. <PRE>
  564.     use Getopt::Tabular qw/GetOptions SetError/;</PRE>
  565. <P></P>
  566. <DT><STRONG><A NAME="item_eval">eval</A></STRONG><BR>
  567. <DD>
  568. An <STRONG>eval</STRONG> option specifies a chunk of Perl code to be executed
  569. (<A HREF="#item_eval"><CODE>eval</CODE></A>'d) when the option is encountered on the command line.  The
  570. code is supplied (as a string) in the <STRONG>option_data</STRONG> field; again,
  571. <STRONG>num_values</STRONG> is ignored.  For example:
  572. <PRE>
  573.     ["-foo", "eval", undef, 
  574.      'print "-foo seen on command line\n"']</PRE>
  575. <P>will cause <CODE>GetOptions</CODE> to print out (via an <A HREF="#item_eval"><CODE>eval</CODE></A>) the string ``-foo seen
  576. on the command line\n'' when -foo is seen.  No other action is taken
  577. apart from what you include in the eval string.  The code is evaluated
  578. in the package from which <CODE>GetOptions</CODE> was called, so you can access
  579. variables and subroutines in your program easily.  If any error occurs
  580. in the <A HREF="#item_eval"><CODE>eval</CODE></A>, <CODE>GetOptions</CODE> complains loudly and returns 0.</P>
  581. <P>Note that the supplied code is always evaluated in a <CODE>no strict</CODE>
  582. environment---that's because <EM>Getopt::Tabular</EM> is itself <CODE>use
  583. strict</CODE>-compliant, and I didn't want to force strictness on every quick
  584. hack that uses the module.  (Especially since <STRONG>eval</STRONG> options seem to be
  585. used mostly in quick hacks.)  (Anyone who knows how to fetch the
  586. strictness state for another package or scope is welcome to send me
  587. hints!)  However, the <STRONG>-w</STRONG> state is untouched.</P>
  588. <P></P>
  589. <DT><STRONG><A NAME="item_section">section</A></STRONG><BR>
  590. <DD>
  591. <STRONG>section</STRONG> options are just used to help formatting the help text.  See
  592. <A HREF="#help text">HELP TEXT</A> below for more details.
  593. <P></P></DL>
  594. <P>
  595. <HR>
  596. <H1><A NAME="error handling">ERROR HANDLING</A></H1>
  597. <P>Generally, handling errors in the argument list is pretty transparent:
  598. <CODE>GetOptions</CODE> (or one of its minions) generates an error message and
  599. assigns an error class, <CODE>GetOptions</CODE> prints the message to the standard
  600. error, and returns 0.  You can access the error class and error message
  601. using the <CODE>GetError</CODE> routine:</P>
  602. <PRE>
  603.     ($err_class, $err_msg) = &Getopt::Tabular::GetError ();</PRE>
  604. <P>(Like <CODE>SetError</CODE>, <CODE>GetError</CODE> can also be exported from
  605. <EM>Getopt::Tabular</EM>.)  The error message is pretty simple---it is an
  606. explanation for the end user of what went wrong, which is why
  607. <CODE>GetOptions</CODE> just prints it out and forgets about it.  The error class
  608. is further information that might be useful for your program; the
  609. current values are:</P>
  610. <DL>
  611. <DT><STRONG><A NAME="item_bad_option">bad_option</A></STRONG><BR>
  612. <DD>
  613. set when something that looks like an option is found on the command
  614. line, but it's either unknown or an ambiguous abbreviation.
  615. <P></P>
  616. <DT><STRONG><A NAME="item_bad_value">bad_value</A></STRONG><BR>
  617. <DD>
  618. set when an option is followed by an invalid argument (i.e., one that
  619. doesn't match the regexp for that type), or the wrong number of
  620. arguments.
  621. <P></P>
  622. <DT><STRONG><A NAME="item_bad_call">bad_call</A></STRONG><BR>
  623. <DD>
  624. set when a subroutine called via a <STRONG>call</STRONG> option or the code evaluated
  625. for an <STRONG>eval</STRONG> option returns a false value.  The subroutine or eval'd
  626. code can override this by calling <CODE>SetError</CODE> itself.
  627. <P></P>
  628. <DT><STRONG><A NAME="item_bad_eval">bad_eval</A></STRONG><BR>
  629. <DD>
  630. set when the code evaluted for an <STRONG>eval</STRONG> option has an error in it.
  631. <P></P>
  632. <DT><STRONG><A NAME="item_help">help</A></STRONG><BR>
  633. <DD>
  634. set when the user requests help
  635. <P></P></DL>
  636. <P>Note that most of these are errors on the end user's part, such as bad
  637. or missing arguments.  There are also errors that can be caused by you,
  638. the programmer, such as bad or missing values in the option table; these
  639. generally result in <CODE>GetOptions</CODE> croaking so that your program dies
  640. immediately with enough information that you can figure out where the
  641. mistake is.  <STRONG>bad_eval</STRONG> is a borderline case; there are conceivably
  642. cases where the end user's input can result in bogus code to evaluate,
  643. so I grouped this one in the ``user errors'' class.  Finally, asking for
  644. help isn't really an error, but the assumption is that you probably
  645. shouldn't continue normal processing after printing out the help---so
  646. <CODE>GetOptions</CODE> returns 0 in this case.  You can always fetch the error
  647. class with <CODE>GetError</CODE> if you want to treat real errors differently from
  648. help requests.</P>
  649. <P>
  650. <HR>
  651. <H1><A NAME="help text">HELP TEXT</A></H1>
  652. <P>One of Getopt::Tabular's niftier features is the ability to generate and
  653. format a pile of useful help text from the snippets of help you include
  654. in your option table.  The best way to illustrate this is with a couple
  655. of brief examples.  First, it's helpful to know how the user can trigger
  656. a help display.  This is quite simple: by default, <CODE>GetOptions</CODE> always
  657. has a ``-help'' option, presence of which on the command line triggers a
  658. help display.  (Actually, the help option is really your preferred
  659. option prefix plus ``help''.  So, if you like to make GNU-style options to
  660. take precedence as follows:</P>
  661. <PRE>
  662.     &Getopt::Tabular::SetOptionPatterns qw|(--)([\w-]+) (-)(\w+)|;</PRE>
  663. <P>then the help option will be ``--help''.  There is only one help option
  664. available, and you can set it by calling <CODE>&SetHelpOption</CODE> (another
  665. optional export).</P>
  666. <P>Note that in addition to the option help embedded in the option table,
  667. <CODE>GetOptions</CODE> can optionally print out two other messages: a descriptive
  668. text (usually a short paragraph giving a rough overview of what your
  669. program does, possibly referring the user to the fine manual page), and
  670. a usage text.  These are both supplied by calling <CODE>&SetHelp</CODE>, e.g.</P>
  671. <PRE>
  672.     $Help = <<HELP;
  673.     This is the foo program.  It reads one file (specified by -infile),
  674.     operates on it some unspecified way (possibly modified by
  675.     -threshold), and does absolutely nothing with the results.
  676.     (The utility of the -clobber option has yet to be established.)
  677.     HELP</PRE>
  678. <PRE>
  679.     $Usage = <<USAGE;
  680.     usage: foo [options]
  681.            foo -help to list options
  682.     USAGE</PRE>
  683. <PRE>
  684.     &Getopt::Tabular::SetHelp ($Help, $Usage)</PRE>
  685. <P>Note that either of the long help or usage strings may be empty, in
  686. which case <CODE>GetOptions</CODE> simply won't print them.  In the case where both
  687. are supplied, the long help message is printed first, followed by the
  688. option help summary, followed by the usage.  <CODE>GetOptions</CODE> inserts enough
  689. blank lines to make the output look just fine on its own, so you
  690. shouldn't pad either the long help or usage message with blanks.  (It
  691. looks best if each ends with a newline, though, so setting the help
  692. strings with here-documents---as in this example---is the recommended
  693. approach.)</P>
  694. <P>As an example of the help display generated by a typical option table,
  695. let's take a look at the following:</P>
  696. <PRE>
  697.     $Verbose = 1;
  698.     $Clobber = 0;
  699.     undef $InFile;
  700.     @Threshold = (0, 1);</PRE>
  701. <PRE>
  702.     @argtbl = (["-verbose|-quiet", "boolean", 0, \$Verbose,
  703.                 "be noisy"],
  704.                ["-clobber", "boolean", 0, \$Clobber,
  705.                 "overwrite existing files"],
  706.                ["-infile", "string", 1, \$InFile,
  707.                 "specify the input file from which to read a large " .
  708.                 "and sundry variety of data, to which many " .
  709.                 "interesting operations will be applied", "<f>"],
  710.                ["-threshold", "float", 2, \@Threshold,
  711.                 "only consider values between <v1> and <v2>",
  712.                 "<v1> <v2>"]);</PRE>
  713. <P>Assuming you haven't supplied long help or usage strings, then when
  714. <CODE>GetOptions</CODE> encounters the help option, it will immediately stop
  715. parsing arguments and print out the following option summary:</P>
  716. <PRE>
  717.     Summary of options:
  718.        -verbose    be noisy [default]
  719.        -quiet      opposite of -verbose
  720.        -clobber    overwrite existing files
  721.        -noclobber  opposite of -clobber [default]
  722.        -infile <f> specify the input file from which to read a large and
  723.                    sundry variety of data, to which many interesting
  724.                    operations will be applied
  725.        -threshold <v1> <v2>
  726.                    only consider values between <v1> and <v2> [default: 0 1]</PRE>
  727. <P>There are a number of interesting things to note here.  First, there are
  728. three option table fields that affect the generation of help text:
  729. <STRONG>option</STRONG>, <STRONG>help_string</STRONG>, and <STRONG>argdesc</STRONG>.  Note how the <STRONG>argdesc</STRONG>
  730. strings are simply option placeholders, usually used to 1) indicate how
  731. many values are expected to follow an option, 2) (possibly) imply what
  732. form they take (although that's not really shown here), and 3) explain
  733. the exact meaning of the values in the help text.  <STRONG>argdesc</STRONG> is just a
  734. string like the help string; you can put whatever you like in it.  What
  735. I've shown above is just my personal preference (which may well evolve).</P>
  736. <P>A new feature with version 0.3 of Getopt::Tabular is the inclusion of
  737. default values with the help for certain options.  A number of
  738. conditions must be fulfilled for this to happen for a given option:
  739. first, the option type must be one of the ``argument-driven'' types, such
  740. as <CODE>integer</CODE>, <CODE>float</CODE>, <CODE>string</CODE>, or a user-defined type.  Second, the
  741. option data field must refer either to a defined scalar value (for
  742. scalar-valued options) or to a list of one or more defined values (for
  743. vector-valued options).  Thus, in the above example, the <CODE>-infile</CODE>
  744. option doesn't have its default printed because the <CODE>$InFile</CODE> scalar is
  745. undefined.  Likewise, if the <CODE>@Threshold</CODE> array were the empty list
  746. <CODE>()</CODE>, or a list of undefined values <CODE>(undef,undef)</CODE>, then the default
  747. value for <CODE>-threshold</CODE> also would not have been printed.</P>
  748. <P>The formatting is done as follows: enough room is made on the right hand
  749. side for the longest option name, initially omitting the argument
  750. placeholders.  Then, if an option has placeholders, and there is room
  751. for them in between the option and the help string, everything (option,
  752. placeholders, help string) is printed together.  An example of this is
  753. the <CODE>-infile</CODE> option: here, ``-infile <f>'' is just small enough to fit
  754. in the 12-character column (10 characters because that is the length of
  755. the longest option, and 2 blanks), so the help text is placed right
  756. after it on the same line.  However, the <CODE>-threshold</CODE> option becomes
  757. too long when its argument placeholders are appended to it, so the help
  758. text is pushed onto the next line.</P>
  759. <P>In any event, the help string supplied by the caller starts at the same
  760. column, and is filled to make a nice paragraph of help.  <CODE>GetOptions</CODE> will
  761. fill to the width of the terminal (or 80 columns if it fails to find the
  762. terminal width).</P>
  763. <P>Finally, you can have pseudo entries of type <STRONG>section</STRONG>, which are
  764. important to make long option lists readable (and one consequence of
  765. using Getopt::Tabular is programs with ridiculously long option lists -- not
  766. altogether a bad thing, I suppose).  For example, this table fragment:</P>
  767. <PRE>
  768.     @argtbl = (...,
  769.                ["-foo", "integer", 1, \$Foo,
  770.                 "set the foo value", "f"],
  771.                ["-enterfoomode", "call", 0, \&enter_foo_mode,
  772.                 "enter foo mode"],
  773.                ["Non-foo related options", "section"],
  774.                ["-bar", "string", 2, \@Bar,
  775.                 "set the bar strings (which have nothing whatsoever " .
  776.                 "to do with foo", "<bar1> <bar2>"], 
  777.                ...);</PRE>
  778. <P>results in the following chunk of help text:</P>
  779. <PRE>
  780.        -foo f         set the foo value
  781.        -enterfoomode  enter foo mode
  782. </PRE>
  783. <PRE>
  784.  
  785.     -- Non-foo related options ---------------------------------
  786.        -bar b1 b2     set the bar strings (which have nothing
  787.                       whatsoever to do with foo</PRE>
  788. <P>(This example also illustrates a slightly different style of argument
  789. placeholder.  Take your pick, or invent your own!)</P>
  790. <P>
  791. <HR>
  792. <H1><A NAME="spoof mode">SPOOF MODE</A></H1>
  793. <P>Since callbacks from the command line (<A HREF="#item_call"><CODE>call</CODE></A> and <A HREF="#item_eval"><CODE>eval</CODE></A> options) can
  794. do anything, they might be quite expensive.  In certain cases, then, you
  795. might want to make an initial pass over the command line to ensure that
  796. everything is OK before parsing it ``for real'' and incurring all those
  797. expensive callbacks.  Thus, <CODE>Getopt::Tabular</CODE> provides a ``spoof'' mode
  798. for parsing a command line without side-effects.  In the simplest case,
  799. you can access spoof mode like this:</P>
  800. <PRE>
  801.    use Getopt::Tabular qw(SpoofGetOptions GetOptions);
  802.      .
  803.      .
  804.      .
  805.    &SpoofGetOptions (\@options, \@ARGV, \@newARGV) || exit 1;</PRE>
  806. <P>and then later on, you would call <CODE>GetOptions</CODE> with the <EM>original</EM>
  807. <CODE>@ARGV</CODE> (so it can do what <CODE>SpoofGetOptions</CODE> merely pretended to do):</P>
  808. <PRE>
  809.    &GetOptions (\@options, \@ARGV, \@newARGV) || exit 1;</PRE>
  810. <P>For most option types, any errors that <CODE>GetOptions</CODE> would catch should
  811. also be caught by <CODE>SpoofGetOptions</CODE> -- so you might initially think
  812. that you can get away without that <CODE>|| exit 1</CODE> after calling
  813. <CODE>GetOptions</CODE>.  However, it's a good idea for a couple of reasons.
  814. First, you might inadvertently changed <CODE>@ARGV</CODE> -- this is usually a bug
  815. and a silly thing to do, so you'd probably want your program to crash
  816. loudly rather than fail mysteriously later on.  Second, and more likely,
  817. some of those expensive operations that you're initially avoiding by
  818. using <CODE>SpoofGetOptions</CODE> might themselves fail -- which would cause
  819. <CODE>GetOptions</CODE> to return false where <CODE>SpoofGetOption</CODE> completes without
  820. a problem.  (Finally, there's the faint possiblity of bugs in
  821. <CODE>Getopt::Tabular</CODE> that would cause different behaviour in spoof mode
  822. and real mode -- this really shouldn't happen, though.)</P>
  823. <P>In reality, using spoof mode requires a bit more work.  In particular,
  824. the whole reason for spoof argument parsing is to avoid expensive
  825. callbacks, but since callbacks can eat any number of command line
  826. arguments, you have to emulate them in some way.  It's not possible for
  827. <CODE>SpoofGetOptions</CODE> to do this for you, so you have to help out by
  828. supplying ``spoof'' callbacks.  As an example, let's say you have a
  829. callback option that eats one argument (a filename) and immediately
  830. reads that file:</P>
  831. <PRE>
  832.    @filedata = ();</PRE>
  833. <PRE>
  834.    sub read_file
  835.    {
  836.       my ($opt, $args) = @_;</PRE>
  837. <PRE>
  838.       warn ("$opt option requires an argument\n"), return 0 unless @$args;
  839.       my $file = shift @$args;
  840.       open (FILE, $file) ||
  841.          (warn ("$file: $!\n"), return 0);
  842.       push (@filedata, <FILE>);
  843.       close (FILE);
  844.       return 1;
  845.    }</PRE>
  846. <PRE>
  847.    @options = 
  848.       (['-read_file', 'call', undef, \&read_file]);</PRE>
  849. <P>Since <CODE>-read_file</CODE> could occur any number of times on the command line,
  850. we might end up reading an awful lot of files, and thus it might be a
  851. long time before we catch errors late in the command line.  Thus, we'd
  852. like to do a ``spoof'' pass over the command line to catch all errors.  A
  853. simplistic approach would be to supply a spoof callback that just eats
  854. one argument and returns success:</P>
  855. <PRE>
  856.    sub spoof_read_file
  857.    {
  858.       my ($opt, $args) = @_;
  859.       (warn ("$opt option requires an argument\n"), return 0)
  860.          unless @$args;
  861.       shift @$args;
  862.       return 1;
  863.    }</PRE>
  864. <P>Then, you have to tell <CODE>Getopt::Tabular</CODE> about this alternate callback
  865. with no side-effects (apart from eating that one argument):</P>
  866. <PRE>
  867.    &Getopt::Tabular::SetSpoofCodes (-read_file => \&spoof_read_file);</PRE>
  868. <P>(<CODE>SetSpoofCodes</CODE> just takes a list of key/value pairs, where the keys
  869. are <A HREF="#item_call"><CODE>call</CODE></A> or <A HREF="#item_eval"><CODE>eval</CODE></A> options, and the values are the ``no side-effects''
  870. callbacks.  Naturally, the replacement callback for an <A HREF="#item_eval"><CODE>eval</CODE></A> option
  871. should be a string, and for a <A HREF="#item_call"><CODE>call</CODE></A> option it should be a code
  872. reference.  This is not actually checked, however, until you call
  873. <CODE>SpoofGetOptions</CODE>, because <CODE>SetSpoofCodes</CODE> doesn't know whether
  874. options are <A HREF="#item_call"><CODE>call</CODE></A> or <A HREF="#item_eval"><CODE>eval</CODE></A> or what.)</P>
  875. <P>A more useful <CODE>spoof_read_file</CODE>, however, would actually check if the
  876. requested file exists -- i.e., we should try to catch as many errors as
  877. possible, as early as possible:</P>
  878. <PRE>
  879.    sub spoof_read_file
  880.    {
  881.       my ($opt, $args) = @_;
  882.       warn ("$opt option requires an argument\n"), return 0
  883.          unless @$args;
  884.       my $file = shift @$args;
  885.       warn ("$file does not exist or is not readable\n"), return 0
  886.          unless -r $file;
  887.       return 1;
  888.    }</PRE>
  889. <P>Finally, you can frequently merge the ``real'' and ``spoof'' callback into
  890. one subroutine:</P>
  891. <PRE>
  892.    sub read_file
  893.    {
  894.       my ($opt, $args, $spoof) = @_;</PRE>
  895. <PRE>
  896.       warn ("$opt option requires an argument\n"), return 0 unless @$args;
  897.       my $file = shift @$args;
  898.       warn ("$file does not exist or is not readable\n"), return 0
  899.          unless -r $file;
  900.       return 1 if $spoof;
  901.       open (FILE, $file) ||
  902.          (warn ("$file: $!\n"), return 0);
  903.       push (@filedata, <FILE>);
  904.       close (FILE);
  905.       return 1;
  906.    }</PRE>
  907. <P>And then, when specifying the replacement callback to <CODE>SetSpoofCodes</CODE>,
  908. just create an anonymous sub that calls <CODE>read_file</CODE> with <CODE>$spoof</CODE>
  909. true:</P>
  910. <PRE>
  911.    &Getopt::Tabular::SetSpoofCodes 
  912.       (-read_file => sub { &read_file (@_[0,1], 1) });
  913. </PRE>
  914. <PRE>
  915.  
  916. Even though this means a bigger and more complicated callback, you only
  917. need I<one> such callback -- the alternative is to carry around both
  918. C<read_file> and C<spoof_read_file>, which might do redundant processing
  919. of the argument list.</PRE>
  920. <P>
  921. <HR>
  922. <H1><A NAME="author">AUTHOR</A></H1>
  923. <P>Greg Ward <<A HREF="mailto:greg@bic.mni.mcgill.ca">greg@bic.mni.mcgill.ca</A>></P>
  924. <P>Started in July, 1995 as ParseArgs.pm, with John Ousterhout's
  925. Tk_ParseArgv.c as a loose inspiration.  Many many features added over
  926. the ensuing months; documentation written in a mad frenzy 16-18 April,
  927. 1996.  Renamed to Getopt::Tabular, revamped, reorganized, and
  928. documentation expanded 8-11 November, 1996.</P>
  929. <P>Copyright (c) 1995-97 Greg Ward. All rights reserved.  This is
  930. free software; you can redistribute it and/or modify it under the same
  931. terms as Perl itself.</P>
  932. <P>
  933. <HR>
  934. <H1><A NAME="bugs">BUGS</A></H1>
  935. <P>The documentation is bigger than the code, and I still haven't covered
  936. option patterns or extending the type system (apart from pattern types).
  937. Yow!</P>
  938. <P>No support for list-valued options, although you can roll your own with
  939. <STRONG>call</STRONG> options.  (See the demo program included with the distribution
  940. for an example.)</P>
  941. <P>Error messages are hard-coded to English.</P>
  942. <TABLE BORDER=0 CELLPADDING=0 CELLSPACING=0 WIDTH=100%>
  943. <TR><TD CLASS=block VALIGN=MIDDLE WIDTH=100% BGCOLOR="#cccccc">
  944. <STRONG><P CLASS=block> Getopt::Tabular - table-driven argument parsing for Perl 5</P></STRONG>
  945. </TD></TR>
  946. </TABLE>
  947.  
  948. </BODY>
  949.  
  950. </HTML>
  951.