Help language development. Donate to The Perl Foundation

Getopt::ForClass cpan:HANENKAMP last updated on 2018-08-06



Getopt::ForClass - Use MAIN to dispatch to a class


#!/usr/bin/env perl6
use Getopt::ForClass;

class MyApp {
    has $.token;

    method BUILD(:$!token) { }

    method list-things(:$filter) { ... }
    method add-thing($name) { ... }
    method remove-thing($name, Bool :$cascade) { ... }

our &MAIN := build-main-for-class(
    class => MyApp,

# On the command-line:
# % myapp --token=abc123 list-things --filter red
# % myapp --token=abc123 add-thing socks
# % myapp --token=abc123 remove-thing shrubbery --cascade


This module exports a function, build-main-for-class, which takes a class type and uses it to setup a MAIN function that is able to execut the various methods of that class as sub-commands of the script.


sub build-main-for-class

sub build-main-for-class(:$class!, :$methods = *) returns Routine:D

This routine is exported by default. Given a $class, it will inspect that class and generate a MAIN function that is able to execute one of the methods of that class per run. It does this by generating a multisub, which may be assigned to MAIN in your program.

Specifically, it does the following:

When run, the MAIN method will first construct an object by calling the new method and passing to that method the same parameters as are defined in BUILD. It will then call the method for the selected candidate passing to that method all the arguments given on the command-line.


sub MAIN_HELPER($retval = 0)

In addition to generating the MAIN routine, this module also provides a MAIN_HELPER, which will parse the command-line arguments to call the generated MAIN subroutine.

This implementation will attempt to locate the most appropriate MAIN candidate using parameters given on the command-line. It will then organize and pass the command-line parameters to the MAIN candidate. This works somewhat differently from the Perl6 native MAIN_HELPER (at least as of this writing):

This implementation is less picky about the ordering of parameters than the built-in Perl 6 implementation that is in place as of this writing.


Sterling Hanenkamp <>


Copyright 2016 Sterling Hanenkamp.

This software is licensed under the same terms as Perl 6.