Getopt-Long-2.58 > Getopt::Long
Getopt-Long-2.58

名前

Getopt::Long - Extended processing of command line options

Getopt::Long - コマンド行オプションの拡張処理

(訳注: (TBR)がついている段落は「みんなの自動翻訳@TexTra」による 機械翻訳です。)

概要

  use Getopt::Long;
  my $data   = "file.dat";
  my $length = 24;
  my $verbose;
  GetOptions ("length=i" => \$length,    # numeric
              "file=s"   => \$data,      # string
              "verbose"  => \$verbose)   # flag
  or die("Error in command line arguments\n");

説明

The Getopt::Long module implements an extended getopt function called GetOptions(). It parses the command line from @ARGV, recognizing and removing specified options and their possible values.

Getopt::Longモジュールは、GetOptions()と呼ばれる拡張getopt関数を実装します。 @ARGVからのコマンド行を解析し、指定されたオプションとその可能な値を認識し削除します。 (TBR)

This function adheres to the POSIX syntax for command line options, with GNU extensions. In general, this means that options have long names instead of single letters, and are introduced with a double dash "--". Support for bundling of command line options, as was the case with the more traditional single-letter approach, is provided but not enabled by default.

この関数は、コマンドラインオプションのPOSIX構文に準拠し、GNU拡張を使用しています。 一般に、これは、オプションが単一文字ではなく長い名前を持ち、二重ダッシュ「--」で導入されることを意味します。 従来の単一文字による方法と同様に、コマンドラインオプションのバンドル化がサポートされていますが、デフォルトでは使用可能になっていません。 (TBR)

Command Line Options, an Introduction

Command line operated programs traditionally take their arguments from the command line, for example filenames or other information that the program needs to know. Besides arguments, these programs often take command line options as well. Options are not necessary for the program to work, hence the name 'option', but are used to modify its default behaviour. For example, a program could do its job quietly, but with a suitable option it could provide verbose information about what it did.

コマンドラインで操作されるプログラムは、伝統的にコマンドラインから引数(例えば、ファイル名やプログラムが知る必要のあるその他の情報)を受け取ります。 引数に加えて、これらのプログラムはしばしばコマンドラインoptionsも受け取ります。 オプションはプログラムが動作するために必要ではないので、「オプション」という名前が付いていますが、デフォルトの動作を変更するために使用されます。 例えば、プログラムはそのジョブを静かに行うことができますが、適切なオプションを使えば、それが何をしたかについての詳細な情報を提供することができます。 (TBR)

Command line options come in several flavours. Historically, they are preceded by a single dash -, and consist of a single letter.

コマンドラインオプションにはいくつかの種類があります。 歴史的には、これらの前には1つのダッシュ-が付き、1つの文字で構成されています。 (TBR)

    -l -a -c

Usually, these single-character options can be bundled:

通常、これらの1文字のオプションは次のようにまとめることができます。 (TBR)

    -lac

Options can have values, the value is placed after the option character. Sometimes with whitespace in between, sometimes not:

オプションは値を持つことができ、値はオプション文字の後に置かれます。 間に空白文字がある場合もあれば、ない場合もあります。 (TBR)

    -s 24 -s24

Due to the very cryptic nature of these options, another style was developed that used long names. So instead of a cryptic -l one could use the more descriptive --long. To distinguish between a bundle of single-character options and a long one, two dashes are used to precede the option name. Early implementations of long options used a plus + instead. Also, option values could be specified either like

これらのオプションの非常に謎めいた性質のために、長い名前を使用する別のスタイルが開発されました。 したがって、謎めいた-lの代わりに、より記述的な--longを使用できます。 単一文字オプションの束と長いオプションを区別するために、オプション名の前に2つのダッシュを使用します。 長いオプションの初期の実装では、代わりにプラス+を使用していました。 また、オプション値は次のように指定できます。 (TBR)

    --size=24

or

または (TBR)

    --size 24

The + form is now obsolete and strongly deprecated.

+形式は廃止され、非推奨になりました。 (TBR)

Getting Started with Getopt::Long

Getopt::Long is the Perl5 successor of newgetopt.pl. This was the first Perl module that provided support for handling the new style of command line options, in particular long option names, hence the Perl5 name Getopt::Long. This module also supports single-character options and bundling.

Getopt::Longは、newgetopt.plのPerl5の後継です。 これは、新しいスタイルのコマンドラインオプション、特に長いオプション名の処理をサポートした最初のPerlモジュールであり、Perl5ではGetopt::Longという名前になっています。 このモジュールは、単一文字オプションとバンドルもサポートしています。 (TBR)

To use Getopt::Long from a Perl program, you must include the following line in your Perl program:

PerlプログラムからGetopt::Longを使用するには、Perlプログラムに次の行を含める必要があります。 (TBR)

    use Getopt::Long;

This will load the core of the Getopt::Long module and prepare your program for using it. Most of the actual Getopt::Long code is not loaded until you really call one of its functions.

これにより、Getopt::Longモジュールのコアがロードされ、それを使用するプログラムが準備されます。 実際のGetopt::Longコードのほとんどは、その関数の1つを実際に呼び出すまでロードされません。 (TBR)

In the default configuration, options names may be abbreviated to uniqueness, case does not matter, and a single dash is sufficient, even for long option names. Also, options may be placed between non-option arguments. See "Configuring Getopt::Long" for more details on how to configure Getopt::Long.

デフォルトの構成では、オプション名は一意になるように省略できます。 大文字と小文字は区別されず、長いオプション名の場合でも1つのダッシュで十分です。 また、オプションをオプション以外の引数の間に置くこともできます。 Getopt::Longの構成方法の詳細は、"Configuring Getopt::Long"を参照してください。 (TBR)

Simple options

The most simple options are the ones that take no values. Their mere presence on the command line enables the option. Popular examples are:

最も単純なオプションは、値を取らないオプションです。 コマンドラインに存在するだけで、オプションが有効になります。 一般的な例は次のとおりです。 (TBR)

    --all --verbose --quiet --debug

Handling simple options is straightforward:

単純なオプションの処理は簡単です。 (TBR)

    my $verbose = '';   # option variable with default value (false)
    my $all = '';       # option variable with default value (false)
    GetOptions ('verbose' => \$verbose, 'all' => \$all);

The call to GetOptions() parses the command line arguments that are present in @ARGV and sets the option variable to the value 1 if the option did occur on the command line. Otherwise, the option variable is not touched. Setting the option value to true is often called enabling the option.

GetOptions()への呼出しは、@ARGVにあるコマンドライン引数を解析し、オプションがコマンド行にある場合は、オプション変数を値1に設定します。 そうでない場合は、オプション変数は変更されません。 オプション値を真に設定することは、オプションを有効にすると呼ばれます。 (TBR)

The option name as specified to the GetOptions() function is called the option specification. Later we'll see that this specification can contain more than just the option name. The reference to the variable is called the option destination.

GetOptions()関数に指定されたオプション名は、オプションspecificationと呼ばれます。 後で、この仕様にはオプション名以上のものを含めることができることがわかります。 変数への参照は、オプションdestinationと呼ばれます。 (TBR)

GetOptions() will return a true value if the command line could be processed successfully. Otherwise, it will write error messages using die() and warn(), and return a false result.

GetOptions()は、コマンドラインが正常に処理された場合はtrueを返します。 それ以外の場合は、die()およびwarn()を使用してエラーメッセージを書き込み、falseを返します。 (TBR)

A little bit less simple options

Getopt::Long supports two useful variants of simple options: negatable options and incremental options.

Getopt::Longは、negableオプションとincrementalオプションという2つの便利な単純オプションをサポートしています。 (TBR)

A negatable option is specified with an exclamation mark ! after the option name:

否定可能なオプションは、オプション名の後に感嘆符!を付けて指定します。 (TBR)

    my $verbose = '';   # option variable with default value (false)
    GetOptions ('verbose!' => \$verbose);

Now, using --verbose on the command line will enable $verbose, as expected. But it is also allowed to use --noverbose, which will disable $verbose by setting its value to 0. Using a suitable default value, the program can find out whether $verbose is false by default, or disabled by using --noverbose.

現在、コマンドラインで--verboseを使用すると、期待どおりに$verboseが有効になります。 しかし、--noverboseを使用することもできます。 これは、その値を0に設定することによって$verboseを無効にします。 適切なデフォルト値を使用して、プログラムは$verboseがデフォルトでfalseであるか、--noverboseを使用して無効になっているかを調べることができます。 (TBR)

(If both --verbose and --noverbose are given, whichever is given last takes precedence.)

(--verbose--noverboseの両方が指定されている場合は、最後に指定された方が優先されます)。 (TBR)

An incremental option is specified with a plus + after the option name:

インクリメンタルオプションは、オプション名の後にプラス記号+を付けて指定します。 (TBR)

    my $verbose = '';   # option variable with default value (false)
    GetOptions ('verbose+' => \$verbose);

Using --verbose on the command line will increment the value of $verbose. This way the program can keep track of how many times the option occurred on the command line. For example, each occurrence of --verbose could increase the verbosity level of the program.

コマンドラインで--verboseを使用すると、$verboseの値が増加します。 これにより、プログラムはコマンドラインでオプションが何回発生したかを追跡できます。 たとえば、--verboseが発生するたびに、プログラムの冗長レベルが増加します。 (TBR)

Mixing command line option with other arguments

Usually programs take command line options as well as other arguments, for example, file names. It is good practice to always specify the options first, and the other arguments last. Getopt::Long will, however, allow the options and arguments to be mixed and 'filter out' all the options before passing the rest of the arguments to the program. To stop Getopt::Long from processing further arguments, insert a double dash -- on the command line:

通常、プログラムはコマンドラインオプションだけでなく、ファイル名などの他の引数も受け取ります。 常にオプションを最初に指定し、他の引数を最後に指定することをお勧めします。 ただし、Getopt::Longでは、オプションと引数を混在させて、残りの引数をプログラムに渡す前にすべてのオプションを「除外」することができます。 Getopt::Longがそれ以上の引数を処理しないようにするには、コマンドラインにダブルダッシュ--を挿入します。 (TBR)

    --size 24 -- --all

In this example, --all will not be treated as an option, but passed to the program unharmed, in @ARGV.

この例では、--allはオプションとして扱われますが<not>、@ARGVにそのままプログラムに渡されます。 (TBR)

Options with values

For options that take values it must be specified whether the option value is required or not, and what kind of value the option expects.

値を取るオプションの場合は、オプション値が必須かどうか、およびオプションが期待する値の種類を指定する必要があります。 (TBR)

Three kinds of values are supported: integer numbers, floating point numbers, and strings.

サポートされている値は、整数、浮動小数点数、文字列の3種類です。 (TBR)

If the option value is required, Getopt::Long will take the command line argument that follows the option and assign this to the option variable. If, however, the option value is specified as optional, this will only be done if that value does not look like a valid command line option itself.

オプション値が必要な場合、Getopt::Longはオプションに続くコマンドライン引数を取り、これをオプション変数に代入します。 ただし、オプション値がオプションとして指定されている場合は、その値が有効なコマンドラインオプションではないと思われる場合にのみ、これが行われます。 (TBR)

    my $tag = '';       # option variable with default value
    GetOptions ('tag=s' => \$tag);

In the option specification, the option name is followed by an equals sign = and the letter s. The equals sign indicates that this option requires a value. The letter s indicates that this value is an arbitrary string. Other possible value types are i for integer values, and f for floating point values. Using a colon : instead of the equals sign indicates that the option value is optional. In this case, if no suitable value is supplied, string valued options get an empty string '' assigned, while numeric options are set to 0.

オプション指定では、オプション名の後に等号=と文字sが続きます。 等号は、このオプションに値が必要であることを示します。 文字sは、この値が任意の文字列であることを示します。 他に使用可能な値の型は、整数値の場合はi、浮動小数点値の場合はfです。 等号の代わりにコロン:を使用すると、オプション値がオプションであることを示します。 この場合、適切な値が指定されていないと、文字列値のオプションには空の文字列''が割り当てられ、数値オプションは0に設定されます。 (TBR)

(If the same option appears more than once on the command line, the last given value is used. If you want to take all the values, see below.)

(同じオプションがコマンドラインに複数回指定されている場合は、最後に指定された値が使用されます。 すべての値を取得する場合は、以下を参照してください。 ) (TBR)

Options with multiple values

Options sometimes take several values. For example, a program could use multiple directories to search for library files:

オプションは複数の値を取ることがあります。 たとえば、プログラムは複数のディレクトリを使用してライブラリファイルを検索できます。 (TBR)

    --library lib/stdlib --library lib/extlib

To accomplish this behaviour, simply specify an array reference as the destination for the option:

この動作を実現するには、オプションの宛先として配列参照を指定するだけです。 (TBR)

    GetOptions ("library=s" => \@libfiles);

Alternatively, you can specify that the option can have multiple values by adding a "@", and pass a reference to a scalar as the destination:

または、「@」を追加してオプションが複数の値を持つことを指定し、宛先としてスカラーへの参照を渡すこともできます。 (TBR)

    GetOptions ("library=s@" => \$libfiles);

Used with the example above, @libfiles c.q. @$libfiles would contain two strings upon completion: "lib/stdlib" and "lib/extlib", in that order. It is also possible to specify that only integer or floating point numbers are acceptable values.

上記の例で使用すると、@libfilesc.q. @$libfilesは、完了時に"lib/stdlib""lib/extlib"の2つの文字列をこの順序で含むことになります。 整数または浮動小数点数のみを有効な値として指定することもできます。 (TBR)

Often it is useful to allow comma-separated lists of values as well as multiple occurrences of the options. This is easy using Perl's split() and join() operators:

多くの場合、オプションの複数回の出現だけでなく、カンマで区切られた値のリストを許可すると便利です。 これは、Perlのsplit()およびjoin()演算子を使用すると簡単です。 (TBR)

    GetOptions ("library=s" => \@libfiles);
    @libfiles = split(/,/,join(',',@libfiles));

Of course, it is important to choose the right separator string for each purpose.

もちろん、目的ごとに適切な区切り文字列を選択することが重要です。 (TBR)

Warning: What follows is an experimental feature.

警告:以下は実験的な機能です。 (TBR)

Options can take multiple values at once, for example

オプションは一度に複数の値をとることができます。 (TBR)

    --coordinates 52.2 16.4 --rgbcolor 255 255 149

This can be accomplished by adding a repeat specifier to the option specification. Repeat specifiers are very similar to the {...} repeat specifiers that can be used with regular expression patterns. For example, the above command line would be handled as follows:

これは、オプション指定に繰り返し指定子を追加することで実現できます。 繰り返し指定子は、正規表現パターンで使用できる{.}繰り返し指定子と非常によく似ています。 たとえば、上記のコマンドラインは次のように処理されます。 (TBR)

    GetOptions('coordinates=f{2}' => \@coor, 'rgbcolor=i{3}' => \@color);

The destination for the option must be an array or array reference.

オプションの格納先は、配列または配列参照である必要があります。 (TBR)

It is also possible to specify the minimal and maximal number of arguments an option takes. foo=s{2,4} indicates an option that takes at least two and at most 4 arguments. foo=s{1,} indicates one or more values; foo:s{,} indicates zero or more option values.

オプションが取る引数の最小数と最大数を指定することもできます。 foo=s{2,4}は、少なくとも2つ、多くても4つの引数を取るオプションを示します。 foo=s{1,}は1つ以上の値を示し、foo:s{,}は0個以上のオプション値を示します。 (TBR)

Options with hash values

If the option destination is a reference to a hash, the option will take, as value, strings of the form key=value. The value will be stored with the specified key in the hash.

オプションの宛先がハッシュへの参照である場合、オプションは値としてkey=valueの形式の文字列を取ります。 値は指定されたキーとともにハッシュに格納されます。 (TBR)

    GetOptions ("define=s" => \%defines);

Alternatively you can use:

または、以下を使用することもできます。 (TBR)

    GetOptions ("define=s%" => \$defines);

When used with command line options:

コマンドラインオプションとともに使用する場合: (TBR)

    --define os=linux --define vendor=redhat

the hash %defines (or %$defines) will contain two keys, "os" with value "linux" and "vendor" with value "redhat". It is also possible to specify that only integer or floating point numbers are acceptable values. The keys are always taken to be strings.

ハッシュ%defines(または%$defines)は2つのキーを持ちます。 値"linux""os"と値"redhat""vendor"です。 整数または浮動小数点数だけが値として受け入れられるように指定することもできます。 キーは常に文字列と解釈されます。 (TBR)

User-defined subroutines to handle options

Ultimate control over what should be done when (actually: each time) an option is encountered on the command line can be achieved by designating a reference to a subroutine (or an anonymous subroutine) as the option destination. When GetOptions() encounters the option, it will call the subroutine with two or three arguments. The first argument is the name of the option. (Actually, it is an object that stringifies to the name of the option.) For a scalar or array destination, the second argument is the value to be stored. For a hash destination, the second argument is the key to the hash, and the third argument the value to be stored. It is up to the subroutine to store the value, or do whatever it thinks is appropriate.

コマンドラインでオプションに遭遇したとき(実際には毎回)に何をすべきかを最終的に制御するには、オプションの宛先としてサブルーチン(または匿名サブルーチン)への参照を指定します。 GetOptions()はオプションに遭遇すると、2つまたは3つの引数を使用してサブルーチンを呼び出します。 最初の引数はオプションの名前です(実際には、オプションの名前に文字列化されるオブジェクトです)。 スカラーまたは配列の宛先の場合、2番目の引数は格納される値です。 ハッシュの宛先の場合、2番目の引数はハッシュへのキーで、3番目の引数は格納される値です。 値を格納するか、適切と思われることを行うかは、サブルーチン次第です。 (TBR)

A trivial application of this mechanism is to implement options that are related to each other. For example:

このメカニズムの簡単なアプリケーションは、相互に関連するオプションを実装することです。 次に例を示します。 (TBR)

    my $verbose = '';   # option variable with default value (false)
    GetOptions ('verbose' => \$verbose,
                'quiet'   => sub { $verbose = 0 });

Here --verbose and --quiet control the same variable $verbose, but with opposite values.

ここで、--verbose--quietは同じ変数$verboseを制御しますが、値は逆です。 (TBR)

If the subroutine needs to signal an error, it should call die() with the desired error message as its argument. GetOptions() will catch the die(), issue the error message, and record that an error result must be returned upon completion.

サブルーチンがエラーを通知する必要がある場合は、目的のエラーメッセージを引数としてdie()を呼び出す必要があります。 GetOptions()はdie()をキャッチし、エラーメッセージを発行し、完了時にエラー結果を返す必要があることを記録します。 (TBR)

If the text of the error message starts with an exclamation mark ! it is interpreted specially by GetOptions(). There is currently one special command implemented: die("!FINISH") will cause GetOptions() to stop processing options, as if it encountered a double dash --.

エラーメッセージのテキストが感嘆符!で始まる場合は、GetOptions()によって特別に解釈されます。 現在、1つの特別なコマンドが実装されています。 die("!FINISH")を実行すると、GetOptions()は、ダブルダッシュ--が発生したかのように、オプションの処理を停止します。 (TBR)

Here is an example of how to access the option name and value from within a subroutine:

サブルーチン内からオプション名と値にアクセスする方法の例を次に示します。 (TBR)

    GetOptions ('opt=i' => \&handler);
    sub handler {
        my ($opt_name, $opt_value) = @_;
        print("Option name is $opt_name and value is $opt_value\n");
    }

Options with multiple names

Often it is user friendly to supply alternate mnemonic names for options. For example --height could be an alternate name for --length. Alternate names can be included in the option specification, separated by vertical bar | characters. To implement the above example:

多くの場合、オプションの代替ニーモニック名を指定するのはユーザーフレンドリーです。 たとえば、--height--lengthの代替名になります。 代替名はオプション指定に含めることができ、縦棒|文字で区切られます。 前述の例を実装するには、次のようにします。 (TBR)

    GetOptions ('length|height=f' => \$length);

The first name is called the primary name, the other names are called aliases. When using a hash to store options, the key will always be the primary name.

最初の名前はprimarynameと呼ばれ、他の名前はaliasesと呼ばれます。 ハッシュを使用してオプションを格納する場合、キーは常にプライマリ名になります。 (TBR)

Multiple alternate names are possible.

複数の代替名を使用できます。 (TBR)

Case and abbreviations

Without additional configuration, GetOptions() will ignore the case of option names, and allow the options to be abbreviated to uniqueness.

追加の設定がない場合、GetOptions()はオプション名の大文字と小文字を無視し、オプションを一意に短縮することができます。 (TBR)

    GetOptions ('length|height=f' => \$length, "head" => \$head);

This call will allow --l and --L for the length option, but requires a least --hea and --hei for the head and height options.

この呼び出しでは、長さオプションに--l--Lを使用できますが、頭と高さのオプションには少なくとも--hea--heiが必要です。 (TBR)

Summary of Option Specifications

Each option specifier consists of two parts: the name specification and the argument specification.

各オプション指定子は、名前指定と引数指定の2つの部分で構成されます。 (TBR)

The name specification contains the name of the option, optionally followed by a list of alternative names separated by vertical bar characters. The name is made up of alphanumeric characters, hyphens, underscores. If pass_through is disabled, a period is also allowed in option names.

名前の指定には、オプションの名前が含まれ、オプションの後に縦棒文字で区切られた代替名のリストが続く場合があります。 名前は、英数字、ハイフン、下線で構成されます。 pass_throughが無効な場合は、オプション名にピリオドも使用できます。 (TBR)

    length            option name is "length"
    length|size|l     name is "length", aliases are "size" and "l"

The argument specification is optional. If omitted, the option is considered boolean, a value of 1 will be assigned when the option is used on the command line.

引数の指定はオプションです。 省略した場合、オプションはブール値とみなされ、コマンドラインで使用するときに値1が割り当てられます。 (TBR)

The argument specification can be

引数の指定には、次のものを使用できます。 (TBR)

!

The option does not take an argument and may be negated by prefixing it with "no" or "no-". E.g. "foo!" will allow --foo (a value of 1 will be assigned) as well as --nofoo and --no-foo (a value of 0 will be assigned). If the option has aliases, this applies to the aliases as well.

このオプションは引数を取らず、"no"または"no-"を前に付けることで否定できます。 たとえば、"foo!"は、--nofoo--no-foo(値0が割り当てられます)だけでなく、--foo(値1が割り当てられます)も許可します。 オプションにエイリアスがある場合、これはエイリアスにも適用されます。 (TBR)

Using negation on a single letter option when bundling is in effect is pointless and will result in a warning.

バンドルが有効な場合に単一文字オプションに否定を使用しても意味がなく、警告が表示されます。 (TBR)

+

The option does not take an argument and will be incremented by 1 every time it appears on the command line. E.g. "more+", when used with --more --more --more, will increment the value three times, resulting in a value of 3 (provided it was 0 or undefined at first).

このオプションは引数を取らず、コマンドラインに表示されるたびに1ずつ増分されます。 たとえば、"more+"--more --more --moreと一緒に使用すると、値が3倍になります(最初は0または未定義でした)。 (TBR)

The + specifier is ignored if the option destination is not a scalar.

オプションの出力先がスカラーでない場合、+指定子は無視されます。 (TBR)

= type [ desttype ] [ repeat ]

The option requires an argument of the given type. Supported types are:

オプションには、指定したタイプの引数が必要です。 サポートされているタイプは次のとおりです: (TBR)

s

String. An arbitrary sequence of characters. It is valid for the argument to start with - or --.

文字列。 任意の文字列。 引数が-または--で始まる場合に有効です。 (TBR)

i

Integer. An optional leading plus or minus sign, followed by a sequence of digits.

整数型(Integer)の値を指定します。 先頭にプラス記号またはマイナス記号(省略可能)を付け、その後に一連の数字を続けます。 (TBR)

o

Extended integer, Perl style. This can be either an optional leading plus or minus sign, followed by a sequence of digits, or an octal string (a zero, optionally followed by '0', '1', .. '7'), or a hexadecimal string (0x followed by '0' .. '9', 'a' .. 'f', case insensitive), or a binary string (0b followed by a series of '0' and '1').

拡張整数。 Perlスタイル。 先頭にプラス記号またはマイナス記号(省略可能)を付け、その後に一連の数字を続けるか、8進数文字列(0、その後に「0」、「1」、.「7」)、16進数文字列(0xの後に「0」.「9」、「a」.「f」、大文字と小文字は区別されません)、またはバイナリ列(0bの後に一連の「0」と「1」)を指定できます。 (TBR)

f

Real number. For example 3.14, -6.23E24 and so on.

実数。 たとえば、3.14-6.23E24など。 (TBR)

The desttype can be @ or % to specify that the option is list or a hash valued. This is only needed when the destination for the option value is not otherwise specified. It should be omitted when not needed.

desttypeには、@または%を使用して、オプションがリストまたはハッシュ値であることを指定できます。 これは、オプション値の宛先が他に指定されていない場合にのみ必要です。 不要な場合は省略してください。 (TBR)

The repeat specifies the number of values this option takes per occurrence on the command line. It has the format { [ min ] [ , [ max ] ] }.

repeatは、このオプションがコマンドラインで使用する値の数を指定します。 {[min][,[max]]}の形式で指定します。 (TBR)

min denotes the minimal number of arguments. It defaults to 1 for options with = and to 0 for options with :, see below. Note that min overrules the = / : semantics.

minは引数の最小数を表します。 デフォルトは=のオプションでは1、:のオプションでは0です。 以下を参照してください。 min=/:セマンティクスを無効にすることに注意してください。 (TBR)

max denotes the maximum number of arguments. It must be at least min. If max is omitted, but the comma is not, there is no upper bound to the number of argument values taken.

maxは、引数の最大数を表します。 min以上である必要があります。 maxを省略し、でもカンマがでない場合、取得される引数値の数に上限はありません。 (TBR)

: type [ desttype ]

Like =, but designates the argument as optional. If omitted, an empty string will be assigned to string values options, and the value zero to numeric options.

=と似ていますが、引数をオプションとして指定します。 省略した場合、文字列値オプションには空の文字列が割り当てられ、数値オプションには0が割り当てられます。 (TBR)

Note that if a string argument starts with - or --, it will be considered an option on itself.

文字列引数が-または--で始まる場合、それ自体がオプションとみなされることに注意してください。 (TBR)

: number [ desttype ]

Like :i, but if the value is omitted, the number will be assigned.

:iと似ていますが、値を省略するとnumberが割り当てられます。 (TBR)

If the number is octal, hexadecimal or binary, behaves like :o.

numberが8進数、16進数、または2進数の場合、:oのように動作します。 (TBR)

: + [ desttype ]

Like :i, but if the value is omitted, the current value for the option will be incremented.

:iと似ていますが、値を省略すると、オプションの現在の値が増分されます。 (TBR)

Advanced Possibilities

Object oriented interface

Getopt::Long::Parserを参照してください。 (TBR)

Callback object

In version 2.37 the first argument to the callback function was changed from string to object. This was done to make room for extensions and more detailed control. The object stringifies to the option name so this change should not introduce compatibility problems.

バージョン2.37では、コールバック関数の最初の引数がstringからobjectに変更されました。 これは、拡張とより詳細な制御のための領域を確保するために行われました。 オブジェクトはオプション名に文字列化されるため、この変更によって互換性の問題が発生することはありません。 (TBR)

The callback object has the following methods:

コールバックオブジェクトには、次のメソッドがあります。 (TBR)

name

The name of the option, unabbreviated. For an option with multiple names it return the first (canonical) name.

省略されていないオプションの名前。 複数の名前を持つオプションに対しては、最初の(正規の)名前を返します。 (TBR)

given

The name of the option as actually used, unabbreveated.

実際に使用されているオプションの名前(省略なし)。 (TBR)

Thread Safety

Getopt::Long is thread safe when using ithreads as of Perl 5.8. It is not thread safe when using the older (experimental and now obsolete) threads implementation that was added to Perl 5.005.

Perl 5.8の時点でithreadを使用する場合、Getopt::Longはスレッドセーフです。 Perl 5.005に追加された古い(実験的で現在は廃止された)スレッド実装を使用する場合、Getopt::Longはスレッドセーフではありません。 (TBR)

Documentation and help texts

Getopt::Long encourages the use of Pod::Usage to produce help messages. For example:

Getopt::Longでは、Pod::Usageを使用してヘルプメッセージを生成することをお勧めします。 次に例を示します。 (TBR)

    use Getopt::Long;
    use Pod::Usage;

    my $man = 0;
    my $help = 0;

    GetOptions('help|?' => \$help, man => \$man) or pod2usage(2);
    pod2usage(1) if $help;
    pod2usage(-exitval => 0, -verbose => 2) if $man;

    __END__

    =head1 NAME

    sample - Using Getopt::Long and Pod::Usage

    =head1 SYNOPSIS

    sample [options] [file ...]

     Options:
       -help            brief help message
       -man             full documentation

    =head1 OPTIONS

    =over 8

    =item B<-help>

    Print a brief help message and exits.

    =item B<-man>

    Prints the manual page and exits.

    =back

    =head1 DESCRIPTION

    B<This program> will read the given input file(s) and do something
    useful with the contents thereof.

    =cut

See Pod::Usage for details.

詳細は、Pod::Usageを参照してください。 (TBR)

Parsing options from an arbitrary array

By default, GetOptions parses the options that are present in the global array @ARGV. A special entry GetOptionsFromArray can be used to parse options from an arbitrary array.

デフォルトでは、GetOptionsはグローバル配列@ARGVに存在するオプションを解析します。 特別なエントリGetOptionsFromArrayは任意の配列からオプションを解析するために使用できます。 (TBR)

    use Getopt::Long qw(GetOptionsFromArray);
    $ret = GetOptionsFromArray(\@myopts, ...);

When used like this, options and their possible values are removed from @myopts, the global @ARGV is not touched at all.

このように使用すると、オプションとそれらの可能な値は@myoptsから削除され、グローバル@ARGVは全く変更されません。 (TBR)

The following two calls behave identically:

次の2つの呼び出しは同じように動作します。 (TBR)

    $ret = GetOptions( ... );
    $ret = GetOptionsFromArray(\@ARGV, ... );

This also means that a first argument hash reference now becomes the second argument:

これは、最初の引数のハッシュ参照が2番目の引数になることも意味します。 (TBR)

    $ret = GetOptions(\%opts, ... );
    $ret = GetOptionsFromArray(\@ARGV, \%opts, ... );

Parsing options from an arbitrary string

A special entry GetOptionsFromString can be used to parse options from an arbitrary string.

特殊なエントリGetOptionsFromStringを使用して、任意の文字列からオプションを解析できます。 (TBR)

    use Getopt::Long qw(GetOptionsFromString);
    $ret = GetOptionsFromString($string, ...);

The contents of the string are split into arguments using a call to Text::ParseWords::shellwords. As with GetOptionsFromArray, the global @ARGV is not touched.

文字列の内容は、Text::ParseWords::shellwordsの呼び出しを使用して引数に分割されます。 GetOptionsFromArrayと同様に、グローバル@ARGVは変更されません。 (TBR)

It is possible that, upon completion, not all arguments in the string have been processed. GetOptionsFromString will, when called in list context, return both the return status and an array reference to any remaining arguments:

完了時に、文字列内のすべての引数が処理されていない可能性があります。 GetOptionsFromStringは、リストコンテキストで呼び出されると、リターンステータスと、残りの引数への配列参照の両方を返します。 (TBR)

    ($ret, $args) = GetOptionsFromString($string, ... );

If any arguments remain, and GetOptionsFromString was not called in list context, a message will be given and GetOptionsFromString will return failure.

引数が残っていて、リストコンテキストでGetOptionsFromStringが呼び出されなかった場合、メッセージが表示され、GetOptionsFromStringは失敗を返します。 (TBR)

As with GetOptionsFromArray, a first argument hash reference now becomes the second argument. See the next section.

GetOptionsFromArrayと同様に、最初の引数のハッシュ参照が2番目の引数になるようになりました。 次のセクションを参照してください。 (TBR)

Storing options values in a hash

Sometimes, for example when there are a lot of options, having a separate variable for each of them can be cumbersome. GetOptions() supports, as an alternative mechanism, storing options values in a hash.

場合によっては、たとえばオプションが多数ある場合、それぞれに個別の変数を使用するのが面倒になることがあります。 GetOptions()は、代替メカニズムとして、オプション値をハッシュに格納することをサポートします。 (TBR)

To obtain this, a reference to a hash must be passed as the first argument to GetOptions(). For each option that is specified on the command line, the option value will be stored in the hash with the option name as key. Options that are not actually used on the command line will not be put in the hash, on other words, exists($h{option}) (or defined()) can be used to test if an option was used. The drawback is that warnings will be issued if the program runs under use strict and uses $h{option} without testing with exists() or defined() first.

これを取得するには、ハッシュへの参照を最初の引数としてGetOptions()に渡す必要があります。 コマンドラインで指定された各オプションの値は、キーとしてオプション名とともにハッシュに格納されます。 コマンドラインで実際に使用されないオプションはハッシュに格納されません。 つまり、exists($h{option})(またはdefined())を使用して、オプションが使用されたかどうかをテストできます。 欠点は、プログラムがuse strictの下で実行され、最初にexists()またはdefined()を使用してテストせずに$h{option}を使用する場合に警告が発行されることです。 (TBR)

    my %h = ();
    GetOptions (\%h, 'length=i');       # will store in $h{length}

For options that take list or hash values, it is necessary to indicate this by appending an @ or % sign after the type:

リストまたはハッシュ値をとるオプションでは、型の後に@または%記号を追加することでこれを示す必要があります。 (TBR)

    GetOptions (\%h, 'colours=s@');     # will push to @{$h{colours}}

To make things more complicated, the hash may contain references to the actual destinations, for example:

さらに複雑にするために、ハッシュには実際の宛先への参照が含まれる場合があります。 次に例を示します。 (TBR)

    my $len = 0;
    my %h = ('length' => \$len);
    GetOptions (\%h, 'length=i');       # will store in $len

This example is fully equivalent with:

この例は、次と完全に同等です。 (TBR)

    my $len = 0;
    GetOptions ('length=i' => \$len);   # will store in $len

Any mixture is possible. For example, the most frequently used options could be stored in variables while all other options get stored in the hash:

任意の組み合わせが可能です。 たとえば、最も頻繁に使用されるオプションは変数に格納され、他のすべてのオプションはハッシュに格納されます。 (TBR)

    my $verbose = 0;                    # frequently referred
    my $debug = 0;                      # frequently referred
    my %h = ('verbose' => \$verbose, 'debug' => \$debug);
    GetOptions (\%h, 'verbose', 'debug', 'filter', 'size=i');
    if ( $verbose ) { ... }
    if ( exists $h{filter} ) { ... option 'filter' was specified ... }

Bundling

With bundling it is possible to set several single-character options at once. For example if a, v and x are all valid options,

バンドルを使用すると、複数の単一文字オプションを一度に設定できます。 たとえば、av、およびxがすべて有効なオプションである場合 (TBR)

    -vax

will set all three.

は3つすべてを設定します。 (TBR)

Getopt::Long supports three styles of bundling. To enable bundling, a call to Getopt::Long::Configure is required.

Getopt::Longは、3つのバンドルスタイルをサポートしています。 バンドルを有効にするには、Getopt::Long::Configureを呼び出す必要があります。 (TBR)

The simplest style of bundling can be enabled with:

最も単純なスタイルのバンドルは、次のようにして有効にできます。 (TBR)

    Getopt::Long::Configure ("bundling");

Configured this way, single-character options can be bundled but long options (and any of their auto-abbreviated shortened forms) must always start with a double dash -- to avoid ambiguity. For example, when vax, a, v and x are all valid options,

このように設定すると、1文字のオプションを束ねることができますが、長いオプション(および自動省略の短縮形)mustは、あいまいさを避けるために常にダブルダッシュ--で始まります。 たとえば、vaxav、およびxがすべて有効なオプションである場合 (TBR)

    -vax

will set a, v and x, but

a,v,xを設定するが (TBR)

    --vax

will set vax.

vaxを設定する。 (TBR)

The second style of bundling lifts this restriction. It can be enabled with:

2番目のバンドルスタイルでは、この制限が解除されます。 これは次の方法で有効にできます。 (TBR)

    Getopt::Long::Configure ("bundling_override");

Now, -vax will set the option vax.

ここで、-vaxはオプションvaxをセットする。 (TBR)

In all of the above cases, option values may be inserted in the bundle. For example:

上記のすべての場合において、オプション値をバンドルに挿入できます。 例: (TBR)

    -h24w80

is equivalent to

と同じです。 (TBR)

    -h 24 -w 80

A third style of bundling allows only values to be bundled with options. It can be enabled with:

バンドルの3番目のスタイルでは、値のみをオプションとバンドルできます。 これは次の方法で有効にできます。 (TBR)

    Getopt::Long::Configure ("bundling_values");

Now, -h24 will set the option h to 24, but option bundles like -vxa and -h24w80 are flagged as errors.

現在、-h24はオプションh24に設定しますが、-vxa-h24w80のようなオプションバンドルはエラーとしてフラグが立てられます。 (TBR)

Enabling bundling_values will disable the other two styles of bundling.

bundling_valuesを有効にすると、他の2つのバンドル方式が無効になります。 (TBR)

When configured for bundling, single-character options are matched case sensitive while long options are matched case insensitive. To have the single-character options matched case insensitive as well, use:

バンドル用に設定されている場合、1文字のオプションは大文字と小文字を区別し、長いオプションは大文字と小文字を区別しません。 1文字のオプションも大文字と小文字を区別しないようにするには、次のように指定します。 (TBR)

    Getopt::Long::Configure ("bundling", "ignorecase_always");

It goes without saying that bundling can be quite confusing.

言うまでもなく、バンドルは非常に混乱を招く可能性があります。 (TBR)

The lonesome dash

Normally, a lone dash - on the command line will not be considered an option. Option processing will terminate (unless "permute" is configured) and the dash will be left in @ARGV.

通常、コマンドラインの単独のダッシュ-はオプションとはみなされません。 オプション処理は終了し("permute"が設定されていない限り)、ダッシュは@ARGVのままになります。 (TBR)

It is possible to get special treatment for a lone dash. This can be achieved by adding an option specification with an empty name, for example:

単発の場合は特別な治療を受けることができます。 これは、空の名前を持つオプション仕様を追加することで実現できます。 例: (TBR)

    GetOptions ('' => \$stdio);

A lone dash on the command line will now be a legal option, and using it will set variable $stdio.

コマンドラインの一文字のダッシュは正しいオプションとなり、これを使用すると変数$stdioが設定されます。 (TBR)

Argument callback

A special option 'name' <> can be used to designate a subroutine to handle non-option arguments. When GetOptions() encounters an argument that does not look like an option, it will immediately call this subroutine and passes it one parameter: the argument name.

特殊なオプション'name'<<>>を使用して、オプション以外の引数を処理するサブルーチンを指定できます。 GetOptions()は、オプションのように見えない引数を検出すると、すぐにこのサブルーチンを呼び出し、引数名という1つのパラメータを渡します。 (TBR)

For example:

次に例を示します。 (TBR)

    my $width = 80;
    sub process { ... }
    GetOptions ('width=i' => \$width, '<>' => \&process);

When applied to the following command line:

次のコマンドラインに適用した場合: (TBR)

    arg1 --width=72 arg2 --width=60 arg3

This will call process("arg1") while $width is 80, process("arg2") while $width is 72, and process("arg3") while $width is 60.

これにより、$width80の場合はprocess("arg1")$width72の場合はprocess("arg2")$width60の場合はprocess("arg3")が呼び出されます。 (TBR)

This feature requires configuration option permute, see section "Configuring Getopt::Long".

この機能には設定オプションpermuteが必要です。 セクションGetopt::Longの設定を参照してください。 (TBR)

Configuring Getopt::Long

Getopt::Long can be configured by calling subroutine Getopt::Long::Configure(). This subroutine takes a list of quoted strings, each specifying a configuration option to be enabled, e.g. ignore_case. To disable, prefix with no or no_, e.g. no_ignore_case. Case does not matter. Multiple calls to Configure() are possible.

Getopt::Longは、サブルーチンGetopt::Long::Configure()を呼び出すことで設定できます。 このサブルーチンは、引用符で囲まれた文字列のリストを受け取り、それぞれが有効にする設定オプションを指定します。 たとえば、ignore_caseです。 無効にするには、noまたはno_でプレフィックスします。 たとえば、no_ignore_caseです。 大文字と小文字は区別されません。 Configure()は複数回呼び出すことができます。 (TBR)

Alternatively, as of version 2.24, the configuration options may be passed together with the use statement:

あるいは、バージョン2.24では、設定オプションをuse文と一緒に渡すこともできます。 (TBR)

    use Getopt::Long qw(:config no_ignore_case bundling);

The following options are available:

次のオプションを使用できます。 (TBR)

default

This option causes all configuration options to be reset to their default values.

このオプションを使用すると、すべてのコンフィギュレーションオプションがデフォルト値にリセットされます。 (TBR)

posix_default

This option causes all configuration options to be reset to their default values as if the environment variable POSIXLY_CORRECT had been set.

このオプションは、環境変数POSIXLY_CORRECTが設定されているかのように、すべての構成オプションをデフォルト値にリセットします。 (TBR)

auto_abbrev

Allow option names to be abbreviated to uniqueness. Default is enabled unless environment variable POSIXLY_CORRECT has been set, in which case auto_abbrev is disabled.

オプション名を一意に短縮できるようにします。 環境変数POSIXLY_CORRECTが設定されていない限り、デフォルトは有効です。 環境変数POSIXLY_CORRECTが設定されている場合、auto_abbrevは無効になります。 (TBR)

getopt_compat

Allow + to start options. Default is enabled unless environment variable POSIXLY_CORRECT has been set, in which case getopt_compat is disabled.

+でオプションを開始できるようにします。 環境変数POSIXLY_CORRECTが設定されていない限り、デフォルトは有効です。 環境変数POSIXLY_CORRECTが設定されている場合、getopt_compatは無効になります。 (TBR)

gnu_compat

gnu_compat controls whether --opt= is allowed, and what it should do. Without gnu_compat, --opt= gives an error. With gnu_compat, --opt= will give option opt an empty value. This is the way GNU getopt_long() does it.

gnu_compatは、--opt=を許可するかどうか、そして何をすべきかを制御します。 gnu_compatがなければ、--opt=はエラーになります。 gnu_compatがあれば、--opt=はオプションoptに空の値を与えます。 これはGNU getopt_long()が行う方法です。 (TBR)

Note that for options with optional arguments, --opt value is still accepted, even though GNU getopt_long() requires writing --opt=value in this case.

GNUのgetopt_long()では--opt=valueを記述する必要がありますが、オプション引数を持つオプションでは、--opt valueも受け入れられることに注意してください。 (TBR)

gnu_getopt

This is a short way of setting gnu_compat bundling permute no_getopt_compat. With gnu_getopt, command line handling should be reasonably compatible with GNU getopt_long().

これはgnu_compatbundlingpermuteno_getopt_compatを設定する簡単な方法です。 gnu_getoptでは、コマンドライン処理はGNU getopt_long()と適度に互換性があるはずです。 (TBR)

require_order

Whether command line arguments are allowed to be mixed with options. Default is disabled unless environment variable POSIXLY_CORRECT has been set, in which case require_order is enabled.

コマンドライン引数とオプションを混在させることができるかどうか。 環境変数POSIXLY_CORRECTが設定されていない限り、デフォルトは無効です。 環境変数POSIXLY_CORRECTが設定されている場合は、require_orderが有効になります。 (TBR)

See also permute, which is the opposite of require_order.

require_orderの逆であるpermuteも参照してください。 (TBR)

permute

Whether command line arguments are allowed to be mixed with options. Default is enabled unless environment variable POSIXLY_CORRECT has been set, in which case permute is disabled. Note that permute is the opposite of require_order.

コマンドライン引数をオプションと混在させることができるかどうか。 環境変数POSIXLY_CORRECTが設定されていない限り、デフォルトは有効です。 環境変数POSIXLY_CORRECTが設定されている場合、permuteは無効になります。 permuterequire_orderの逆であることに注意してください。 (TBR)

If permute is enabled, this means that

permuteが有効になっていると (TBR)

    --foo arg1 --bar arg2 arg3

is equivalent to

と同じです。 (TBR)

    --foo --bar arg1 arg2 arg3

If an argument callback routine is specified, @ARGV will always be empty upon successful return of GetOptions() since all options have been processed. The only exception is when -- is used:

引き数コールバックルーチンが指定される場合、@ARGVは、すべてのオプションが処理されているので、GetOptions()が正常に戻されると常に空になります。 唯一の例外は、--が使用される場合です: (TBR)

    --foo arg1 --bar arg2 -- arg3

This will call the callback routine for arg1 and arg2, and then terminate GetOptions() leaving "arg3" in @ARGV.

これはarg1とarg2のためのコールバックルーチンを呼び出し、"arg3"@ARGVに残してGetOptions()を終了します。 (TBR)

If require_order is enabled, options processing terminates when the first non-option is encountered.

require_orderが有効になっている場合、オプション処理は、最初の非オプションに遭遇したときに終了します。 (TBR)

    --foo arg1 --bar arg2 arg3

is equivalent to

と同じです。 (TBR)

    --foo -- arg1 --bar arg2 arg3

If pass_through is also enabled, options processing will terminate at the first unrecognized option, or non-option, whichever comes first.

pass_throughも有効になっている場合、オプションの処理は最初の認識されないオプション、またはオプションでないもののどちらか早い方で終了します。 (TBR)

bundling (default: disabled)

Enabling this option will allow single-character options to be bundled. To distinguish bundles from long option names, long options (and any of their auto-abbreviated shortened forms) must be introduced with -- and bundles with -.

このオプションを有効にすると、1文字のオプションをバンドルすることができます。 バンドルを長いオプション名と区別するために、長いオプション(およびそれらの自動省略された短縮形)must--で導入され、バンドルは-で導入されます。 (TBR)

Note that, if you have options a, l and all, and auto_abbrev enabled, possible arguments and option settings are:

オプションal、およびallがあり、auto_abbrevが有効になっている場合、使用できる引数とオプション設定は次のとおりです。 (TBR)

    using argument               sets option(s)
    ------------------------------------------
    -a, --a                      a
    -l, --l                      l
    -al, -la, -ala, -all,...     a, l
    --al, --all                  all

The surprising part is that --a sets option a (due to auto completion), not all.

驚くべき点は、--aがオプションaを設定するのであって(自動補完のため)、allではないことである。 (TBR)

Note: disabling bundling also disables bundling_override.

注意:bundlingを無効にすると、bundling_overrideも無効になります。 (TBR)

bundling_override (default: disabled)

If bundling_override is enabled, bundling is enabled as with bundling but now long option names override option bundles.

bundling_overrideが有効な場合、bundlingと同様にバンドルが有効になりますが、長いオプション名がオプションバンドルを上書きするようになりました。 (TBR)

Note: disabling bundling_override also disables bundling.

注意:bundling_overrideを無効にすると、bundlingも無効になります。 (TBR)

Note: Using option bundling can easily lead to unexpected results, especially when mixing long options and bundles. Caveat emptor.

注:オプションのバンドル化を使用すると、特に長いオプションとバンドルを混在させる場合に、予期しない結果が簡単に発生する可能性があります。 買手側の注意。 (TBR)

ignore_case (default: enabled)

If enabled, case is ignored when matching option names. If, however, bundling is enabled as well, single character options will be treated case-sensitive.

有効にすると、オプション名の照合時に大文字と小文字が無視されます。 ただし、バンドルも有効にすると、1文字のオプションは大文字と小文字が区別されます。 (TBR)

With ignore_case, option specifications for options that only differ in case, e.g., "foo" and "Foo", will be flagged as duplicates.

ignore_caseでは、"foo""Foo"のように大文字と小文字が異なるだけのオプションの指定は、重複としてフラグが立てられます。 (TBR)

Note: disabling ignore_case also disables ignore_case_always.

注意:ignore_caseを無効にすると、ignore_case_alwaysも無効になります。 (TBR)

ignore_case_always (default: disabled)

When bundling is in effect, case is ignored on single-character options also.

バンドルが有効な場合、1文字のオプションでも大文字と小文字は無視されます。 (TBR)

Note: disabling ignore_case_always also disables ignore_case.

注意:ignore_case_alwaysを無効にすると、ignore_caseも無効になります。 (TBR)

auto_version (default:disabled)

Automatically provide support for the --version option if the application did not specify a handler for this option itself.

アプリケーションが--versionオプション自体のハンドラを指定しなかった場合に、このオプションのサポートを自動的に提供します。 (TBR)

Getopt::Long will provide a standard version message that includes the program name, its version (if $main::VERSION is defined), and the versions of Getopt::Long and Perl. The message will be written to standard output and processing will terminate.

Getopt::Longは、プログラム名、そのバージョン($main::VERSIONが定義されている場合)、およびGetopt::LongとPerlのバージョンを含む標準バージョンメッセージを提供します。 メッセージは標準出力に書き込まれ、処理は終了します。 (TBR)

auto_version will be enabled if the calling program explicitly specified a version number higher than 2.32 in the use or require statement.

auto_versionは、呼び出し元のプログラムがuseまたはrequire文で2.32より大きいバージョン番号を明示的に指定した場合に有効になります。 (TBR)

auto_help (default:disabled)

Automatically provide support for the --help and -? options if the application did not specify a handler for this option itself.

アプリケーションが--helpおよび-?オプション自体のハンドラを指定しなかった場合に、このオプションのサポートを自動的に提供します。 (TBR)

Getopt::Long will provide a help message using module Pod::Usage. The message, derived from the SYNOPSIS POD section, will be written to standard output and processing will terminate.

Getopt::Longは、モジュールPod::Usageを使用してヘルプメッセージを提供します。 SYNOPSIS PODセクションから派生したメッセージは標準出力に書き込まれ、処理が終了します。 (TBR)

auto_help will be enabled if the calling program explicitly specified a version number higher than 2.32 in the use or require statement.

auto_helpは、呼び出し元のプログラムがuseまたはrequire文で2.32より大きいバージョン番号を明示的に指定した場合に有効になります。 (TBR)

pass_through (default: disabled)

With pass_through anything that is unknown, ambiguous or supplied with an invalid option will not be flagged as an error. Instead the unknown option(s) will be passed to the catchall <> if present, otherwise through to @ARGV. This makes it possible to write wrapper scripts that process only part of the user supplied command line arguments, and pass the remaining options to some other program.

pass_throughでは、不明なもの、あいまいなもの、無効なオプションが指定されたものはエラーとしてフラグ付けされません。 代わりに、不明なオプションはキャッチオール<<>>があればそれに渡され、なければ@ARGVに渡されます。 これにより、ユーザが指定したコマンドライン引数の一部だけを処理し、残りのオプションを他のプログラムに渡すラッパースクリプトを書くことができます。 (TBR)

If require_order is enabled, options processing will terminate at the first unrecognized option, or non-option, whichever comes first and all remaining arguments are passed to @ARGV instead of the catchall <> if present. However, if permute is enabled instead, results can become confusing.

require_orderが有効な場合、オプション処理は最初の認識できないオプション、またはオプションでないもののうち最初に来たもので終了し、全ての残りの引数は<<>の代わりに@ARGVに渡されます。 しかし、もしpermuteが有効な場合、結果が混乱するかもしれません。 (TBR)

Note that the options terminator (default --), if present, will also be passed through in @ARGV.

もし存在するなら、オプション終端文字(デフォルト--)は@ARGVでもパススルーされることに注意してください。 (TBR)

prefix

The string that starts options. If a constant string is not sufficient, see prefix_pattern.

オプションを開始する文字列。 定数文字列が十分でない場合は、prefix_patternを参照してください。 (TBR)

prefix_pattern

A Perl pattern that identifies the strings that introduce options. Default is --|-|\+ unless environment variable POSIXLY_CORRECT has been set, in which case it is --|-.

オプションを導入する文字列を識別するPerlパターン。 環境変数POSIXLY_CORRECTが設定されていない限り、デフォルトは--|-|\+です。 環境変数POSIXLY_CORRECTが設定されている場合は、--|-です。 (TBR)

long_prefix_pattern

A Perl pattern that allows the disambiguation of long and short prefixes. Default is --.

長い接頭部と短い接頭部を区別できるPerlパターン。 デフォルトは--です。 (TBR)

Typically you only need to set this if you are using nonstandard prefixes and want some or all of them to have the same semantics as '--' does under normal circumstances.

通常、これを設定する必要があるのは、非標準のプレフィックスを使用していて、その一部またはすべてを通常の状況での'--'と同じセマンティクスにしたい場合だけです。 (TBR)

For example, setting prefix_pattern to --|-|\+|\/ and long_prefix_pattern to --|\/ would add Win32 style argument handling.

たとえば、prefix_patternを--|-|\+|\/に設定し、long_prefix_patternを--|\/に設定すると、Win32スタイルの引数処理が追加されます。 (TBR)

debug (default: disabled)

Enable debugging output.

デバッグ出力を有効にします。 (TBR)

Exportable Methods

VersionMessage

This subroutine provides a standard version message. Its argument can be:

このサブルーチンは、標準バージョンのメッセージを提供します。 引数は次のいずれかです。 (TBR)

  • A string containing the text of a message to print before printing the standard message.

    標準メッセージを表示するbeforeを出力するメッセージのテキストを含む文字列。 (TBR)

  • A numeric value corresponding to the desired exit status.

    目的の終了ステータスに対応する数値。 (TBR)

  • A reference to a hash.

    ハッシュへの参照。 (TBR)

If more than one argument is given then the entire argument list is assumed to be a hash. If a hash is supplied (either as a reference or as a list) it should contain one or more elements with the following keys:

複数の引数が指定された場合、引数リスト全体がハッシュとみなされます。 ハッシュが(参照またはリストとして)指定された場合、次のキーを持つ1つ以上の要素が含まれている必要があります。 (TBR)

-message
-msg

The text of a message to print immediately prior to printing the program's usage message.

プログラムの使用状況メッセージを表示する直前に表示するメッセージのテキストです。 (TBR)

-exitval

The desired exit status to pass to the exit() function. This should be an integer, or else the string "NOEXIT" to indicate that control should simply be returned without terminating the invoking process.

exit()関数に渡す終了ステータス。 整数値、または文字列"NOEXIT"を指定します。 文字列を指定すると、呼び出し元のプロセスを終了せずに制御を返すことを示します。 (TBR)

-output

A reference to a filehandle, or the pathname of a file to which the usage message should be written. The default is \*STDERR unless the exit value is less than 2 (in which case the default is \*STDOUT).

ファイルハンドルへの参照、または使用状況メッセージの書き込み先となるファイルのパス名。 終了値が2より小さい場合(この場合のデフォルトは\*STDOUT)を除き、デフォルトは\*STDERRである。 (TBR)

You cannot tie this routine directly to an option, e.g.:

このルーチンを直接オプションに関連付けることはできません。 例: (TBR)

    GetOptions("version" => \&VersionMessage);

Use this instead:

代わりにこれを使用します。 (TBR)

    GetOptions("version" => sub { VersionMessage() });
HelpMessage

This subroutine produces a standard help message, derived from the program's POD section SYNOPSIS using Pod::Usage. It takes the same arguments as VersionMessage(). In particular, you cannot tie it directly to an option, e.g.:

このサブルーチンは、Pod::Usageを使用して、プログラムのPODセクションのSYNOPSISから派生した標準のヘルプメッセージを生成します。 VersionMessage()と同じ引数を取ります。 特に、次のようにオプションに直接結び付けることはできません。 (TBR)

    GetOptions("help" => \&HelpMessage);

Use this instead:

代わりにこれを使用します。 (TBR)

    GetOptions("help" => sub { HelpMessage() });

Return values and Errors

Configuration errors and errors in the option definitions are signalled using die() and will terminate the calling program unless the call to Getopt::Long::GetOptions() was embedded in eval { ... }, or die() was trapped using $SIG{__DIE__}.

設定エラーとオプション定義のエラーはdie()を使用して通知され、Getopt::Long::GetOptions()の呼び出しがeval{.}に埋め込まれているか、die()が$SIG{__DIE__}を使用してトラップされていない限り、呼び出し元のプログラムを終了します。 (TBR)

GetOptions returns true to indicate success. It returns false when the function detected one or more errors during option parsing. These errors are signalled using warn() and can be trapped with $SIG{__WARN__}.

GetOptionsは、成功した場合にtrueを返します。 関数がオプションの解析中に1つ以上のエラーを検出した場合はfalseを返します。 これらのエラーはwarn()を使用して通知され、$SIG{__WARN__}でトラップできます。 (TBR)

Legacy

The earliest development of newgetopt.pl started in 1990, with Perl version 4. As a result, its development, and the development of Getopt::Long, has gone through several stages. Since backward compatibility has always been extremely important, the current version of Getopt::Long still supports a lot of constructs that nowadays are no longer necessary or otherwise unwanted. This section describes briefly some of these 'features'.

newgetopt.plの最も初期の開発は、1990年にPerlバージョン4で始まりました。 その結果、その開発とGetopt::Longの開発は、いくつかの段階を経てきました。 下位互換性は常に非常に重要であったため、現在のバージョンのGetopt::Longは、現在では不要になった、あるいは望ましくない多くの構成体をサポートしています。 このセクションでは、これらの「機能」のいくつかについて簡単に説明します。 (TBR)

Default destinations

When no destination is specified for an option, GetOptions will store the resultant value in a global variable named opt_XXX, where XXX is the primary name of this option. When a program executes under use strict (recommended), these variables must be pre-declared with our().

オプションに出力先が指定されていない場合、GetOptionsは、結果の値をopt_XXXという名前のグローバル変数に格納します。 XXXは、このオプションのプライマリ名です。 プログラムをuse strict(推奨)で実行する場合は、これらの変数を()で事前に宣言しておく必要があります。 (TBR)

    our $opt_length = 0;
    GetOptions ('length=i');    # will store in $opt_length

To yield a usable Perl variable, characters that are not part of the syntax for variables are translated to underscores. For example, --fpp-struct-return will set the variable $opt_fpp_struct_return. Note that this variable resides in the namespace of the calling program, not necessarily main. For example:

使用可能なPerl変数を生成するために、変数の構文の一部ではない文字はアンダースコアに変換されます。 たとえば、--fpp-struct-returnは、変数$opt_fpp_struct_returnを設定します。 この変数は、必ずしもmainではなく、呼び出し元プログラムのネームスペースに存在することに注意してください。 例: (TBR)

    GetOptions ("size=i", "sizes=i@");

with command line "-size 10 -sizes 24 -sizes 48" will perform the equivalent of the assignments

コマンド行に"-size 10-sizes 24-sizes 48"と指定すると (TBR)

    $opt_size = 10;
    @opt_sizes = (24, 48);

Alternative option starters

A string of alternative option starter characters may be passed as the first argument (or the first argument after a leading hash reference argument).

最初の引数(もしくは、先行するハッシュ参照引数の後の最初の引数)として、複数選択可能なオプション開始文字の文字列を渡すことができます。 (TBR)

    my $len = 0;
    GetOptions ('/', 'length=i' => $len);

Now the command line may look like:

コマンドラインは次のようになります。 (TBR)

    /length 24 -- arg

Note that to terminate options processing still requires a double dash --.

オプション処理を終了するには、依然としてダブルダッシュ--が必要であることに注意してください。 (TBR)

GetOptions() will not interpret a leading "<>" as option starters if the next argument is a reference. To force "<" and ">" as option starters, use "><". Confusing? Well, using a starter argument is strongly deprecated anyway.

GetOptions()は、次の引数が参照の場合、先頭の<"<">>をオプションスターターとして解釈しません。 <"<" >と<" ">>をオプションスターターとして強制するには、<" <" >>を使用してください。 混乱しますか?まあ、スターター引数を使用することは強く推奨されません。 (TBR)

Configuration variables

Previous versions of Getopt::Long used variables for the purpose of configuring. Although manipulating these variables still work, it is strongly encouraged to use the Configure routine that was introduced in version 2.17. Besides, it is much easier.

以前のバージョンのGetopt::Longでは、設定のために変数を使用していました。 これらの変数を操作することはできますが、バージョン2.17で導入されたConfigureルーチンを使用することを強くお勧めします。 しかも、はるかに簡単です。 (TBR)

Tips and Techniques

Pushing multiple values in a hash option

Sometimes you want to combine the best of hashes and arrays. For example, the command line:

場合によっては、ハッシュと配列の最良の部分を組み合わせたい場合があります。 たとえば、コマンドラインは次のとおりです: (TBR)

  --list add=first --list add=second --list add=third

where each successive 'list add' option will push the value of add into array ref $list->{'add'}. The result would be like

ここで、それぞれの連続した'list add'オプションは、addの値を配列ref$list->{'add'}にプッシュします。 結果は次のようになります。 (TBR)

  $list->{add} = [qw(first second third)];

This can be accomplished with a destination routine:

これは、宛先ルーチンを使用して行うことができます。 (TBR)

  GetOptions('list=s%' =>
               sub { push(@{$list{$_[1]}}, $_[2]) });

Troubleshooting

GetOptions does not return a false result when an option is not supplied

That's why they're called 'options'.

それが「オプション」と呼ばれる理由です。 (TBR)

GetOptions does not split the command line correctly

The command line is not split by GetOptions, but by the command line interpreter (CLI). On Unix, this is the shell. On Windows, it is COMMAND.COM or CMD.EXE. Other operating systems have other CLIs.

コマンドラインは、GetOptionsではなく、コマンドラインインタープリタ(CLI)によって分割されます。 Unixでは、これはシェルです。 WindowsではCOMMAND.COMまたはCMD.EXEです。 他のオペレーティングシステムには他のCLIがあります。 (TBR)

It is important to know that these CLIs may behave different when the command line contains special characters, in particular quotes or backslashes. For example, with Unix shells you can use single quotes (') and double quotes (") to group words together. The following alternatives are equivalent on Unix:

コマンドラインに特殊文字(特に引用符やバックスラッシュ)が含まれている場合、これらのCLIの動作が異なる場合があることに注意してください。 たとえば、Unixシェルでは、一重引用符(')と二重引用符(")を使用して単語をグループ化できます。 次の選択肢は、Unixでも同じです。 (TBR)

    "two words"
    'two words'
    two\ words

In case of doubt, insert the following statement in front of your Perl program:

疑問がある場合は、Perlプログラムの前に次のステートメントを挿入してください。 (TBR)

    print STDERR (join("|",@ARGV),"\n");

to verify how your CLI passes the arguments to the program.

CLIがどのように引数をプログラムに渡すかを確認します。 (TBR)

Undefined subroutine &main::GetOptions called

Are you running Windows, and did you write

あなたはWindowsを使っていますか? (TBR)

    use GetOpt::Long;

(note the capital 'O')?

(大文字の「O」に注意)? (TBR)

How do I put a "-?" option into a Getopt::Long?

You can only obtain this using an alias, and Getopt::Long of at least version 2.13.

これを取得するには、エイリアスとバージョン2.13以降のGetopt::Longを使用する必要があります。 (TBR)

    use Getopt::Long;
    GetOptions ("help|?");    # -help and -? will both set $opt_help

Other characters that can't appear in Perl identifiers are also supported in aliases with Getopt::Long of at version 2.39. Note that the characters !, |, +, =, and : can only appear as the first (or only) character of an alias.

バージョン2.39のGetopt::Longのエイリアスでは、Perl識別子に表示できないその他の文字もサポートされています。 !|+=、および:の文字は、エイリアスの最初(または唯一)の文字としてのみ表示できることに注意してください。 (TBR)

As of version 2.32 Getopt::Long provides auto-help, a quick and easy way to add the options --help and -? to your program, and handle them.

バージョン2.32では、Getopt::Longは自動ヘルプを提供しています。 これは、--helpと--?のオプションをプログラムに追加し、それらを処理するための迅速で簡単な方法です。 (TBR)

See auto_help in section "Configuring Getopt::Long".

Getopt::Longの設定の節のauto_helpを参照してください。 (TBR)

作者

Johan Vromans <jvromans@squirrel.nl>

COPYRIGHT AND DISCLAIMER

This program is Copyright 1990,2015,2023 by Johan Vromans. This program is free software; you can redistribute it and/or modify it under the terms of the Perl Artistic License or the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

If you do not have a copy of the GNU General Public License write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.