LoginSignup
2
2

More than 5 years have passed since last update.

Perl6 プログラムの引数

Posted at

こんばんは :whale2:
Perl 6 Advent Calendar 2015の17日目です。

こんかいはPerl6でのプログラム引数の受け方

Perl5 だと

Perl5 で引数を解析するのにはGetopt::StdモジュールやGetopt::Longモジュールを使っていました。

15.1. Parsing Program Arguments - Perl Cookbook

Getopt::Std
use v5.18;
use Getopt::Std;

getopts("vo:", \my %args); # -v, -o ARG, sets $args{v}, $args{o}

$args{'v'} && say 'v';
$args{'o'} && say $args{'o'} ;
say @ARGV;
Getopt::Long
use v5.18;
use Getopt::Long;

GetOptions( "verbose"  => \my $verbose,  # -v or --verbose
            "output=s" => \my $output ); # -o=string or --output=string

$verbose && say 'verbose';
$output  && say $output;

Perl6 だと

multi dispatch

たとえば、以下のような書き方でinstall, info, search, helpのオプション指定可能なプログラムができます。1

getopt.pl6
use v6;

multi MAIN ('install', *@modules, Bool :$notests, Bool :$nodeps) {}
multi MAIN ('info', *@modules, Str :$prefix) {}
multi MAIN ('search', $pattern = '', Str :$prefix) {}
multi MAIN ('help') {
  qq:x/ perl6 $*PROGRAM-NAME /.say;
}

そして、これを引数無しで実行すると「使い方」が出力されます。魔法みたい :camel:

出力結果
$ perl6 getopt.pl6
Usage:
  getopt.pl6 [--notests] [--nodeps] install [<modules> ...]
  getopt.pl6 [--prefix=<Str>] info [<modules> ...]
  getopt.pl6 [--prefix=<Str>] search [<pattern>]
  getopt.pl6 help

USAGEサブルーチンを定義しておけば、「使い方」としてそれが実行されます。

use v6;

multi MAIN ('verbose') { }
multi MAIN ('help') {}

sub USAGE () {
note q:to/このプログラムの使い方だよー/.chomp;

     ⌒Y⌒
      |
(Y)  / ̄ ̄ ̄\
|(_/ ゜(゚Д゚)ヽ
~ ~~ ~ ~ ~

このプログラムの使い方だよー
}

すごい(小並感)
おわりです。

参考と注釈


  1. pandaコマンドを参考にしたものです。 

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2