1Getopt(3)             User Contributed Perl Documentation            Getopt(3)
2
3
4

NAME

6       Tk::Getopt - User configuration window for Tk with interface to
7       Getopt::Long
8

SYNOPSIS

10           use Tk::Getopt;
11           @opttable = (['opt1', '=s', 'default'], ['opt2', '!', 1], ...);
12           $opt = new Tk::Getopt(-opttable => \@opttable,
13                                 -options => \%options,
14                                 -filename => "$ENV{HOME}/.options");
15           $opt->set_defaults;     # set default values
16           $opt->load_options;     # configuration file
17           $opt->get_options;      # command line
18           $opt->process_options;  # process callbacks, check restrictions ...
19           print $options->{'opt1'}, $options->{'opt2'} ...;
20           ...
21           $top = new MainWindow;
22           $opt->option_editor($top);
23
24       or using a Getopt::Long-like interface
25
26           $opt = new Tk::Getopt(-getopt => ['help'   => \$HELP,
27                                             'file:s' => \$FILE,
28                                             'foo!'   => \$FOO,
29                                             'num:i'  => \$NO,
30                                            ]);
31
32       or an alternative Getopt::Long interface
33
34           %optctl = ('foo' => \$foo,
35                      'bar' => \$bar);
36           $opt = new Tk::Getopt(-getopt => [\%optctl, "foo!", "bar=s"]);
37

DESCRIPTION

39       Tk::Getopt provides an interface to access command line options via
40       Getopt::Long and editing with a graphical user interface via a Tk
41       window.
42
43       Unlike Getopt::Long, this package uses a object oriented interface, so
44       you have to create a new Tk::Getopt object with new. Unlike other
45       packages in the Tk hierarchy, this package does not define a Tk widget.
46       The graphical interface is calles by the method option_editor.
47
48       After creating an object with new, you can parse command line options
49       by calling get_options. This method calls itself
50       Getopt::Long::GetOptions.
51

METHODS

53       new Tk::Getopt(arg_hash)
54           Constructs a new object of the class Tk::Getopt. Arguments are
55           passed in a hash (just like Tk widgets and methods). There are many
56           variants to specify the option description. You can use an
57           interface similar to Getopt::Long::GetOptions by using -getopt or a
58           more powerful interface by using -opttable. Internally, the option
59           description will be converted to the -opttable interface. One of
60           the arguments -getopt or -opttable are mandatory.
61
62           The arguments for new are:
63
64           -getopt
65               -getopt should be a reference to a hash or an array. This hash
66               has the same format as the argument to the
67               Getopt::Long::GetOptions function.  Look at Getopt::Long for a
68               detailed description. Note also that not all of GetOptions is
69               implemented, see "BUGS" for further information.
70
71               Example:
72
73                   new Tk::Getopt(-getopt => [\%options,
74                                              "opt1=i", "opt2=s" ...]);
75
76           -opttable
77               -opttable provides a more powerful interface. The options are
78               stored in variables named $opt_XXX or in a hash when -options
79               is given (see below). -opttable should be a reference to an
80               array containing all options. Elements of this array may be
81               strings, which indicate the beginning of a new group, or array
82               references describing the options. The first element of this
83               array is the name of the option, the second is the type ("=s"
84               for string, "=i" for integer, "!" for boolean, "=f" for float
85               etc., see Getopt::Long) for a detailed list. The third element
86               is optional and contains the default value (otherwise the
87               default is undefined). Further elements are optional too and
88               describe more attributes. For a complete list of these
89               attributes refer to "OPTTABLE ARGUMENTS".
90
91               If an option has no name, then the third element in the
92               description array will be used as an global message for the
93               current option page.  This message can be multi-line.  Example:
94                   ['', '', 'This is an explanation for this option group.']
95
96               To insert horizontal lines, use:
97                   ['', '', '-']
98
99               Here is an example for a simple opttable:
100
101                   @opttable =
102                       ('First section',
103                        ['', '', 'Section description'],
104                        ['debug', '!',  0],
105                        ['age',   '=i', 18],
106
107                        'Second section',
108                        ['', '', 'Description for 2nd section'],
109                        ['browser', '=s', 'tkweb'],
110                        ['foo',     '=f', undef],
111                       );
112                   new Tk::Getopt(-opttable => \@opttable,
113                                  -options => \%options);
114
115           -options
116               This argument should be a reference to an (empty) hash. Options
117               are set into this hash. If this argument is missing, options
118               will be stored in variables named $opt_XXX.
119
120           -filename
121               This argument is optional and specifies the filename for
122               loading and saving options.
123
124           -nosafe
125               If set to true, do not use a safe compartment when loading
126               options (see load_options).
127
128           -useerrordialog
129               If set to true, then use an error dialog in user-relevant error
130               conditions. Otherwise, the error message is printed to STDERR.
131               This only includes errors which may happen in normal operation,
132               but not programming errors like specifying erroneous options.
133               If no Tk context is available (i.e. there is no MainWindow),
134               then the error message will also be printed to STDERR.
135
136       set_defaults
137           Sets default values. This only applies if the -opttable variant is
138           used.
139
140       load_options(filename)
141           Loads options from file filename, or, if not specified, from
142           object's filename as specified in new. The loading is done in a
143           safe compartment ensure security.The loaded file should have a
144           reference to a hash named $loadoptions.
145
146       save_options(filename)
147           Writes options to file filename, or, if not specified, from
148           object's filename as specified in new. The saving is done with
149           Data::Dumper. Since saving may fail, you should call this method
150           inside of "eval {}" and check $@. Possible exceptions are "No
151           Data::Dumper" (cannot find the Data::Dumper module) and "Writing
152           failed" (cannot write to file).
153
154       get_options
155           Gets options via GetOptions. Returns the same value as GetOptions,
156           i.e.  0 indicates that the function detected one or more errors.
157
158           If you want to process options which does not appear in the GUI,
159           you have two alternatives:
160
161           ·       Use the -opttable variant of the "new" constructor and mark
162                   all non-GUI options with nogui, e.g.
163
164                       new Tk::Getopt(-opttable => ['not-in-gui', '!', undef,
165                                                    nogui => 1], ...)
166
167           ·       Use Getopt::Long::passthrough and process non-GUI options
168                   directly with Getopt::Long::GetOptions. The remaining args
169                   can be passed to get_options.
170
171                   Example:
172
173                       use Tk::Getopt;
174                       use Getopt::Long;
175
176                       $Getopt::Long::passthrough = 1;
177                       GetOptions('options!' => \$preloadopt);
178                       $Getopt::Long::passthrough = 0;
179
180                       $opt = new Tk::Getopt( ... );
181                       $opt->get_options;
182
183       usage
184           Generates an usage string from object's opttable. The usage string
185           is constructed from the option name, default value and help
186           entries.
187
188       process_options([undo_hash])
189           Checks wheather given values are valid (if strict is set) and calls
190           any callbacks specified by the sub option. If undo_hash is given
191           and the new value of an option did not change, no sub is called.
192
193       option_editor(widget, [arguments ...])
194           Pops the option editor up. The editor provides facilitied for
195           editing options, undoing, restoring to their default valued and
196           saving to the default options file.
197
198           The option editor is non-modal. For a modal dialog, see below for
199           the "option_dialog" method.
200
201           The first argument is the parent widget. Further optional arguments
202           are passed as a hash:
203
204           -callback
205                   Execute additional callback after creating the option
206                   editor. Arguments passed to this callback are: reference to
207                   the Tk::Getopt object and a reference to the option editor
208                   window.
209
210           -nosave Disable saving of options.
211
212           -savevar
213                   When saving with the "saveoptions" method, use the
214                   specified variable reference instead of the "-var"
215                   reference. This is useful if "-var" is a subroutine
216                   reference.
217
218           -buttons
219                   Specify, which buttons should be drawn. It is advisable to
220                   draw at least the OK and Cancel buttons. The default set
221                   looks like this:
222
223                       -buttons => [qw/ok apply cancel undo lastsaved save defaults/]
224
225                   A minimal set could look like (here OK means accept and
226                   save)
227
228                       -buttons => [qw/oksave cancel/]
229
230                   (and using less buttons is recommended).
231
232           -toplevel
233                   Use another widget class instead of Toplevel for embedding
234                   the option editor, e.g. "Frame" to embed the editor into
235                   another toplevel widget (do not forget to pack the frame!).
236                   See also the "-pack" option below.
237
238           -transient
239                   Set the transient flag on the toplevel window. See the
240                   description of the transient method in Tk::Wm.
241
242                       -transient => $mw
243
244           -pack   If using "-toplevel" with a non-Toplevel widget (e.g.
245                   Frame) and using the "-wait" option, then packing have to
246                   be done through the "-pack" option. The argument to this
247                   option is a array reference of pack options, e.g.
248
249                       $opt->option_editor(-toplevel => "Frame",
250                                           -wait => 1,
251                                           -pack => [-fill => "both", -expand => 1]);
252
253           -statusbar
254                   Use an additional status bar for help messages.
255
256           -string Change button labels and title. This argument should be a
257                   hash reference with all or a subset of the following keys:
258                   "optedit", "undo", "lastsaved", "save", "defaults", "ok",
259                   "cancel", "helpfor".
260
261           -wait   Do not return immediately, but rather wait for the user
262                   pressing OK or Cancel.
263
264           -page   Raise the named notebook page (if grouping is used, see
265                   below).
266
267           Since the option editor uses the "NoteBook" widget, options may be
268           grouped in several pages. Grouping is only possible if using the
269           "-opttable" variant of "new". Help messages are shown in balloons
270           and, if specified, in a statusbar.
271
272           option_editor returns a reference to the created window.
273
274           Note: this method returns immediately to the calling program.
275
276           Buttons in the option editor window:
277
278           OK  Accept options and close option editor window.
279
280           Cancel
281               Set old values and close option editor window.
282
283           Undo
284               Set old values. Further selections toggle between new and old
285               values.
286
287           Last saved
288               Set last saved options. This button is not displayed if no
289               filename was given in "new".
290
291           Save
292               Save options to file. This button is not displayed if no
293               filename was given in "new".
294
295           The option types are translated to following widgets:
296
297           Boolean
298               Checkbutton (_boolean_widget)
299
300           Integer and Float
301               Scale, if range is set, otherwise either BrowseEntry or Entry
302               (_integer_widget, _float_widget).
303
304           String
305               BrowseEntry if choices is set, otherwise entry
306               (_string_widget).  FileDialog if subtype is set to file.
307
308       option_dialog(widget, [arguments ...])
309           This method works like "option_editor", but it shows the option
310           editor as a modal dialog. Additionaly, the return value is either
311           ok or cancel depending on how the user quits the editor.
312

OPTTABLE ARGUMENTS

314       Additional attributes in an option description have to be key-value
315       pairs with following keys:
316
317       alias
318           An array of aliases also accepted by Getopt::Long.
319
320       callback
321           Call a subroutine every time the option changes (e.g. after
322           pressing on Apply, Ok or after loading). The callback will get a
323           hash with the following keys as argument:
324
325           optdef
326               The opttable item definition for this option.
327
328           bag A hash reference which is persistent for this "process_options"
329               call. This can be used to share state between multiple
330               callbacks.
331
332       callback-interactive
333           Like "callback", but only applies in interactive mode.
334
335       label
336           A label to be displayed in the GUI instead of the option name.
337
338       help
339           A short help string used by usage and the Balloon help facility in
340           option_editor.
341
342       longhelp
343           A long help string used by option_editor.
344
345       choices
346           An array of additional choices for the option editor.
347
348           If "strict" is set to a true value, then the elements of choices
349           may also contain array references. In this case the first value of
350           the "sub" array references are the display labels and the second
351           value the used value. This is similar to Tk::Optionmenu (in fact,
352           for displaying this option an Optionmenu is used).
353
354                choices => ["one", "two", "three"]
355
356                choices => [["english"  => "en"],
357                            ["deutsch"  => "de"],
358                            ["hrvatski" => "hr"]]
359
360       range
361           An array with the beginning and end of a range for an integer or
362           float value.
363
364       strict
365           Must be used with choices or range. When set to true, options have
366           to match either the choices or the range.
367
368       subtype
369           Valid subtypes are file, savefile, dir, geometry, font and color.
370           These can be used with string options. For file and savefile, the
371           GUI interface will pop up a file dialog, using getOpenFile for the
372           former and getSaveFile for the latter. For dir, the GUI interface
373           will pop up a dialog for selecting directories (using either
374           Tk::chooseDirectory, Tk::DirSelect, or a custom dialog built on top
375           of Tk::DirTree). If the geometry subtype is specified, the user can
376           set the current geometry of the main window.  The color subtype is
377           not yet implemented.
378
379       var Use variable instead of $options->{optname} or $opt_optname to
380           store the value.
381
382       nogui
383           This option will not have an entry in the GUI.
384
385       size
386           Create an entry with the specified size.
387
388       maxlength
389           Restrict the maximum number of characters in entries.
390
391       widget
392           This should be a reference to a subroutine for creating an own
393           widget.  Folowing arguments will be passed to this subroutine: a
394           reference to the Tk::Getopt object, Frame object, and the options
395           entry. The options entry should be used to get the variable
396           reference with the "_varref" method. The subroutine should create a
397           widget in the frame (packing is not necessary!) and should return a
398           reference to the created widget.
399
400           A sample with an opttable entry for a custom numeric entry using
401           the CPAN module Tk::NumEntry:
402
403              ['numentry', '=i', 50,
404               range => [0, 100],
405               widget => sub { numentry_widget(@_) },
406              ],
407
408           And "numentry_widget" defined as:
409
410               use Tk::NumEntry;
411               sub numentry_widget {
412                   my($self, $frame, $opt) = @_;
413                   my $v = $self->varref($opt);
414                   $frame->NumEntry(-minvalue => $opt->[3]{range}[0],
415                                    -maxvalue => $opt->[3]{range}[1],
416                                    -variable => $v,
417                                    -value => $$v,
418                                   );
419               }
420
421       Here is an example for using a complex opttable description:
422
423           @opttable =
424               ('Misc',   # Head of first group
425                ['debug', # name of the option (--debug)
426                 '!',     # type boolean, accept --nodebug
427                 0,       # default is 0 (false)
428                 callback => sub { $^W = 1
429                                       if $options->{'debug'}; }
430                 # additional attribute: callback to be called if
431                 # you set or change the value
432                 ],
433                ['age',
434                 '=i',    # option accepts integer value
435                 18,
436                 strict => 1, # value must be in range
437                 range => [0, 100], # allowed range
438                 alias => ['year', 'years'] # possible aliases
439                 ],
440                'External', # Head of second group
441                ['browser',
442                 '=s',    # option accepts string value
443                 'tkweb',
444                 choices => ['mosaic', 'netscape',
445                             'lynx', 'chimera'],
446                 # choices for the list widget in the GUI
447                 label => 'WWW browser program'
448                 # label for the GUI instead of 'browser'
449                 ],
450                ['foo',
451                 '=f',    # option accepts float value
452                 undef,   # no default value
453                 help => 'This is a short help',
454                 # help string for usage() and the help balloon
455                 longhelp => 'And this is a slightly longer help'
456                 # longer help displayed in the GUI's help window
457                 ]);
458

OPTION ENTRY METHODS

460       These methods operate on option entries:
461
462       varref(optentry)
463           Return the variable reference for this entry.
464
465       optextra(optentry, optarg)
466           Return the value for the specified optarg argument. See the
467           "OPTTABLE ARGUMENTS" section above for a list of possible
468           arguments.
469

COMPATIBILITY

471       The argument to -opttable can be converted to a "Getopt::Long"
472       compatible argument list with the following function:
473
474         sub opttable_to_getopt {
475             my(%args) = @_;
476             my $options = $args{-options};
477             my @getopt;
478             for (@{$args{-opttable}}) {
479               if (ref $_) {
480                   push @getopt, $_->[0].$_->[1];
481                   if (defined $_->[3] and ref $_->[3] ne 'HASH') {
482                       my %h = splice @$_, 3;
483                       $_->[3] = \%h;
484                   }
485                   if ($_->[3]{'var'}) {
486                       push @getopt, $_->[3]{'var'};
487                   } else {
488                       push @getopt, \$options->{$_->[0]};
489                   }
490               }
491             }
492             @getopt;
493         }
494

REQUIREMENTS

496       You need at least:
497
498       ·   perl5.004 (perl5.003 near 5.004 may work too, e.g perl5.003_26)
499
500       ·   Tk400.202 (better: Tk800.007) (only if you want the GUI)
501
502       ·   Data-Dumper-2.07 (only if you want to save options and it's anyway
503           standard in perl5.005)
504

BUGS

506       Be sure to pass a real hash reference (not a uninitialized reference)
507       to the -options switch in "new Tk::Getopt". Use either:
508
509           my %options;
510           my $opt = new Tk::Getopt(-options => \%options ...)
511
512       or
513
514           my $options = {};
515           my $opt = new Tk::Getopt(-options => $options ...)
516
517       Note the initial assignement for $options in the second example.
518
519       Not all of Getopt::Long is supported (array and hash options, <>,
520       abbrevs).
521
522       The option editor probably should be a real widget.
523
524       The option editor window may grow very large if NoteBook is not used
525       (should use a scrollable pane).
526
527       If the user resizes the window, the buttons at bottom may disappear.
528       This is confusing and it is advisable to disallow the resizing:
529
530           $opt_editor = $opt->option_editor;
531           $opt_editor->resizable(0,0);
532
533       The API will not be stable until version 1.00.
534
535       This manual is confusing. In fact, the whole module is confusing.
536
537       Setting variables in the editor should not set immediately the real
538       variables.  This should be done only by Apply and Ok buttons.
539
540       There's no -font option (you have to use tricks with the option db and
541       a special Name for the option editor):
542
543           $top->optionAdd("*somename*font" => $font);
544           $opt->option_editor(Name => "somename", ...);
545
546       There's no (easy) way to get a large option editor fit on small
547       screens. Try -font, if it would exist, but see above.
548

AUTHOR

550       Slaven Rezic <slaven@rezic.de>
551
552       This package is free software; you can redistribute it and/or modify it
553       under the same terms as Perl itself.
554

SEE ALSO

556       perl Getopt::Long Data::Dumper Tk Tk::FileDialog Tk::NoteBook Tk::Tiler
557       Safe
558
559
560
561perl v5.30.0                      2019-07-26                         Getopt(3)
Impressum