constant-1.17 > constant

名前

constant - Perl pragma to declare constants

constant - 定数を宣言するための Perl プラグマ

概要

    use constant PI    => 4 * atan2(1, 1);
    use constant DEBUG => 0;

    print "Pi equals ", PI, "...\n" if DEBUG;

    use constant {
        SEC   => 0,
        MIN   => 1,
        HOUR  => 2,
        MDAY  => 3,
        MON   => 4,
        YEAR  => 5,
        WDAY  => 6,
        YDAY  => 7,
        ISDST => 8,
    };

    use constant WEEKDAYS => qw(
        Sunday Monday Tuesday Wednesday Thursday Friday Saturday
    );

    print "Today is ", (WEEKDAYS)[ (localtime)[WDAY] ], ".\n";

説明

This pragma allows you to declare constants at compile-time.

このプラグマは、コンパイル時に定数を宣言できるようにします。

When you declare a constant such as PI using the method shown above, each machine your script runs upon can have as many digits of accuracy as it can use. Also, your program will be easier to read, more likely to be maintained (and maintained correctly), and far less likely to send a space probe to the wrong planet because nobody noticed the one equation in which you wrote 3.14195.

上述の PI のようにメソッドを使った定数を宣言すると、マシン毎に 利用可能なだけの精度でスクリプトを実行します。 さらに、プログラムが読みやすくなり、それどころか保守しやすく (そして正しく保守しやすく)なり、3.14195 と書いた一つの方程式に 誰も気付かなかったために宇宙探査機を間違った星に送り込む可能性が 遥かに小さくなります。

When a constant is used in an expression, Perl replaces it with its value at compile time, and may then optimize the expression further. In particular, any code in an if (CONSTANT) block will be optimized away if the constant is false.

定数を式で使ったとき、Perl はこれをコンパイル時に値に置き換え、それから さらに式を最適化します。 特に、if (CONSTANT) ブロックにあるコードは、定数が偽の時には最適化されて なくなります。

注意

As with all use directives, defining a constant happens at compile time. Thus, it's probably not correct to put a constant declaration inside of a conditional statement (like if ($foo) { use constant ... }).

全ての use 指示子と同様、定数の定義はコンパイル時に行われます。 従って、(if ($foo) { use constant ... } のように) 条件文の内側で定数宣言を 行うのはおそらく間違っています。

Constants defined using this module cannot be interpolated into strings like variables. However, concatenation works just fine:

このモジュールを使って定義された定数は変数のように文字列に展開されません。 しかし、結合はうまく動きます:

    print "Pi equals PI...\n";        # WRONG: does not expand "PI"
    print "Pi equals ".PI."...\n";    # right

Even though a reference may be declared as a constant, the reference may point to data which may be changed, as this code shows.

リファレンスを定数として宣言することはできますが、以下のコードが示すように リファレンスは変更されるデータを指しているかもしれません。

    use constant ARRAY => [ 1,2,3,4 ];
    print ARRAY->[1];
    ARRAY->[1] = " be changed";
    print ARRAY->[1];

Dereferencing constant references incorrectly (such as using an array subscript on a constant hash reference, or vice versa) will be trapped at compile time.

(定数ハッシュリファレンスに配列添え字を使ったり、その逆のように) 定数リファレンスを間違ってデリファレンスすると、コンパイル時に トラップされます。

Constants belong to the package they are defined in. To refer to a constant defined in another package, specify the full package name, as in Some::Package::CONSTANT. Constants may be exported by modules, and may also be called as either class or instance methods, that is, as Some::Package->CONSTANT or as $obj->CONSTANT where $obj is an instance of Some::Package. Subclasses may define their own constants to override those in their base class.

定数は定義されたパッケージに属します。 他のパッケージで定義された定数を参照するには、 Some::Package::CONSTANT のように完全なパッケージ名を指定します。 定数はモジュールによってエクスポートすることができ、またクラスメソッド またはインスタンスメソッドとして呼び出すこともできます; $objSome::Package のインスタンスのときに Some::Package->CONSTANT$obj->CONSTANT のようにできます。 サブクラスは基底クラスをオーバーライドして独自の定数を定義できます。

The use of all caps for constant names is merely a convention, although it is recommended in order to make constants stand out and to help avoid collisions with other barewords, keywords, and subroutine names. Constant names must begin with a letter or underscore. Names beginning with a double underscore are reserved. Some poor choices for names will generate warnings, if warnings are enabled at compile time.

定数名に全て大文字を使うのは単に慣習ですが、定数を目立つようにして 他の裸の単語、キーワード、サブルーチン名との衝突を避けることを助けるために、 そのようにすることを勧めます。 定数名は英字または下線で始まらなければなりません。 下線二つで始まる名前は予約されています。 警告がコンパイル時に有効になっているなら、間違った名前を選択すると 警告が生成されます。

リスト定数

Constants may be lists of more (or less) than one value. A constant with no values evaluates to undef in scalar context. Note that constants with more than one value do not return their last value in scalar context as one might expect. They currently return the number of values, but this may change in the future. Do not use constants with multiple values in scalar context.

定数は一つより多い(または少ない)値のリストを指定できます。 値のない定数はスカラコンテキストでは undef と評価されます。 複数の値を持つ定数は、想定されるようにスカラコンテキストで最後の値を 返す わけではない ことに注意してください。 これらは現在のところ値の数を返しますが、 これは将来変更されるかもしれません。 複数の値を持つ定数はスカラコンテキストで使わないでください。

NOTE: This implies that the expression defining the value of a constant is evaluated in list context. This may produce surprises:

注意: これは定数の値をリストコンテキストで評価された値を定義する 式です。 これは驚きを呼ぶかもしれません:

    use constant TIMESTAMP => localtime;                # WRONG!
    use constant TIMESTAMP => scalar localtime;         # right

The first line above defines TIMESTAMP as a 9-element list, as returned by localtime() in list context. To set it to the string returned by localtime() in scalar context, an explicit scalar keyword is required.

上述の 1 番目の行は、TIMESTAMP をリストコンテキストで localtime() から 返される 9 要素リストとして定義します。 スカラコンテキストで localtime() から返される文字列にするには、明示的な scalar キーワードが必要です。

List constants are lists, not arrays. To index or slice them, they must be placed in parentheses.

リスト定数は配列ではなくリストです。 インデックスやスライスを使うには、かっこの中に書かなければなりません。

    my @workdays = WEEKDAYS[1 .. 5];            # WRONG!
    my @workdays = (WEEKDAYS)[1 .. 5];          # right

一度に複数の定数を定義する

Instead of writing multiple use constant statements, you may define multiple constants in a single statement by giving, instead of the constant name, a reference to a hash where the keys are the names of the constants to be defined. Obviously, all constants defined using this method must have a single value.

use constant 文を複数回書く代わりに、一つの文で複数の定数を定義できます; 定数名の代わりに、キーが定数名であるハッシュへのリファレンスを渡します。 明らかに、この手法を使って定義された定数は単一の値を持たなければなりません。

    use constant {
        FOO => "A single value",
        BAR => "This", "won't", "work!",        # Error!
    };

This is a fundamental limitation of the way hashes are constructed in Perl. The error messages produced when this happens will often be quite cryptic -- in the worst case there may be none at all, and you'll only later find that something is broken.

これは Perl でハッシュを構築するための基本的な制限です。 これが起きたときのエラーメッセージはしばしばかなり暗号的です -- 最悪の場合、 全くメッセージは出ず、後で何かが壊れていることに気付くだけです。

When defining multiple constants, you cannot use the values of other constants defined in the same declaration. This is because the calling package doesn't know about any constant within that group until after the use statement is finished.

複数の定数を定義するとき、同じ宣言で定義したその他の定数の値は使えません。 これは呼び出しパッケージは use 文が完了した でしかグループの内側の 定数に関して知ることがないからです。

    use constant {
        BITMASK => 0xAFBAEBA8,
        NEGMASK => ~BITMASK,                    # Error!
    };

マジック定数

Magical values and references can be made into constants at compile time, allowing for way cool stuff like this. (These error numbers aren't totally portable, alas.)

マジック変数とリファレンスはコンパイル時に定数にすることができ、 以下のようなかっこいいことができるようになります。 (これらのエラー番号は完全な移植性はありません; あーあ。)

    use constant E2BIG => ($! = 7);
    print   E2BIG, "\n";        # something like "Arg list too long"
    print 0+E2BIG, "\n";        # "7"

You can't produce a tied constant by giving a tied scalar as the value. References to tied variables, however, can be used as constants without any problems.

値として tie されたスカラを与えることで tie された定数を 生成することはできません。 しかし、tie された変数へのリファレンスは、何の問題もなく定数として 使えます。

技術的な注意

In the current implementation, scalar constants are actually inlinable subroutines. As of version 5.004 of Perl, the appropriate scalar constant is inserted directly in place of some subroutine calls, thereby saving the overhead of a subroutine call. See "Constant Functions" in perlsub for details about how and when this happens.

現在の実装では、スカラ定数は実際にはインライン化可能なサブルーチンです。 Perl バージョン 5.004 から、対応するスカラ定数はサブルーチン呼び出しの 場所に直接挿入されるので、サブルーチン呼び出しのオーバーヘッドが なくなります。 これがいつどのように起こるかの詳細については "Constant Functions" in perlsub を参照してください。

In the rare case in which you need to discover at run time whether a particular constant has been declared via this module, you may use this function to examine the hash %constant::declared. If the given constant name does not include a package name, the current package is used.

稀な場合として、ある定数がこのモジュール経由で宣言されたかどうかを 実行時に発見する必要があるなら、ハッシュ %constant::declared を 調べるために以下の関数が使えます。 与えられた定数名にパッケージ名が含まれていない場合、現在のパッケージが 使われます。

    sub declared ($) {
        use constant 1.01;              # don't omit this!
        my $name = shift;
        $name =~ s/^::/main::/;
        my $pkg = caller;
        my $full_name = $name =~ /::/ ? $name : "${pkg}::$name";
        $constant::declared{$full_name};
    }

警告

In the current version of Perl, list constants are not inlined and some symbols may be redefined without generating a warning.

現在のバージョンの Perl では、リスト定数はインライン化されず、一部の シンボルは警告を出さずに再定義できてしまいます。

It is not possible to have a subroutine or a keyword with the same name as a constant in the same package. This is probably a Good Thing.

同じパッケージで定数と同じ名前のサブルーチンやキーワードは使えません。 これはおそらく「良いこと」です。

A constant with a name in the list STDIN STDOUT STDERR ARGV ARGVOUT ENV INC SIG is not allowed anywhere but in package main::, for technical reasons.

技術的な理由により、STDIN STDOUT STDERR ARGV ARGVOUT ENV INC SIG という名前の定数は main:: パッケージ以外では 宣言できません。

Unlike constants in some languages, these cannot be overridden on the command line or via environment variables.

一部の言語の定数と異なり、コマンドラインや環境定数で定数を 上書きできません。

You can get into trouble if you use constants in a context which automatically quotes barewords (as is true for any subroutine call). For example, you can't say $hash{CONSTANT} because CONSTANT will be interpreted as a string. Use $hash{CONSTANT()} or $hash{+CONSTANT} to prevent the bareword quoting mechanism from kicking in. Similarly, since the => operator quotes a bareword immediately to its left, you have to say CONSTANT() => 'value' (or simply use a comma in place of the big arrow) instead of CONSTANT => 'value'.

自動的に裸の単語をクォートするコンテキストで定数を使うと (サブルーチン呼び出しの場合と同様)問題が起こります。 例えば、$hash{CONSTANT} とはできません; CONSTANT は文字列として 解釈されるからです。 裸の単語をクォートする機構を防ぐために $hash{CONSTANT()}$hash{+CONSTANT} を使ってください。 同様に、the => 演算子は左側の裸の単語をクォートするので、 CONSTANT => 'value' ではなく CONSTANT() => 'value' とする (または単に大矢印の代わりにカンマを使う)必要があります。

SEE ALSO

Readonly - Facility for creating read-only scalars, arrays, hashes.

Readonly - 読み込み専用のスカラ、配列、ハッシュを作る機能。

Const - Facility for creating read-only variables. Similar to Readonly, but uses SvREADONLY instead of tie.

Const - 読み込み専用の変数を作る機能。 Readonly と似ていますが、tie ではなく SvREADONLY を使います。

Attribute::Constant - Make read-only variables via attribute

Attribute::Constant - 属性経由で読み込み専用変数を作る。

Scalar::Readonly - Perl extension to the SvREADONLY scalar flag

Scalar::Readonly - SvREADONLY スカラフラグのための Perl エクステンション

Hash::Util - A selection of general-utility hash subroutines (mostly to lock/unlock keys and values)

Hash::Util - 汎用ハッシュサブルーチンの集合 (ほとんどはキーと値を ロック/アンロックするもの)

バグ

Please report any bugs or feature requests via the perlbug(1) utility.

バグや機能追加リクエストは perlbug(1) ユーティリティを使って送って下さい。

作者

Tom Phoenix, <rootbeer@redcat.com>, with help from many other folks.

Tom Phoenix, <rootbeer@redcat.com> が多くの人々の助けと共に。

Multiple constant declarations at once added by Casey West, <casey@geeknest.com>.

一度に複数の定数を宣言する機能は Casey West, <casey@geeknest.com> によって追加されました。

Documentation mostly rewritten by Ilmari Karonen, <perl@itz.pp.sci.fi>.

文書は Ilmari Karonen, <perl@itz.pp.sci.fi> によって ほとんど書き直されました。

This program is maintained by the Perl 5 Porters. The CPAN distribution is maintained by Sébastien Aperghis-Tramoni <sebastien@aperghis.net>.

このプログラムは the Perl 5 Porters によって保守されています。 CPAN 配布は Sébastien Aperghis-Tramoni <sebastien@aperghis.net> によって保守されています。

COPYRIGHT & LICENSE

Copyright (C) 1997, 1999 Tom Phoenix

This module is free software; you can redistribute it or modify it under the same terms as Perl itself.