perl-5.38.0
require VERSION
require EXPR
require

Demands a version of Perl specified by VERSION, or demands some semantics specified by EXPR or by $_ if EXPR is not supplied.

VERSION で指定される Perl のバージョンを要求するか、 EXPR (省略時には $_) によって指定されるいくつかの動作を 要求します。

VERSION may be either a literal such as v5.24.1, which will be compared to $^V (or $PERL_VERSION in English), or a numeric argument of the form 5.024001, which will be compared to $]. An exception is raised if VERSION is greater than the version of the current Perl interpreter. Compare with use, which can do a similar check at compile time.

VERSION は、v5.24.1 のようなリテラル ($^V (または English モジュールでは $PERL_VERSION) と比較されます) か、 5.024001 の数値形式($] と比較されます)で指定します。 VERSION が Perl の現在のバージョンより大きいと、例外が発生します。 use と似ていますが、これはコンパイル時に チェックされます。

Specifying VERSION as a numeric argument of the form 5.024001 should generally be avoided as older less readable syntax compared to v5.24.1. Before perl 5.8.0 (released in 2002), the more verbose numeric form was the only supported syntax, which is why you might see it in older code.

VERSION に 5.024001 の形の数値引数を指定することは一般的には避けるべきです; v5.24.1 に比べてより古く読みにくい文法だからです。 (2002 年にリリースされた) perl 5.8.0 より前では、より冗長な 数値形式が唯一対応している文法でした; これが古いコードでこれを 見るかも知れない理由です。

    require v5.24.1;    # run time version check
    require 5.24.1;     # ditto
    require 5.024_001;  # ditto; older syntax compatible
                          with perl 5.6
    require v5.24.1;    # 実行時バージョンチェック
    require 5.24.1;     # 同様
    require 5.024_001;  # 同様; perl 5.6 と互換性のある古い文法

Otherwise, require demands that a library file be included if it hasn't already been included. The file is included via the do-FILE mechanism, which is essentially just a variety of eval with the caveat that lexical variables in the invoking script will be invisible to the included code. If it were implemented in pure Perl, it would have semantics similar to the following:

それ以外の場合には、require は、既に 読み込まれていないときに読み込むライブラリファイルを要求するものとなります。 そのファイルは、基本的には eval の一種である、 do-FILE によって読み込まれますが、起動したスクリプトのレキシカル変数は 読み込まれたコードから見えないという欠点があります。 ピュア Perl で実装した場合、意味的には、次のようなサブルーチンと 同じようなものです:

    use Carp 'croak';
    use version;

    sub require {
        my ($filename) = @_;
        if ( my $version = eval { version->parse($filename) } ) {
            if ( $version > $^V ) {
               my $vn = $version->normal;
               croak "Perl $vn required--this is only $^V, stopped";
            }
            return 1;
        }

        if (exists $INC{$filename}) {
            return 1 if $INC{$filename};
            croak "Compilation failed in require";
        }

        local $INC;
        # this type of loop lets a hook overwrite $INC if they wish
        for($INC = 0; $INC < @INC; $INC++) {
            my $prefix = $INC[$INC];
            if (!defined $prefix) {
                next;
            }
            if (ref $prefix) {
                #... do other stuff - see text below ....
            }
            # (see text below about possible appending of .pmc
            # suffix to $filename)
            my $realfilename = "$prefix/$filename";
            next if ! -e $realfilename || -d _ || -b _;
            $INC{$filename} = $realfilename;
            my $result = do($realfilename);
                         # but run in caller's namespace

            if (!defined $result) {
                $INC{$filename} = undef;
                croak $@ ? "$@Compilation failed in require"
                         : "Can't locate $filename: $!\n";
            }
            if (!$result) {
                delete $INC{$filename};
                croak "$filename did not return true value";
            }
            $! = 0;
            return $result;
        }
        croak "Can't locate $filename in \@INC ...";
    }

Note that the file will not be included twice under the same specified name.

ファイルは、同じ名前で 2 回読み込まれることはないことに注意してください。

Historically the file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements. As of 5.37.6 this requirement may be avoided by enabling the 'module_true' feature, which is enabled by default in modern version bundles. Thus code with use v5.37; no longer needs to concern itself with this issue. See feature for more details. Note that this affects the compilation unit within which the feature is used, and using it before requiring a module will not change the behavior of existing modules that do not themselves also use it.

歴史的に、初期化コードの実行がうまくいったことを示すために、ファイルは真を 返さなければならないので、真を返すようになっている自信がある場合を除いては、 ファイルの最後に 1; と書くのが習慣です。 しかし、実行文を追加するような場合に備えて、1; と書いておいた方が良いです。 5.37.6 から、この要求は最近の機能の束ではデフォルトで有効になっている 'module_true' 機能を有効にすることで避けることができます。 従って use v5.37; のあるコードは、もはやこの問題を考慮する必要は ありません。 さらなる詳細については feature を参照してください。 これはこの機能が使われているコンパイルユニットに影響を与え、 モジュールを require する前にこれを使うと、自分自身でこれを使っていない 既存のモジュールの振る舞いは変更しないことに注意してください。

If EXPR is a bareword, require assumes a .pm extension and replaces :: with / in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace, however it will autovivify the stash for the required module.

EXPR が裸の単語であるときには、標準モジュールのロードを簡単にするように、 require は拡張子が .pm であり、::/ に 変えたものがファイル名であると仮定します。 この形式のモジュールロードは、名前空間を変更してしまう危険はありませんが、 要求されたモジュールのためのスタッシュが自動有効化されます。

In other words, if you try this:

言い換えると、以下のようにすると:

        require Foo::Bar;     # a splendid bareword

The require function will actually look for the Foo/Bar.pm file in the directories specified in the @INC array, and it will autovivify the Foo::Bar:: stash at compile time.

require 関数は @INC 配列で指定されたディレクトリにある Foo/Bar.pm ファイルを探し、コンパイル時に Foo::Bar:: のスタッシュを自動有効化します。

But if you try this:

しかし、以下のようにすると:

        my $class = 'Foo::Bar';
        require $class;       # $class is not a bareword
    #or
        require "Foo::Bar";   # not a bareword because of the ""

The require function will look for the Foo::Bar file in the @INC array and will complain about not finding Foo::Bar there. In this case you can do:

require 関数は @INC 配列の Foo::Bar ファイルを探し、 おそらくそこに Foo::Bar がないと文句をいうことになるでしょう。 このような場合には、以下のように:

        eval "require $class";

or you could do

あるいは次のようにも出来ます

        require "Foo/Bar.pm";

Neither of these forms will autovivify any stashes at compile time and only have run time effects.

これらのどちらもコンパイル時にスタッシュを自動有効化せず、 実行時の効果のみを持ちます。

Now that you understand how require looks for files with a bareword argument, there is a little extra functionality going on behind the scenes. Before require looks for a .pm extension, it will first look for a similar filename with a .pmc extension. If this file is found, it will be loaded in place of any file ending in a .pm extension. This applies to both the explicit require "Foo/Bar.pm"; form and the require Foo::Bar; form.

引数が裸の単語の場合、require がどのようにファイルを 探すかを理解してください; 水面下でちょっとした追加の機能があります。 require が拡張子 .pm のファイルを探す前に、まず 拡張子 .pmc を持つファイルを探します。 このファイルが見つかると、このファイルが拡張子 .pm の代わりに 読み込まれます。 これは明示的な require "Foo/Bar.pm"; 形式と require Foo::Bar; 形式の 両方に適用されます。

You can also insert hooks into the import facility by putting Perl coderefs or objects directly into the @INC array. There are two types of hooks, INC filters, and INCDIR hooks, and there are three forms of representing a hook: subroutine references, array references, and blessed objects.

@INC 配列に直接コードリファレンスやオブジェクトを 入れることで、インポート機能にフックを挿入できます。 INC フィルタと INCDIR フックの 2 種類のフックがあり、 フックの表現方法は 3 種類あります: サブルーチンリファレンス、 配列リファレンス、bless されたオブジェクトです。

Subroutine references are the simplest case. When the inclusion system walks through @INC and encounters a subroutine, unless this subroutine is blessed and supports an INCDIR hook this subroutine will be assumed to be an INC hook will be called with two parameters, the first a reference to itself, and the second the name of the file to be included (e.g., Foo/Bar.pm). The subroutine should return either nothing or else a list of up to four values in the following order:

サブルーチンへのリファレンスは一番単純な場合です。 インクルード機能が @INC を走査してサブルーチンに 出会った場合、 このサブルーチンが bless されていて INCDIR フックに対応していない限り、 このサブルーチンは二つの引数と共に呼び出される INC フックであると 仮定されます; 一つ目は自身へのリファレンス、二つ目はインクルードされるファイル名 (Foo/Bar.pm など)です。 サブルーチンは何も返さないか、以下の順で最大四つの値のリストを返します。

  1. A reference to a scalar, containing any initial source code to prepend to the file or generator output.

    ファイルやジェネレータの出力の前に追加される初期化ソースコードを含む スカラへのリファレンス。

  2. A filehandle, from which the file will be read.

    ファイルが読み込まれるファイルハンドル。

  3. A reference to a subroutine. If there is no filehandle (previous item), then this subroutine is expected to generate one line of source code per call, writing the line into $_ and returning 1, then finally at end of file returning 0. If there is a filehandle, then the subroutine will be called to act as a simple source filter, with the line as read in $_. Again, return 1 for each valid line, and 0 after all lines have been returned. For historical reasons the subroutine will receive a meaningless argument (in fact always the numeric value zero) as $_[0].

    サブルーチンへのリファレンス。 (一つ前のアイテムである)ファイルハンドルがない場合、サブルーチンは呼び出し毎に 一行のソースコードを生成し、その行を $_ に書き込んで 1 を 返し、それから最終的にファイル終端で 0 を返すものと想定されます。 ファイルハンドルがある場合、サブルーチンは単純なソースフィルタとして 振舞うように呼び出され、行は $_ から読み込まれます。 再び、有効な行ごとに 1 を返し、全ての行を返した後では 0 を返します。 歴史的な理由により、サブルーチンは $_[0] として意味のない引数 (実際には常に数値 0) を受け取ります。

  4. Optional state for the subroutine. The state is passed in as $_[1].

    サブルーチンのための状態(オプション)。 状態は $_[1] として渡されます。

AUTOLOAD cannot be used to resolve the INCDIR method, INC is checked first, and AUTOLOAD would resolve that.

AUTOLOAD cannot be used to resolve the INCDIR method, INC is checked first, and AUTOLOAD would resolve that. (TBT)

If an empty list, undef, or nothing that matches the first 3 values above is returned, then require looks at the remaining elements of @INC. Note that this filehandle must be a real filehandle (strictly a typeglob or reference to a typeglob, whether blessed or unblessed); tied filehandles will be ignored and processing will stop there.

空リスト、undef、または上記の最初の三つの値のどれとも 一致しないものが返されると、require@INC の残りの要素を見ます。 このファイルハンドルは実際のファイルハンドル(厳密には型グロブ、型グロブへの リファレンス、bless されているかに関わらず)でなければなりません; tie されたファイルハンドルは無視され、返り値の処理はそこで停止します。

If the hook is an object, it should provide an INC or INCDIR method that will be called as above, the first parameter being the object itself. If it does not provide either method, and the object is not CODE ref then an exception will be thrown, otherwise it will simply be executed like an unblessed CODE ref would. Note that you must fully qualify the method name when you declare an INC sub (unlike the INCDIR sub), as the unqualified symbol INC is always forced into package main. Here is a typical code layout for an INC hook:

フックがオブジェクトの場合、INCINCDIR メソッドを提供している 必要があります; それが、最初の引数をオブジェクト自身として上述のように呼び出されます。 どちらのメソッドも提供されず、オブジェクトが CODE リファレンスでない場合は 例外が発生し、さもなければ 単に bless されていない CODE リファレンスのように実行されます。 修飾されていない INC シンボルは常にパッケージ main に強制されるため、 INC サブルーチンを宣言する場合は、 (INCDIR サブルーチンと異なり) 完全修飾しなければならないことに注意してください。 以下は INC フックの典型的なコードレイアウトです:

    # In Foo.pm
    package Foo;
    sub new { ... }
    sub Foo::INC {
        my ($self, $filename) = @_;
        ...
    }

    # In the main program
    push @INC, Foo->new(...);

If the hook is an array reference, its first element must be a subroutine reference or an object as described above. When the first element is an object that supports an INC or INCDIR method then the method will be called with the object as the first argument, the filename requested as the second, and the hook array reference as the the third. When the first element is a subroutine then it will be called with the array as the first argument, and the filename as the second, no third parameter will be passed in. In both forms you can modify the contents of the array to provide state between calls, or whatever you like.

フックが配列のリファレンスの場合、その最初の要素は前述の通り、 サブルーチンリファレンスかオブジェクトでなければなりません。 最初の要素がINCINCDIR メソッドに対応したオブジェクトの場合、 最初の引数をオブジェクト、2 番目を要求されたファイル名、3 番目を フックの配列リファレンスとして、このメソッドが呼び出されます。 最初の要素がサブルーチンの場合、最初の引数を配列、 2 番目をファイル名、3 番目はなしでこれが呼び出されます。 両方の形式で、呼び出しの間の状態を提供したり、あるいは 好きな理由で、配列の内容を変更できます。

In other words, you can write:

言い換えると、以下のように書けます:

    push @INC, \&my_sub;
    sub my_sub {
        my ($coderef, $filename) = @_;  # $coderef is \&my_sub
        ...
    }

or:

または:

    push @INC, [ \&my_sub, $x, $y, ... ];
    sub my_sub {
        my ($arrayref, $filename) = @_;
        # Retrieve $x, $y, ...
        my (undef, @parameters) = @$arrayref;
        ...
    }

or:

または:

    push @INC, [ HookObj->new(), $x, $y, ... ];
    sub HookObj::INC {
        my ($self, $filename, $arrayref)= @_;
        my (undef, @parameters) = @$arrayref;
        ...
    }

These hooks are also permitted to set the %INC entry corresponding to the files they have loaded. See "%INC" in perlvar. Should an INC hook not do this then perl will set the %INC entry to be the hook reference itself.

これらのフックは、読み込まれるファイルに対応する %INC エントリをセットすることも許可します。 "%INC" in perlvar を参照してください。 INC フックがこれをしない場合、perl は %INC エントリに フックリファレンス自身を設定します。

A hook may also be used to rewrite the @INC array. While this might sound strange, there are situations where it can be very useful to do this. Such hooks usually just return undef and do not mix filtering and @INC modifications. While in older versions of perl having a hook modify @INC was fraught with issues and could even result in segfaults or assert failures, as of 5.37.7 the logic has been made much more robust and the hook now has control over the loop iteration if it wishes to do so.

A hook may also be used to rewrite the @INC array. While this might sound strange, there are situations where it can be very useful to do this. Such hooks usually just return undef and do not mix filtering and @INC modifications. While in older versions of perl having a hook modify @INC was fraught with issues and could even result in segfaults or assert failures, as of 5.37.7 the logic has been made much more robust and the hook now has control over the loop iteration if it wishes to do so. (TBT)

There is a now a facility to control the iterator for the @INC array traversal that is performed during require. The $INC variable will be initialized with the index of the currently executing hook. Once the hook returns the next slot in @INC that will be checked will be the integer successor of value in $INC (or -1 if it is undef). For example the following code

There is a now a facility to control the iterator for the @INC array traversal that is performed during require. The $INC variable will be initialized with the index of the currently executing hook. Once the hook returns the next slot in @INC that will be checked will be the integer successor of value in $INC (or -1 if it is undef). For example the following code (TBT)

    push @INC, sub {
        splice @INC, $INC, 1; # remove this hook from @INC
        unshift @INC, sub { warn "A" };
        undef $INC; # reset the $INC iterator so we
                    # execute the newly installed sub
                    # immediately.
    };

would install a sub into @INC that when executed as a hook (by for instance a require of a file that does not exist), the hook will splice itself out of @INC, and add a new sub to the front that will warn whenever someone does a require operation that requires an @INC search, and then immediately execute that hook.

would install a sub into @INC that when executed as a hook (by for instance a require of a file that does not exist), the hook will splice itself out of @INC, and add a new sub to the front that will warn whenever someone does a require operation that requires an @INC search, and then immediately execute that hook. (TBT)

Prior to 5.37.7, there was no way to cause perl to use the newly installed hook immediately, or to inspect any changed items in @INC to the left of the iterator, and so the warning would only be generated on the second call to require. In more recent perl the presence of the last statement which undefines $INC will cause perl to restart the traversal of the @INC array at the beginning and execute the newly installed sub immediately.

Prior to 5.37.7, there was no way to cause perl to use the newly installed hook immediately, or to inspect any changed items in @INC to the left of the iterator, and so the warning would only be generated on the second call to require. In more recent perl the presence of the last statement which undefines $INC will cause perl to restart the traversal of the @INC array at the beginning and execute the newly installed sub immediately. (TBT)

Whatever value $INC held, if any, will be restored at the end of the require. Any changes made to $INC during the lifetime of the hook will be unrolled after the hook exits, and its value only has meaning immediately after execution of the hook, thus setting $INC to some value prior to executing a require will have no effect on how the require executes at all.

Whatever value $INC held, if any, will be restored at the end of the require. Any changes made to $INC during the lifetime of the hook will be unrolled after the hook exits, and its value only has meaning immediately after execution of the hook, thus setting $INC to some value prior to executing a require will have no effect on how the require executes at all. (TBT)

As of 5.37.7 @INC values of undef will be silently ignored.

As of 5.37.7 @INC values of undef will be silently ignored. (TBT)

The function require() is difficult to wrap properly. Many modules consult the stack to find information about their caller, and injecting a new stack frame by wrapping require() often breaks things. Nevertheless it can be very helpful to have the ability to perform actions before and after a require, for instance for trace utilities like Devel::TraceUse or to measure time to load and the memory consumption of the require graph. Because of the difficulties in safely creating a require() wrapper in 5.37.10 we introduced a new mechanism.

The function require() is difficult to wrap properly. Many modules consult the stack to find information about their caller, and injecting a new stack frame by wrapping require() often breaks things. Nevertheless it can be very helpful to have the ability to perform actions before and after a require, for instance for trace utilities like Devel::TraceUse or to measure time to load and the memory consumption of the require graph. Because of the difficulties in safely creating a require() wrapper in 5.37.10 we introduced a new mechanism. (TBT)

As of 5.37.10, prior to any other actions it performs, require will check if ${^HOOK}{require__before} contains a coderef, and if it does it will be called with the filename form of the item being loaded. The hook may modify $_[0] to load a different filename, or it may throw a fatal exception to cause the require to fail, which will be treated as though the required code itself had thrown an exception.

As of 5.37.10, prior to any other actions it performs, require will check if ${^HOOK}{require__before} contains a coderef, and if it does it will be called with the filename form of the item being loaded. The hook may modify $_[0] to load a different filename, or it may throw a fatal exception to cause the require to fail, which will be treated as though the required code itself had thrown an exception. (TBT)

The ${^HOOK}{require__before} hook may return a code reference, in which case the code reference will be executed (in an eval with the filname as a parameter) after the require completes. It will be executed regardless of how the compilation completed, and even if the require throws a fatal exception. The function may consult %INC to determine if the require failed or not. For instance the following code will print some diagnostics before and after every require statement. The example also includes logic to chain the signal, so that multiple signals can cooperate. Well behaved ${^HOOK}{require__before} handlers should always take this into account.

The ${^HOOK}{require__before} hook may return a code reference, in which case the code reference will be executed (in an eval with the filname as a parameter) after the require completes. It will be executed regardless of how the compilation completed, and even if the require throws a fatal exception. The function may consult %INC to determine if the require failed or not. For instance the following code will print some diagnostics before and after every require statement. The example also includes logic to chain the signal, so that multiple signals can cooperate. Well behaved ${^HOOK}{require__before} handlers should always take this into account. (TBT)

    {
        use Scalar::Util qw(reftype);
        my $old_hook = ${^HOOK}{require__before};
        local ${^HOOK}{require__before} = sub {
            my ($name) = @_;
            my $old_hook_ret;
            $old_hook_ret = $old_hook->($name) if $old_hook;
            warn "Requiring: $name\n";
            return sub {
                $old_hook_ret->() if ref($old_hook_ret)
                                  && reftype($old_hook_ret) eq "CODE";
                warn sprintf "Finished requiring %s: %s\n",
                        $name, $INC{$name} ? "loaded" :"failed";
            };
        };
        require Whatever;
    }

This hook executes for ALL require statements, unlike INC and INCDIR hooks, which are only executed for relative file names, and it executes first before any other special behaviour inside of require. Note that the initial hook in ${^HOOK}{require__before} is *not* executed inside of an eval, and throwing an exception will stop further processing, but the after hook it may return is executed inside of an eval, and any exceptions it throws will be silently ignored. This is because it executes inside of the scope cleanup logic that is triggered after the require completes, and an exception at this time would not stop the module from being loaded, etc.

This hook executes for ALL require statements, unlike INC and INCDIR hooks, which are only executed for relative file names, and it executes first before any other special behaviour inside of require. Note that the initial hook in ${^HOOK}{require__before} is *not* executed inside of an eval, and throwing an exception will stop further processing, but the after hook it may return is executed inside of an eval, and any exceptions it throws will be silently ignored. This is because it executes inside of the scope cleanup logic that is triggered after the require completes, and an exception at this time would not stop the module from being loaded, etc. (TBT)

There is a similar hook that fires after require completes, ${^HOOK}{require__after}, which will be called after each require statement completes, either via an exception or successfully. It will be called with the filename of the most recently executed require statement. It is executed in an eval, and will not in any way affect execution.

There is a similar hook that fires after require completes, ${^HOOK}{require__after}, which will be called after each require statement completes, either via an exception or successfully. It will be called with the filename of the most recently executed require statement. It is executed in an eval, and will not in any way affect execution. (TBT)

For a yet-more-powerful import facility built around require, see use and perlmod.

require 関連で構築されている、より強力な import 機能については、 この文書の use の項と、 perlmod を参照してください。