Raku Land

The uploading author of cpan:ROAM does not match the META author of github:ppentchev.




Getopt::Std - Process single-character options with option clustering


    use Getopt::Std;

    # Classical usage, slightly extended:
    # - for options that take an argument, return only the last one
    # - for options that don't, return a string containing the option
    #   name as many times as the option was specified

    my Str:D %opts = getopts('ho:V', @*ARGS);
    CATCH { when X::Getopt::Std { .message.note; usage } };

    version() if %opts<V>;
    usage(True) if %opts<h>;
    exit(0) if %opts{<V h>}:k;

    my $outfile = %opts<o> // 'a.out';

    # "All options" usage:
    # - for options that take an argument, return an array of all
    #   the arguments supplied if specified more than once
    # - for options that don't, return the option name as many times
    #   as it was specified

    my %opts = getopts-all('o:v', @*ARGS);

    $verbose_level = %opts<v>.elems;

    for %opts<o> -> $fname {
        process_outfile $fname;

    # Permute usage (with both getopts() and getopts-all()):
    # - don't stop at the first non-option argument, look for more
    #   arguments starting with a dash
    # - stop at an -- argument

    my Str:D %opts;
    %opts = getopts('ho:V', @*ARGS, :permute);


This module exports the getopts() and getopts-all()> functions for parsing command-line arguments similarly to the POSIX getopt(3) standard C library routine.

The options are single letters (no long options) preceded by a single dash character. Options that do not accept arguments may be clustered (e.g. -hV for -h and -V); the last one may be an option that accepts an argument (e.g. -vo outfile.txt). Options that accept arguments may have their argument "glued" to the option or in the next element of the arguments array, i.e. -ooutfile is equivalent to -o outfile. There is no equals character between an option and its argument; if one is supplied, it will be considered the first character of the argument.

If an unrecognized option character is supplied in the arguments array, getopts() will throw an exception. Otherwise it will return a hash with the options found in the arguments array. The key in the returned hash is the option name (e.g. h or o); the value is the option argument for options that accept one or the option name (as many times as it has been specified) for options that do not.



Peter Pentchev <roam@ringlet.net>


Copyright (C) 2016, 2017, 2020 Peter Pentchev


The Getopt::Std module is distributed under the terms of the Artistic License 2.0. For more details, see the full text of the license in the file LICENSE in the source distribution.