Getopt(3)

πŸ“¦
version 0.52 Β· 4 versions
, in epel 9

πŸ’– NAME πŸ’–

Tk::Getopt β€” a whole user configuration window for Tk, with an interface to Getopt::Long ✨

(also known as Getopt(3) from the User Contributed Perl Documentation crew 🫢 hi bestie, welcome to the group chat)


🌸 SYNOPSIS 🌸

okay so first you gotta use it, obviously:

use Tk::Getopt;
@opttable = (['opt1', '=s', 'default'], ['opt2', '!', 1], ...);
$opt = new Tk::Getopt(-opttable => \@opttable,
                      -options => \%options,
                      -filename => "$ENV{HOME}/.options");
$opt->set_defaults;     # set default values
$opt->load_options;     # configuration file
$opt->get_options;      # command line
$opt->process_options;  # process callbacks, check restrictions ...
print $options->{'opt1'}, $options->{'opt2'} ...;
...
$top = new MainWindow;
$opt->option_editor($top);

or, if you'd rather live that Getopt::Long-like life (same energy, less setup):

$opt = new Tk::Getopt(-getopt => ['help'   => \$HELP,
                                  'file:s' => \$FILE,
                                  'foo!'   => \$FOO,
                                  'num:i'  => \$NO,
                                 ]);

or the alternative Getopt::Long interface, for when you already have your variables sitting there ready πŸ‘‘

%optctl = ('foo' => \$foo,
           'bar' => \$bar);
$opt = new Tk::Getopt(-getopt => [\%optctl, "foo!", "bar=s"]);

πŸ¦‹ DESCRIPTION πŸ¦‹

Tk::Getopt is literally the moment where command line options and a graphical user interface meet and become besties πŸ’… It gives you an interface to access command line options via Getopt::Long, and lets you edit them in a Tk window. both. at once. iconic.

Quick vibe check though: unlike Getopt::Long, this package uses an object oriented interface, so you have to create a new Tk::Getopt object with new. no shortcuts, no cap.

And here's the plot twist πŸ”₯ β€” unlike the other packages chillin' in the Tk hierarchy, this package does not define a Tk widget. nope. The graphical interface is called by the method option_editor. (the original page spells it "calles" β€” we're leaving that typo alone, it's a relic, it's got lore πŸ’€)

So the flow is: after creating an object with new, you can parse command line options by calling get_options. and that method? it calls itself Getopt::Long::GetOptions. self-possessed queen behavior ✨


πŸ› οΈ METHODS πŸ› οΈ

okay so this is where the actual toolbox lives, bestie. every method, every argument, every little -flag β€” all of it, no skips, no cap πŸ’…

🌟 new Tk::Getopt(arg_hash) 🌟

Builds a brand-new object of the class Tk::Getopt. You pass arguments in a hash β€” just like Tk widgets and methods do. There are many variants for specifying the option description. You can use an interface similar to Getopt::Long::GetOptions by using -getopt, or a more powerful interface by using -opttable. Internally, the option description gets converted to the -opttable interface. One of the arguments -getopt or -opttable is mandatory β€” you literally gotta pick at least one, bestie 🫢

The arguments for new are:

  • -getopt β€” -getopt should be a reference to a hash or an array. This hash has the same format as the argument to the Getopt::Long::GetOptions function. Look at Getopt::Long for a detailed description. Also note that not all of GetOptions is implemented β€” see BUGS for further information.

Example:

new Tk::Getopt(-getopt => [\%options,
                           "opt1=i", "opt2=s" ...]);
  • -opttable β€” -opttable gives you a more powerful interface. The options are stored in variables named $opt_XXX or in a hash when -options is given (see below). -opttable should be a reference to an array containing all options. Elements of this array may be strings, which indicate the beginning of a new group, or array references describing the options. The first element of this array is the name of the option, the second is the type (=s for string, =i for integer, ! for boolean, =f for float etc., see Getopt::Long for a detailed list). The third element is optional and contains the default value (otherwise the default is undefined). Further elements are optional too and describe more attributes. For a complete list of these attributes refer to OPTTABLE ARGUMENTS.

If an option has no name, then the third element in the description array will be used as a global message for the current option page. This message can be multi-line. Example:

['', '', 'This is an explanation for this option group.']

To insert horizontal lines, use:

['', '', '-']

Here is an example for a simple opttable:

@opttable =
    ('First section',
     ['', '', 'Section description'],
     ['debug', '!',  0],
     ['age',   '=i', 18],

     'Second section',
     ['', '', 'Description for 2nd section'],
     ['browser', '=s', 'tkweb'],
     ['foo',     '=f', undef],
    );
new Tk::Getopt(-opttable => \@opttable,
               -options => \%options);
  • -options β€” This argument should be a reference to an (empty) hash. Options are set into this hash. If this argument is missing, options will be stored in variables named $opt_XXX.
  • -filename β€” This argument is optional and specifies the filename for loading and saving options.
  • -nosafe β€” If set to true, do not use a safe compartment when loading options (see load_options).
  • -useerrordialog β€” If set to true, then use an error dialog in user-relevant error conditions. Otherwise, the error message is printed to STDERR. This only includes errors which may happen in normal operation, but not programming errors like specifying erroneous options. If no Tk context is available (i.e. there is no MainWindow), then the error message will also be printed to STDERR.

πŸŽ€ set_defaults πŸŽ€

Sets default values. This only applies if the -opttable variant is used.

πŸ¦‹ load_options(filename) πŸ¦‹

Loads options from file filename, or, if not specified, from the object's filename as specified in new. The loading is done in a safe compartment to ensure security. The loaded file should have a reference to a hash named $loadoptions.

🌸 save_options(filename) 🌸

Writes options to file filename, or, if not specified, to the object's filename as specified in new. The saving is done with Data::Dumper. Since saving may fail, you should call this method inside of eval {} and check $@. Possible exceptions are No Data::Dumper (cannot find the Data::Dumper module) and Writing failed (cannot write to file).

✨ get_options ✨

Gets options via GetOptions. Returns the same value as GetOptions, i.e. 0 indicates that the function detected one or more errors.

If you want to process options which do not appear in the GUI, you have two alternatives:

  • Use the -opttable variant of the new constructor and mark all non-GUI options with nogui, e.g.
new Tk::Getopt(-opttable => ['not-in-gui', '!', undef,
                             nogui => 1], ...)
  • Use Getopt::Long::passthrough and process non-GUI options directly with Getopt::Long::GetOptions. The remaining args can be passed to get_options.

Example:

use Tk::Getopt;
use Getopt::Long;

$Getopt::Long::passthrough = 1;
GetOptions('options!' => \$preloadopt);
$Getopt::Long::passthrough = 0;

$opt = new Tk::Getopt( ... );
$opt->get_options;

πŸ’– usage πŸ’–

Generates a usage string from the object's opttable. The usage string is constructed from the option name, default value and help entries.

🧚 process_options([undo_hash]) 🧚

Checks whether given values are valid (if strict is set) and calls any callbacks specified by the sub option. If undo_hash is given and the new value of an option did not change, no sub is called.

πŸ‘‘ option_editor(widget, [arguments ...]) πŸ‘‘

Pops the option editor up. The editor provides facilities for editing options, undoing, restoring to their default values and saving to the default options file.

The option editor is non-modal. For a modal dialog, see below for the option_dialog method.

The first argument is the parent widget. Further optional arguments are passed as a hash:

  • -callback β€” Execute additional callback after creating the option editor. Arguments passed to this callback are: reference to the Tk::Getopt object and a reference to the option editor window.
  • -nosave β€” Disable saving of options.
  • -savevar β€” When saving with the saveoptions method, use the specified variable reference instead of the -var reference. This is useful if -var is a subroutine reference.
  • -buttons β€” Specify which buttons should be drawn. It is advisable to draw at least the OK and Cancel buttons. The default set looks like this:
-buttons => [qw/ok apply cancel undo lastsaved save defaults/]

A minimal set could look like (here OK means accept and save)

-buttons => [qw/oksave cancel/]

(and using less buttons is recommended).

  • -toplevel β€” Use another widget class instead of Toplevel for embedding the option editor, e.g. Frame to embed the editor into another toplevel widget (do not forget to pack the frame!). See also the -pack option below.
  • -transient β€” Set the transient flag on the toplevel window. See the description of the transient method in Tk::Wm.
-transient => $mw
  • -pack β€” If using -toplevel with a non-Toplevel widget (e.g. Frame) and using the -wait option, then packing has to be done through the -pack option. The argument to this option is an array reference of pack options, e.g.
$opt->option_editor(-toplevel => "Frame",
                    -wait => 1,
                    -pack => [-fill => "both", -expand => 1]);
  • -statusbar β€” Use an additional status bar for help messages.
  • -string β€” Change button labels and title. This argument should be a hash reference with all or a subset of the following keys: optedit, undo, lastsaved, save, defaults, ok, cancel, helpfor.
  • -wait β€” Do not return immediately, but rather wait for the user pressing OK or Cancel.
  • -page β€” Raise the named notebook page (if grouping is used, see below).

Since the option editor uses the NoteBook widget, options may be grouped in several pages. Grouping is only possible if using the -opttable variant of new. Help messages are shown in balloons and, if specified, in a statusbar.

option_editor returns a reference to the created window.

Note: this method returns immediately to the calling program.

Buttons in the option editor window:

  • OK β€” Accept options and close option editor window.
  • Cancel β€” Set old values and close option editor window.
  • Undo β€” Set old values. Further selections toggle between new and old values.
  • Last saved β€” Set last saved options. This button is not displayed if no filename was given in new.
  • Save β€” Save options to file. This button is not displayed if no filename was given in new.

The option types are translated to following widgets:

  • Boolean β€” Checkbutton (_boolean_widget)
  • Integer and Float β€” Scale, if range is set, otherwise either BrowseEntry or Entry (_integer_widget, _float_widget).
  • String β€” BrowseEntry if choices is set, otherwise entry (_string_widget). FileDialog if subtype is set to file.

🌈 option_dialog(widget, [arguments ...]) 🌈

This method works like option_editor, but it shows the option editor as a modal dialog. Additionally, the return value is either ok or cancel depending on how the user quits the editor.

🌸 OPTTABLE ARGUMENTS 🌸

okay bestie so extra attributes in an option description? they have to be key-value pairs, and the keys are literally these:

alias

An array of aliases also accepted by Getopt::Long.

callback

Call a subroutine every time the option changes (e.g. after pressing on Apply, Ok or after loading). The callback will get a hash with the following keys as argument:

  • optdef β€” The opttable item definition for this option.
  • bag β€” A hash reference which is persistent for this process_options call. This can be used to share state between multiple callbacks.

callback-interactive

Like callback, but only applies in interactive mode. same energy, smaller audience.

label

A label to be displayed in the GUI instead of the option name.

help

A short help string used by usage and the Balloon help facility in option_editor.

longhelp

A long help string used by option_editor.

choices

An array of additional choices for the option editor.

If strict is set to a true value, then the elements of choices may also contain array references. In this case the first value of the "sub" array references are the display labels and the second value the used value. This is similar to Tk::Optionmenu (in fact, for displaying this option an Optionmenu is used).

choices => ["one", "two", "three"]

choices => [["english"  => "en"],
            ["deutsch"  => "de"],
            ["hrvatski" => "hr"]]

range

An array with the beginning and end of a range for an integer or float value.

strict

Must be used with choices or range. When set to true, options have to match either the choices or the range.

subtype

Valid subtypes are file, savefile, dir, geometry, font and color. These can be used with string options. For file and savefile, the GUI interface will pop up a file dialog, using getOpenFile for the former and getSaveFile for the latter. For dir, the GUI interface will pop up a dialog for selecting directories (using either Tk::chooseDirectory, Tk::DirSelect, or a custom dialog built on top of Tk::DirTree). If the geometry subtype is specified, the user can set the current geometry of the main window. The color subtype is not yet implemented.

var

Use variable instead of $options->{optname} or $opt_optname to store the value.

nogui

This option will not have an entry in the GUI.

size

Create an entry with the specified size.

maxlength

Restrict the maximum number of characters in entries.

widget

This should be a reference to a subroutine for creating an own widget. Following arguments will be passed to this subroutine: a reference to the Tk::Getopt object, Frame object, and the options entry. The options entry should be used to get the variable reference with the _varref method. The subroutine should create a widget in the frame (packing is not necessary!) and should return a reference to the created widget.

A sample with an opttable entry for a custom numeric entry using the CPAN module Tk::NumEntry:

['numentry', '=i', 50,
 range => [0, 100],
 widget => sub { numentry_widget(@_) },
],

And numentry_widget defined as:

use Tk::NumEntry;
sub numentry_widget {
    my($self, $frame, $opt) = @_;
    my $v = $self->varref($opt);
    $frame->NumEntry(-minvalue => $opt->[3]{range}[0],
                     -maxvalue => $opt->[3]{range}[1],
                     -variable => $v,
                     -value => $$v,
                    );
}

Here is an example for using a complex opttable description:

@opttable =
    ('Misc',   # Head of first group
     ['debug', # name of the option (--debug)
      '!',     # type boolean, accept --nodebug
      0,       # default is 0 (false)
      callback => sub { $^W = 1
                            if $options->{'debug'}; }
      # additional attribute: callback to be called if
      # you set or change the value
      ],
     ['age',
      '=i',    # option accepts integer value
      18,
      strict => 1, # value must be in range
      range => [0, 100], # allowed range
      alias => ['year', 'years'] # possible aliases
      ],
     'External', # Head of second group
     ['browser',
      '=s',    # option accepts string value
      'tkweb',
      choices => ['mosaic', 'netscape',
                  'lynx', 'chimera'],
      # choices for the list widget in the GUI
      label => 'WWW browser program'
      # label for the GUI instead of 'browser'
      ],
     ['foo',
      '=f',    # option accepts float value
      undef,   # no default value
      help => 'This is a short help',
      # help string for usage() and the help balloon
      longhelp => 'And this is a slightly longer help'
      # longer help displayed in the GUI's help window
      ]);

πŸŽ€ OPTION ENTRY METHODS πŸŽ€

These methods operate on option entries:

  • varref(optentry) β€” Return the variable reference for this entry.
  • optextra(optentry, optarg) β€” Return the value for the specified optarg argument. See the OPTTABLE ARGUMENTS section above for a list of possible arguments.

🌈 COMPATIBILITY 🌈

The argument to -opttable can be converted to a Getopt::Long compatible argument list with the following function:

sub opttable_to_getopt {
    my(%args) = @_;
    my $options = $args{-options};
    my @getopt;
    for (@{$args{-opttable}}) {
        if (ref $_) {
            push @getopt, $_->[0].$_->[1];
            if (defined $_->[3] and ref $_->[3] ne 'HASH') {
                my %h = splice @$_, 3;
                $_->[3] = \%h;
            }
            if ($_->[3]{'var'}) {
                push @getopt, $_->[3]{'var'};
            } else {
                push @getopt, \$options->{$_->[0]};
            }
        }
    }
    @getopt;
}

⭐ REQUIREMENTS ⭐

You need at least:

  • perl5.004 (perl5.003 near 5.004 may work too, e.g perl5.003_26)
  • Tk400.202 (better: Tk800.007) (only if you want the GUI)
  • Data-Dumper-2.07 (only if you want to save options and it's anyway standard in perl5.005)

πŸ’€ BUGS πŸ’€

  • Be sure to pass a real hash reference (not an uninitialized reference) to the -options switch in new Tk::Getopt. Use either:
my %options;
my $opt = new Tk::Getopt(-options => \%options ...)

or

my $options = {};
my $opt = new Tk::Getopt(-options => $options ...)

Note the initial assignment for $options in the second example.

  • Not all of Getopt::Long is supported (array and hash options, <>, abbrevs).
  • The option editor probably should be a real widget.
  • The option editor window may grow very large if NoteBook is not used (should use a scrollable pane).
  • If the user resizes the window, the buttons at bottom may disappear. This is confusing and it is advisable to disallow the resizing:
$opt_editor = $opt->option_editor;
$opt_editor->resizable(0,0);
  • The API will not be stable until version 1.00.
  • This manual is confusing. In fact, the whole module is confusing.
  • Setting variables in the editor should not set immediately the real variables. This should be done only by Apply and Ok buttons.
  • There's no -font option (you have to use tricks with the option db and a special Name for the option editor):
$top->optionAdd("*somename*font" => $font);
$opt->option_editor(Name => "somename", ...);
  • There's no (easy) way to get a large option editor fit on small screens. Try -font, if it would exist, but see above.

πŸ‘‘ AUTHOR πŸ‘‘

Slaven Rezic <slaven@rezic.de>

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


πŸ¦‹ SEE ALSO πŸ¦‹

perl Getopt::Long Data::Dumper Tk Tk::FileDialog Tk::NoteBook Tk::Tiler Safe

okay that's the whole page bestie! source/version: perl v5.32.1, date: 2024-09-26, page: Getopt(3) πŸ’…βœ¨

πŸ“¦ where this page comes from