📜 ⬆️ ⬇️

Perl 6 command line interaction from MAIN function

In a Unix environment, many scripts take arguments from the command line. In Perl 6, handling them is very simple:

$ 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 xy 


Simply creating the MAIN function and specifying its signature from the parameters, you automatically get a command line parser that passes them to the arguments of the $ x and $ y functions, and a message about the correct script call.

This message can be customized by adding an additional USAGE feature:
')
  $ cat add2.pl 

  sub MAIN($x, $y) { say $x + $y } sub USAGE() { say ": add.pl <num1> <num2>"; } 

  $ perl6 add2.pl too many arguments : add.pl <num1> <num2> 


By declaring the MAIN function as multi, you can specify an alternative syntax or use syntax depending on the value of a 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 xy or ./calc div xy or ./calc mult xy 


Named parameters correspond to 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 transfer of values ​​to it If there were no Bool type constraints, 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 the built-in features of the command line parser and issuing messages about the proper use of the program when you simply declare special functions and their signatures.

Source: https://habr.com/ru/post/252451/


All Articles