sub MAIN

Documentation for sub MAIN, assembled from the following types:

language documentation Functions

From Functions

(Functions) sub MAIN

The sub with the special name MAIN is executed after all relevant phasers, and its signature is the means by which command line arguments can be parsed. Multi methods are supported and a usage method is automatically generated and displayed if no command line arguments are provided. All command line arguments are also available in @*ARGS, which can be mutated before being processed by MAIN.

The return value of MAIN is ignored: using explicitly return will terminate the MAIN sub but the resulting exit code will always be zero (success). To provide an exit code different from 0, call exit.

#|(optional description for USAGE message) 
sub MAINInt :$length = 24,
           :file($datawhere { .IO.f // die "file not found in $*CWD" } = 'file.dat',
           Bool :v(:$verbose) #`( either --verbose or -v ) )
    say $length if $length.defined;
    say $data   if $data.defined;
    say 'Verbosity ', ($verbose ?? 'on' !! 'off');
    exit 1;


It's possible to alter how arguments are processed before they're passed to sub MAIN {} by setting options in %*SUB-MAIN-OPTS hash. Due to the nature of dynamic variables, one needs to set up its own %*SUB-MAIN-OPTS hash and fill it with the appropriate settings. For instance:

  :named-anywhere,    # allow named variables at any location 
  :!foo,              # don't allow foo 
sub MAIN ($a$b:$c:$d{
    say "Accepted!"

Available options are:


By default, named arguments to the program cannot be given after any positional arguments are specified. However, if %*SUB-MAIN-OPTS<named-anywhere> is set to a truthy value, named arguments can be specified anywhere, even after positional parameter. For example, the above program can be called with:

perl6 example.p6 1 --c=2 3 --d=4