Perl 6 command line interaction from the MAIN function

Original author: Moritz
  • Transfer
In a Unix environment, many scripts get arguments from the command line. In Perl 6, handling them is very simple:

    $ cat

    sub MAIN($x, $y) {
        say $x + $y

    $ perl6 3 4
    $ perl6 too many arguments
    Usage: x y

Just by creating the MAIN function and setting the signature from the parameters to it, you automatically get a command line parser that passes them into the arguments to the $ x and $ y functions, and a message about the correct script call.

This message can be configured by adding an additional USAGE function:

    $ cat

    sub MAIN($x, $y) {
        say $x + $y
    sub USAGE() {
        say "Использование: ";

    $ perl6 too many arguments

By declaring the MAIN function as multi, you can specify an alternative syntax or use syntax depending on the value of the constant:

    $ cat calc

    #!/usr/bin/env perl6
    multi MAIN('add', $x, $y)  { say $x + $y }
    multi MAIN('div', $x, $y)  { say $x / $y }
    multi MAIN('mult', $x, $y) { say $x * $y }

    $ ./calc add 3 5
    $ ./calc mult 3 5
    $ ./calc
    ./calc add x y
    ./calc div x y
    ./calc mult x y

Named parameters correspond to the options:

    $ cat

    sub MAIN($source, $target, Bool :$verbose) {
        say "Копируем '$source' в '$target'" if $verbose;
        run "cp $source $target";

    $ perl6 calc calc2
    $ perl6  --verbose calc calc2
    Копируем 'calc' to 'calc2'

Declaring a parameter as Bool cancels the passing of a value into it. If there were no restrictions of type Bool, the value would be passed to it:

    $ cat

    sub MAIN(:$how = 'быстро') {
        say "Ничего не делай, но делай это $how";

    $ perl6
    Ничего не делай, но делай это быстро
    $ perl6 --how=хорошо
    Ничего не делай, но делай это хорошо
    $ perl6 what?
    Usage: [--how=value-of-how]

In general, Perl 6 provides built-in capabilities for the command line parser and for reporting the proper use of the program when you simply declare special functions and their signatures.

Also popular now: