1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
|
[](https://travis-ci.org/Leont/getopt-long6)
NAME
====
Getopt::Long
SYNOPSIS
========
use Getopt::Long;
get-options("length=i" => my $length, # numeric
"file=s" => my $file, # string
"verbose" => my $verbose); # flag
use Getopt::Long;
my $options = get-options("length=i", # numeric
"file=s", # string
"verbose"); # flag
or
use Getopt::Long;
sub MAIN(Int :$length, Str :$file, Bool :$verbose) { ... }
DESCRIPTION
===========
The Getopt::Long module implements extended getopt functions called `get-options()` and `get-options-from`, as well as automatic argument parsing for a `MAIN` sub.
This function adheres to the POSIX syntax for command line options, with GNU extensions. In general, this means that options have long names instead of single letters, and are introduced with a double dash "--". Support for bundling of command line options, as was the case with the more traditional single-letter approach, is also provided.
Command Line Options, an Introduction
=====================================
Command line operated programs traditionally take their arguments from the command line, for example filenames or other information that the program needs to know. Besides arguments, these programs often take command line *options* as well. Options are not necessary for the program to work, hence the name 'option', but are used to modify its default behaviour. For example, a program could do its job quietly, but with a suitable option it could provide verbose information about what it did.
Command line options come in several flavours. Historically, they are preceded by a single dash `-`, and consist of a single letter.
-l -a -c
Usually, these single-character options can be bundled:
-lac
Options can have values, the value is placed after the option character. Sometimes with whitespace in between, sometimes not:
-s 24 -s24
Due to the very cryptic nature of these options, another style was developed that used long names. So instead of a cryptic `-l` one could use the more descriptive `--long`. To distinguish between a bundle of single-character options and a long one, two dashes are used to precede the option name. Also, option values could be specified either like
--size=24
or
--size 24
Getting Started with Getopt::Long
=================================
To use Getopt::Long from a Raku program, you must include the following line in your program:
use Getopt::Long;
This will load the core of the Getopt::Long module and prepare your program for using it.
Getopt::Long as a MAIN wrapper
------------------------------
Getopt::Long can be used as a argument parsing MAIN wrapper, replacing the builtin argument parsing. It will by default offer a Unix-typical command line interface, but various options allow it to be more similar to Raku's ideosyncratic parsing.
It supports the following types for named and positional arguments:
* Bool
* Any
* Str
* Int
* Rat
* Num
* Real
* Numeric
* Complex
* IO::Path
* DateTime
* Date
* Version
It also supports any enum type, and any coercion type that uses any of the aforementioned types as its contraint type (e.g. `Foo(Str)`).
An explicit converter can also be set using an `is option` trait, e.g.
sub MAIN(Foo :$foo is option(&foo-converter)) { ... }
Simple options
--------------
The most simple options are the ones that take no values. Their mere presence on the command line enables the option. Popular examples are:
--all --verbose --quiet --debug
Handling simple options is straightforward:
sub MAIN(Bool :$verbose, Bool :$all) { ... }
or:
get-options('verbose' => my $verbose, 'all' => my $all);
The call to `get-options()` parses the command line arguments that are present in `@*ARGS` and sets the option variable to the value `True` if the option did occur on the command line. Otherwise, the option variable is not touched. Setting the option value to true is often called *enabling* the option.
The option name as specified to the `get-options()` function is called the option *specification*. Later we'll see that this specification can contain more than just the option name.
`get-options()` will return a `Capture` if the command line could be processed successfully. Otherwise, it will throw an error using die().
A little bit less simple options
--------------------------------
Getopt::Long supports two useful variants of simple options: *negatable* options and *incremental* options.
A negatable option is specified with an exclamation mark `!` after the option name or a default value for `MAIN` argument:
sub MAIN(Bool :$verbose = False) { ... }
or:
get-options('verbose!' => my $verbose);
or:
my $options = get-options('verbose!');
Now, using `--verbose` on the command line will enable `$verbose`, as expected. But it is also allowed to use `--noverbose` or `--no-verbose`, which will disable `$verbose ` by setting its value to `False`.
An incremental option is specified with a plus `+` after the option name:
sub MAIN(Int :$verbose is option('+')) { ... }
or:
get-options('verbose+' => my $verbose);
or
my $options = get-options('verbose+');
Using `--verbose` on the command line will increment the value of `$verbose`. This way the program can keep track of how many times the option occurred on the command line. For example, each occurrence of `--verbose` could increase the verbosity level of the program.
Mixing command line option with other arguments
-----------------------------------------------
Usually programs take command line options as well as other arguments, for example, file names. It is good practice to always specify the options first, and the other arguments last. Getopt::Long will, however, allow the options and arguments to be mixed and 'filter out' all the options before passing the rest of the arguments to the program. To stop Getopt::Long from processing further arguments, insert a double dash `--` on the command line:
--size 24 -- --all
In this example, `--all` will *not* be treated as an option, but passed to the program unharmed, in `@*ARGS`.
Options with values
-------------------
For options that take values it must be specified whether the option value is required or not, and what kind of value the option expects.
Three kinds of values are supported: integer numbers, floating point numbers, and strings.
If the option value is required, Getopt::Long will take the command line argument that follows the option and assign this to the option variable. If, however, the option value is specified as optional, this will only be done if that value does not look like a valid command line option itself.
sub MAIN(Str :$tag) { ... }
or
get-options('tag=s' => my $tag);
or my %options = get-options('tag=s');
In the option specification, the option name is followed by an equals sign `=` and the letter `s`. The equals sign indicates that this option requires a value. The letter `s` indicates that this value is an arbitrary string. Other possible value types are `i` for integer values, and `f` for floating point values. Using a colon `:` instead of the equals sign indicates that the option value is optional. In this case, if no suitable value is supplied, string valued options get an empty string `''` assigned, while numeric options are set to `0`.
Options with multiple values
----------------------------
Options sometimes take several values. For example, a program could use multiple directories to search for library files:
--library lib/stdlib --library lib/extlib
You can specify that the option can have multiple values by adding a "@" to the format, or declare the argument as positional:
sub MAIN(Str :@library) { ... }
or
get-options('library=s@' => my @libraries);
or
my $options = get-options('library=s@');
Used with the example above, `@libraries`/`$options<library>` would contain two strings upon completion: `"lib/stdlib"` and `"lib/extlib"`, in that order. It is also possible to specify that only integer or floating point numbers are acceptable values.
Warning: What follows is an experimental feature.
Options can take multiple values at once, for example
--coordinates 52.2 16.4 --rgbcolor 255 255 149
This can be accomplished by adding a repeat specifier to the option specification. Repeat specifiers are very similar to the `{...}` repeat specifiers that can be used with regular expression patterns. For example, the above command line would be handled as follows:
my $options = get-options('coordinates=f{2}', 'rgbcolor=i{3}');
or
sub MAIN(Rat :@coordinates is option('f{2}'),
Int :@rgbcolor is option('i{3}'))
get-options('coordinates=f{2}' => my @coordinates,
'rgbcolor=i{3}' => my @rgbcolor);
It is also possible to specify the minimal and maximal number of arguments an option takes. `foo=s{2,4}` indicates an option that takes at least two and at most 4 arguments. `foo=s{1,}` indicates one or more values; `foo:s{,}` indicates zero or more option values.
Options with hash values
------------------------
If you specify that the option can have multiple named values by adding a "%":
sub MAIN(Str :%define) { ... }
or
get-options("define=s%" => my %define);
or
my $options = get-options("define=s%");
When used with command line options:
--define os=linux --define vendor=redhat
the hash `%defines` or `$options<define> ` will contain two keys, `"os"` with value `"linux"` and `"vendor"` with value `"redhat"`. It is also possible to specify that only integer or floating point numbers are acceptable values. The keys are always taken to be strings.
Options with multiple names
---------------------------
Often it is user friendly to supply alternate mnemonic names for options. For example `--height` could be an alternate name for `--length`. Alternate names can be included in the option specification, separated by vertical bar `|` characters. To implement the above example:
sub MAIN(:height(:$length)) { ... }
or
get-options('length|height=f' => my $length);
or
$options = get-options('length|height=f');
The first name is called the *primary* name, the other names are called *aliases*. When using a hash to store options, the key will always be the primary name.
Multiple alternate names are possible.
Summary of Option Specifications
--------------------------------
Each option specifier consists of two parts: the name specification and the argument specification.
The name specification contains the name of the option, optionally followed by a list of alternative names separated by vertical bar characters.
length option name is "length"
length|size|l name is "length", aliases are "size" and "l"
The argument specification is optional. If omitted, the option is considered boolean, a value of `True` will be assigned when the option is used on the command line.
The argument specification can be
* !
The option does not take an argument and may be negated by prefixing it with "no" or "no-". E.g. `"foo!"` will allow `--foo` (a value of 1 will be assigned) as well as `--nofoo` and `--no-foo` (a value of 0 will be assigned). If the option has aliases, this applies to the aliases as well.
* +
The option does not take an argument and will be incremented by 1 every time it appears on the command line. E.g. `"more+"`, when used with `--more --more --more`, will increment the value three times, resulting in a value of 3 (provided it was 0 or undefined at firs).
The `+` specifier is ignored if the option destination is not a scalar.
* = *type* [ *desttype* ] [ *repeat* ]
The option requires an argument of the given type. Supported types are:
* s
String(`Str`). An arbitrary sequence of characters. It is valid for the argument to start with `-` or `--`.
* i
Integer (`Int`). This can be either an optional leading plus or minus sign, followed by a sequence of digits, or an octal string (`0o`, optionally followed by '0', '1', .. '7'), or a hexadecimal string (`0x` followed by '0' .. '9', 'a' .. 'f', case insensitive), or a binary string (`0b` followed by a series of '0' and '1').
* r
Rational number (`Rat`). For example `3.14`.
* f
Floating-pointer number (`Num`). For example `3.14`, `-6.23E24` and so on.
* c
Complex number (`Complex`). For example `1+2i`.
* p
Path (`IO::Path`). For example `foo/bar.txt`.
* d
An ISO-8601 formatted date and time (`DateTime`). For example `2019-12-30T01:23:45-0700`.
* a
A ISO-8601 formatted date (`Date`). For example `2019-12-30`.
* v
A Version (`Version`). For example `1.2.3`.
The *desttype* can be `@` or `%` to specify that the option is list or a hash valued.
The *repeat* specifies the number of values this option takes per occurrence on the command line. It has the format `{` [ *min* ] [ `,` [ *max* ] ] `}`.
*min* denotes the minimal number of arguments. It defaults to `0`.
*max* denotes the maximum number of arguments. It must be at least *min*. If *max* is omitted, *but the comma is not*, there is no upper bound to the number of argument values taken.
* : *type* [ *desttype* ]
Like `=`, but designates the argument as optional. If omitted, an empty string will be assigned to string values options, and the value zero to numeric options.
Note that if a string argument starts with `-` or `--`, it will be considered an option on itself.
* : *number* [ *desttype* ]
Like `:i`, but if the value is omitted, the *number* will be assigned.
* : + [ *desttype* ]
Like `:i`, but if the value is omitted, the current value for the option will be incremented.
Advanced Possibilities
======================
Object oriented interface
-------------------------
Getopt::Long can be used in an object oriented way as well:
use Getopt::Long;
my $p = Getopt::Long.new-from-patterns(@options);
my $o = $p.get-options(@args) ...
Configuration options can be passed to the constructor as named arguments:
$p = Getopt::Long.new-from-patterns(@options, :!permute);
Parsing options from an arbitrary array
---------------------------------------
By default, get-options parses the options that are present in the global array `@*ARGS`. A special entry `get-options-from` can be used to parse options from an arbitrary array.
use Getopt::Long;
$ret = get-options-from(@myargs, ...);
The following two calls behave identically:
$ret = get-options( ... );
$ret = get-options-from(@*ARGS, :overwrite, ... );
Configuring Getopt::Long
========================
`get-options` and `get-options-from` take the following named options to configure. When using Getopt::Long as a `MAIN` wrapper, you can set them using the `%*SUB-MAIN-OPTS` variable:
* auto-abbreviate (default: `False`)
Enabling this allows option names to be abbreviated to uniqueness (e.g. `--foo` can be written as `--f` if no other option starts with an `f`).
* compat-builtin (default: `False`)
Enable all compatibility options that make argument parsing more like the builtin argument parsing. Currently that means disabling `bundling` and `permute`, and enabling `compat-singles`, `compat-negation`, `compat-positional` and `auto-help`)
* bundling (default: `!$compat-builtin`)
Enabling this option will allow single-character options to be bundled. To distinguish bundles from long option names, long options *must* be introduced with `--` and bundles with `-`.
Note that, if you have options `a`, `l` and `all`, possible arguments and option settings are:
using argument sets option(s)
-------------------------------
-a, --a a
-l, --l l
-all a, l
--all all
* permute (default: `!$compat-builtin`)
Whether command line arguments are allowed to be mixed with options. Default is enabled unless `$compat-builtin` is set.
If `permute` is enabled, this means that
--foo arg1 --bar arg2 arg3
is equivalent to
--foo --bar arg1 arg2 arg3
* compat-singles (default: `$compat-builtin`)
Enabling this will allow single letter arguments with an `=` between the letter and its argument. E.g. `-j=2` instead of `-j2`. This is for compatibility with raku's built-in argument parsing.
* compat-negation (default: `$compat-builtin`)
Enabling this will allow one to one to use `--/foo` as an alias for `--no-foo`, for compatibility with raku's built-in argument parsing. Note that this still requires the presence of a `--no-foo` handler, typically by using the `!` modifier.
* compat-positional (default: `$compat-builtin`)
Enabling this will turn all positional arguments into allomorphs, if possible.
* compat-space (default: `$compat-builtin`)
By default, an option with an optional argument will take that as a separate argument unless that argument starts with `--`; e.g. `--foo bar`. If this option is enabled, no such separate arguments are allowed, and the only way to express such an argument is in the same argument: `--foo=bar`.
* auto-help (default: `$compat-builtin`)
This adds an extra --help option, that can hook into Raku's built-in usage message generator.
Return values and Errors
========================
`get-options` returns a capture to indicate success, or throws an `Getopt::Long::Exception` otherwise.
Troubleshooting
===============
`get-options` does not fail when an option is not supplied
----------------------------------------------------------
That's why they're called 'options'.
`get-options` does not split the command line correctly
-------------------------------------------------------
The command line is not split by get-options, but by the command line interpreter (CLI). On Unix, this is the shell. On Windows, it is CMD.EXE. Other operating systems have other CLIs.
It is important to know that these CLIs may behave different when the command line contains special characters, in particular quotes or backslashes. For example, with Unix shells you can use single quotes (`'`) and double quotes (`"`) to group words together. The following alternatives are equivalent on Unix:
"two words"
'two words'
two\ words
In case of doubt, insert the following statement in front of your Perl program:
note @*ARGS.join('|');
to verify how your CLI passes the arguments to the program.
AUTHOR
======
Leon Timmermans <fawaka@gmail.com>
|