
Perl 6 command line interaction from the MAIN function
- Transfer
In a Unix environment, many scripts get arguments from the command line. In Perl 6, handling them is very simple:
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:
By declaring the MAIN function as multi, you can specify an alternative syntax or use syntax depending on the value of the constant:
Named parameters correspond to the options:
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:
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.
$ cat add.pl
sub MAIN($x, $y) {
say $x + $y
}
$ perl6 add.pl 3 4
7
$ perl6 add.pl too many arguments
Usage:
add.pl 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 add2.pl
sub MAIN($x, $y) {
say $x + $y
}
sub USAGE() {
say "Использование: add.pl ";
}
$ perl6 add2.pl too many arguments
Использование: add.pl
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
8
$ ./calc mult 3 5
15
$ ./calc
Usage:
./calc add x y
or
./calc div x y
or
./calc mult x y
Named parameters correspond to the options:
$ cat copy.pl
sub MAIN($source, $target, Bool :$verbose) {
say "Копируем '$source' в '$target'" if $verbose;
run "cp $source $target";
}
$ perl6 copy.pl calc calc2
$ perl6 copy.pl --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 do-nothing.pl
sub MAIN(:$how = 'быстро') {
say "Ничего не делай, но делай это $how";
}
$ perl6 do-nothing.pl
Ничего не делай, но делай это быстро
$ perl6 do-nothing.pl --how=хорошо
Ничего не делай, но делай это хорошо
$ perl6 do-nothing.pl what?
Usage:
do-nothing.pl [--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.