5.30.0

NAME

perlfunc - Perl builtin functions

perlfunc - Perl 組み込み関数

説明

The functions in this section can serve as terms in an expression. They fall into two major categories: list operators and named unary operators. These differ in their precedence relationship with a following comma. (See the precedence table in perlop.) List operators take more than one argument, while unary operators can never take more than one argument. Thus, a comma terminates the argument of a unary operator, but merely separates the arguments of a list operator. A unary operator generally provides scalar context to its argument, while a list operator may provide either scalar or list contexts for its arguments. If it does both, scalar arguments come first and list argument follow, and there can only ever be one such list argument. For instance, splice has three scalar arguments followed by a list, whereas gethostbyname has four scalar arguments.

この節の関数は、式の中で項として使うことができます。 これらは、大きく二つに分けられます: リスト演算子と名前付き単項演算子です。 これらの違いは、その後に出て来るコンマとの優先順位の関係にあります。 (perlop の優先順位の表を参照してください。) リスト演算子は 2 個以上の引数をとるのに対して、単項演算子が複数の引数を とることはありません。 つまり、コンマは単項演算子の引数の終わりとなりますが、リスト演算子の 場合には、引数の区切りでしかありません。 単項演算子は一般に、引数に対してスカラコンテキストを与えるのに対して、 スカラ演算子の場合には、引数に対してスカラコンテキストを与える場合も、 リストコンテキストを与える場合もあります。 一つのリスト演算子が両方のコンテキストを与える場合には、スカラ引数が いくつか並び、最後にリスト引数が一つ続きます; そしてそのようなリスト引数は一つだけしかありません。 たとえば、splice は三つのスカラ引数に 一つのリスト引数が続きます; 一方 gethostbyname は四つのスカラ引数を持ちます。

In the syntax descriptions that follow, list operators that expect a list (and provide list context for elements of the list) are shown with LIST as an argument. Such a list may consist of any combination of scalar arguments or list values; the list values will be included in the list as if each individual element were interpolated at that point in the list, forming a longer single-dimensional list value. Commas should separate literal elements of the LIST.

後に載せる構文記述では、リストをとり (そのリストの要素にリストコンテキストを 与える)リスト演算子は、引数として LIST をとるように書いています; そのようなリストには、任意のスカラ引数の組み合わせやリスト値を 含めることができ、リスト値はリストの中に、個々の要素が展開されたように 埋め込まれます。 1 次元の長いリスト値が形成されることになります。 LIST のリテラルな要素は、コンマで区切られます。

Any function in the list below may be used either with or without parentheses around its arguments. (The syntax descriptions omit the parentheses.) If you use parentheses, the simple but occasionally surprising rule is this: It looks like a function, therefore it is a function, and precedence doesn't matter. Otherwise it's a list operator or unary operator, and precedence does matter. Whitespace between the function and left parenthesis doesn't count, so sometimes you need to be careful:

以下のリストの関数はすべて、引数の前後の括弧は省略可能となっています。 (構文記述では省略しています。) 括弧を使うときには、単純な、(しかし、ときには驚く結果となる規則が 適用できます: 関数に見えるならば、それは関数で、優先順位は関係ありません。 そう見えなければ、それはリスト演算子か単項演算子で、優先順位が関係します。 関数と開き括弧の間の空白は関係ありませんので、ときに 気を付けなければなりません:

    print 1+2+4;      # Prints 7.
    print(1+2) + 4;   # Prints 3.
    print (1+2)+4;    # Also prints 3!
    print +(1+2)+4;   # Prints 7.
    print ((1+2)+4);  # Prints 7.

If you run Perl with the use warnings pragma, it can warn you about this. For example, the third line above produces:

Perl に use warnings プラグマを付けて実行すれば、 こういったものには警告を出してくれます。 たとえば、上記の三つめは、以下のような警告が出ます:

    print (...) interpreted as function at - line 1.
    Useless use of integer addition in void context at - line 1.

A few functions take no arguments at all, and therefore work as neither unary nor list operators. These include such functions as time and endpwent. For example, time+86_400 always means time() + 86_400.

いくつかの関数は引数を全くとらないので、単項演算子としても リスト演算子としても動作しません。 このような関数としては timeendpwent が あります。 例えば、time+86_400 は常に time() + 86_400 として扱われます。

For functions that can be used in either a scalar or list context, nonabortive failure is generally indicated in scalar context by returning the undefined value, and in list context by returning the empty list.

スカラコンテキストでも、リストコンテキストでも使える関数は、致命的でない エラーを示すために、スカラコンテキストでは未定義値を返し、 リストコンテキストでは空リストを返します。

Remember the following important rule: There is no rule that relates the behavior of an expression in list context to its behavior in scalar context, or vice versa. It might do two totally different things. Each operator and function decides which sort of value would be most appropriate to return in scalar context. Some operators return the length of the list that would have been returned in list context. Some operators return the first value in the list. Some operators return the last value in the list. Some operators return a count of successful operations. In general, they do what you want, unless you want consistency.

以下に述べる重要なルールを忘れないで下さい: リストコンテキストでの 振る舞いとスカラコンテキストでの振る舞いの関係、あるいはその逆に ルールはありません。 2 つの全く異なったことがあります。 それぞれの演算子と関数は、スカラコンテキストでは、もっとも適切と 思われる値を返します。 リストコンテキストで返す時のリストの長さを返す演算子もあります。 リストの最初の値を返す演算子もあります。 リストの最後の値を返す演算子もあります。 成功した操作の数を返す演算子もあります。 一般的には、一貫性を求めない限り、こちらが求めることをします。

A named array in scalar context is quite different from what would at first glance appear to be a list in scalar context. You can't get a list like (1,2,3) into being in scalar context, because the compiler knows the context at compile time. It would generate the scalar comma operator there, not the list concatenation version of the comma. That means it was never a list to start with.

スカラコンテキストでの名前付き配列は、スカラコンテキストでのリストを 一目見たものとは全く違います。 コンパイラはコンパイル時にコンテキストを知っているので、 (1,2,3) のようなリストをスカラコンテキストで得ることはできません。 これはスカラコンマ演算子を生成し、コンマのリスト結合版ではありません。 これは初めからリストであることはないことを意味します。

In general, functions in Perl that serve as wrappers for system calls ("syscalls") of the same name (like chown(2), fork(2), closedir(2), etc.) return true when they succeed and undef otherwise, as is usually mentioned in the descriptions below. This is different from the C interfaces, which return -1 on failure. Exceptions to this rule include wait, waitpid, and syscall. System calls also set the special $! variable on failure. Other functions do not, except accidentally.

一般的に、同じ名前のシステムコールのラッパーとして動作する Perl の関数 (chown(2), fork(2), closedir(2) など)は、以下に述べるように、 成功時に真を返し、そうでなければ undef を返します。 これは失敗時に -1 を返す C のインターフェースとは違います。 このルールの例外は wait, waitpid, syscall です。 システムコールは失敗時に特殊変数 $! をセットします。 その他の関数は、事故を除いて、セットしません。

Extension modules can also hook into the Perl parser to define new kinds of keyword-headed expression. These may look like functions, but may also look completely different. The syntax following the keyword is defined entirely by the extension. If you are an implementor, see "PL_keyword_plugin" in perlapi for the mechanism. If you are using such a module, see the module's documentation for details of the syntax that it defines.

エクステンションモジュールは、新しい種類のキーワードが頭に付いた式を 定義するために Perl パーサをフックできます。 これらは関数のように見えるかもしれませんが、全く別物かもしれません。 キーワード以降の文法は完全にエクステンションによって定義されます。 もしあなたが実装者なら、この機構については "PL_keyword_plugin" in perlapi を 参照してください。 もしあなたがそのようなモジュールを使っているなら、 定義されている文法の詳細についてはモジュールの文書を参照してください。

カテゴリ別の Perl 関数

Here are Perl's functions (including things that look like functions, like some keywords and named operators) arranged by category. Some functions appear in more than one place. Any warnings, including those produced by keywords, are described in perldiag and warnings.

以下に、カテゴリ別の関数(キーワードや名前付き演算子のような、 関数のように見えるものも含みます)を示します。 複数の場所に現れる関数もあります。 キーワードによって生成されるものを含む全ての警告は perldiagwarnings に記述されています。

Functions for SCALARs or strings

(スカラや文字列のための関数)

chomp, chop, chr, crypt, fc, hex, index, lc, lcfirst, length, oct, ord, pack, q//, qq//, reverse, rindex, sprintf, substr, tr///, uc, ucfirst, y///

fc is available only if the "fc" feature is enabled or if it is prefixed with CORE::. The "fc" feature is enabled automatically with a use v5.16 (or higher) declaration in the current scope.

fc"fc" 機能 が有効か CORE:: が前置されたときにのみ利用可能です。 "fc" 機能 は現在のスコープで use v5.16 (またはそれ以上) が宣言されると自動的に有効になります。

Regular expressions and pattern matching

(正規表現とパターンマッチング)

m//, pos, qr//, quotemeta, s///, split, study

Numeric functions

(数値関数)

abs, atan2, cos, exp, hex, int, log, oct, rand, sin, sqrt, srand

Functions for real @ARRAYs

(実配列のための関数)

each, keys, pop, push, shift, splice, unshift, values

Functions for list data

(リストデータのための関数)

grep, join, map, qw//, reverse, sort, unpack

Functions for real %HASHes

(実ハッシュのための関数)

delete, each, exists, keys, values

Input and output functions

(入出力関数)

binmode, close, closedir, dbmclose, dbmopen, die, eof, fileno, flock, format, getc, print, printf, read, readdir, readline, rewinddir, say, seek, seekdir, select, syscall, sysread, sysseek, syswrite, tell, telldir, truncate, warn, write

say is available only if the "say" feature is enabled or if it is prefixed with CORE::. The "say" feature is enabled automatically with a use v5.10 (or higher) declaration in the current scope.

say"say" 機能 が有効か CORE:: が 前置されたときにのみ利用可能です。 "say" 機能 は現在のスコープで use v5.10 (またはそれ以上) が宣言されると自動的に有効になります。

Functions for fixed-length data or records

(固定長データやレコードのための関数)

pack, read, syscall, sysread, sysseek, syswrite, unpack, vec

Functions for filehandles, files, or directories

(ファイルハンドル、ファイル、ディレクトリのための関数)

-X, chdir, chmod, chown, chroot, fcntl, glob, ioctl, link, lstat, mkdir, open, opendir, readlink, rename, rmdir, select, stat, symlink, sysopen, umask, unlink, utime

Keywords related to the control flow of your Perl program

(プログラムの流れを制御することに関連するキーワード)

break, caller, continue, die, do, dump, eval, evalbytes, exit, __FILE__, goto, last, __LINE__, next, __PACKAGE__, redo, return, sub, __SUB__, wantarray

break is available only if you enable the experimental "switch" feature or use the CORE:: prefix. The "switch" feature also enables the default, given and when statements, which are documented in "Switch Statements" in perlsyn. The "switch" feature is enabled automatically with a use v5.10 (or higher) declaration in the current scope. In Perl v5.14 and earlier, continue required the "switch" feature, like the other keywords.

break は、実験的な "switch" 機能 が有効か CORE:: 接頭辞を 使ったときにのみ利用可能です。 "switch" 機能 は、 "Switch Statements" in perlsyn で文書化されている default, given, when 文も有効にします。 "switch" 機能 は、現在のスコープで use v5.10 (またはそれ以上) 宣言があると自動的に有効になります。 Perl v5.14 以前では、continue は他のキーワードと同様に "switch" 機能 が必要です。

evalbytes is only available with the "evalbytes" feature (see feature) or if prefixed with CORE::. __SUB__ is only available with the "current_sub" feature or if prefixed with CORE::. Both the "evalbytes" and "current_sub" features are enabled automatically with a use v5.16 (or higher) declaration in the current scope.

evalbytes"evalbytes" 機能 (feature 参照) が有効か CORE:: が前置されたときにのみ利用可能です。 __SUB__"current_sub" 機能 が有効か CORE:: が前置されたときにのみ利用可能です。 "evalbytes""current_sub" の両方の機能は 現在のスコープで use v5.16 (またはそれ以上) が宣言されると自動的に有効になります。

Keywords related to scoping

(スコープに関するキーワード)

caller, import, local, my, our, package, state, use

state is available only if the "state" feature is enabled or if it is prefixed with CORE::. The "state" feature is enabled automatically with a use v5.10 (or higher) declaration in the current scope.

state"state" 機能 が有効か CORE:: を 前置した場合にのみ利用可能です。 "state" 機能 は現在のスコープで use v5.10 (またはそれ以上) を宣言した場合自動的に有効になります。

Miscellaneous functions

(さまざまな関数)

defined, formline, lock, prototype, reset, scalar, undef

Functions for processes and process groups

(プロセスとプロセスグループのための関数)

alarm, exec, fork, getpgrp, getppid, getpriority, kill, pipe, qx//, readpipe, setpgrp, setpriority, sleep, system, times, wait, waitpid

Keywords related to Perl modules

(Perl モジュールに関するキーワード)

do, import, no, package, require, use

Keywords related to classes and object-orientation

(クラスとオブジェクト指向に関するキーワード)

bless, dbmclose, dbmopen, package, ref, tie, tied, untie, use

Low-level socket functions

(低レベルソケット関数)

accept, bind, connect, getpeername, getsockname, getsockopt, listen, recv, send, setsockopt, shutdown, socket, socketpair

System V interprocess communication functions

(System V プロセス間通信関数)

msgctl, msgget, msgrcv, msgsnd, semctl, semget, semop, shmctl, shmget, shmread, shmwrite

Fetching user and group info

(ユーザーとグループの情報取得)

endgrent, endhostent, endnetent, endpwent, getgrent, getgrgid, getgrnam, getlogin, getpwent, getpwnam, getpwuid, setgrent, setpwent

Fetching network info

(ネットワーク情報取得)

endprotoent, endservent, gethostbyaddr, gethostbyname, gethostent, getnetbyaddr, getnetbyname, getnetent, getprotobyname, getprotobynumber, getprotoent, getservbyname, getservbyport, getservent, sethostent, setnetent, setprotoent, setservent

Time-related functions

(時刻に関する関数)

gmtime, localtime, time, times

Non-function keywords

and, AUTOLOAD, BEGIN, CHECK, cmp, CORE, __DATA__, default, DESTROY, else, elseif, elsif, END, __END__, eq, for, foreach, ge, given, gt, if, INIT, le, lt, ne, not, or, UNITCHECK, unless, until, when, while, x, xor

移植性

Perl was born in Unix and can therefore access all common Unix system calls. In non-Unix environments, the functionality of some Unix system calls may not be available or details of the available functionality may differ slightly. The Perl functions affected by this are:

Perl は Unix 環境で生まれたので、全ての共通する Unix システムコールに アクセスします。 非 Unix 環境では、いくつかの Unix システムコールの機能が使えなかったり、 使える機能の詳細が多少異なったりします。 これによる影響を受ける Perl 関数は以下のものです:

-X, binmode, chmod, chown, chroot, crypt, dbmclose, dbmopen, dump, endgrent, endhostent, endnetent, endprotoent, endpwent, endservent, exec, fcntl, flock, fork, getgrent, getgrgid, gethostbyname, gethostent, getlogin, getnetbyaddr, getnetbyname, getnetent, getppid, getpgrp, getpriority, getprotobynumber, getprotoent, getpwent, getpwnam, getpwuid, getservbyport, getservent, getsockopt, glob, ioctl, kill, link, lstat, msgctl, msgget, msgrcv, msgsnd, open, pipe, readlink, rename, select, semctl, semget, semop, setgrent, sethostent, setnetent, setpgrp, setpriority, setprotoent, setpwent, setservent, setsockopt, shmctl, shmget, shmread, shmwrite, socket, socketpair, stat, symlink, syscall, sysopen, system, times, truncate, umask, unlink, utime, wait, waitpid

For more information about the portability of these functions, see perlport and other available platform-specific documentation.

これらの関数の移植性に関するさらなる情報については、 perlport とその他のプラットホーム固有のドキュメントを参照してください。

Alphabetical Listing of Perl Functions

-X FILEHANDLE
-X EXPR
-X DIRHANDLE
-X

A file test, where X is one of the letters listed below. This unary operator takes one argument, either a filename, a filehandle, or a dirhandle, and tests the associated file to see if something is true about it. If the argument is omitted, tests $_, except for -t, which tests STDIN. Unless otherwise documented, it returns 1 for true and '' for false. If the file doesn't exist or can't be examined, it returns undef and sets $! (errno). With the exception of the -l test they all follow symbolic links because they use stat() and not lstat() (so dangling symlinks can't be examined and will therefore report failure).

X は以下にあげる文字で、ファイルテストを行ないます。 この単項演算子は、ファイル名かファイルハンドルを唯一の引数として動作し、 「あること」について真であるか否かを判定した結果を返します。 引数が省略されると、-t では STDIN を調べますが、その他は $_ を調べます。 特に記述されていなければ、真として 1 を返し、偽として '' を返します。 ファイルが存在しないか、テスト出来なければ、undef を返し、 $! (errno) を設定します。 -l テストを例外として、これら全てはシンボリックリンクに従います; lstat() ではなく stat() を使っているからです (従って壊れたシンボリックリンクは検査されず、失敗が報告されます)。

Despite the funny names, precedence is the same as any other named unary operator. The operator may be any of:

みかけは変わっていますが、優先順位は名前付き単項演算子と同じで、 他の単項演算子と同じく、引数を括弧で括ることもできます。 演算子には以下のものがあります:

    -r  File is readable by effective uid/gid.
    -w  File is writable by effective uid/gid.
    -x  File is executable by effective uid/gid.
    -o  File is owned by effective uid.
    -r  ファイルが実効 uid/gid で読み出し可。
    -w  ファイルが実効 uid/gid で書き込み可。
    -x  ファイルが実効 uid/gid で実行可。
    -o  ファイルが実効 uid の所有物。
    -R  File is readable by real uid/gid.
    -W  File is writable by real uid/gid.
    -X  File is executable by real uid/gid.
    -O  File is owned by real uid.
    -R  ファイルが実 uid/gid で読み出し可。
    -W  ファイルが実 uid/gid で書き込み可。
    -X  ファイルが実 uid/gid で実行可。
    -O  ファイルが実 uid の所有物。
    -e  File exists.
    -z  File has zero size (is empty).
    -s  File has nonzero size (returns size in bytes).
    -e  ファイルが存在する。
    -z  ファイルの大きさがゼロ(空)。
    -s  ファイルの大きさがゼロ以外 (バイト単位での大きさを返す)。
    -f  File is a plain file.
    -d  File is a directory.
    -l  File is a symbolic link (false if symlinks aren't
        supported by the file system).
    -p  File is a named pipe (FIFO), or Filehandle is a pipe.
    -S  File is a socket.
    -b  File is a block special file.
    -c  File is a character special file.
    -t  Filehandle is opened to a tty.
    -f  ファイルは通常ファイル。
    -d  ファイルはディレクトリ。
    -l  ファイルはシンボリックリンク(ファイルシステムが非対応なら偽)。
    -p  ファイルは名前付きパイプ (FIFO) またはファイルハンドルはパイプ。
    -S  ファイルはソケット。
    -b  ファイルはブロック特殊ファイル。
    -c  ファイルはキャラクタ特殊ファイル。
    -t  ファイルハンドルは tty にオープンされている。
    -u  File has setuid bit set.
    -g  File has setgid bit set.
    -k  File has sticky bit set.
    -u  ファイルの setuid ビットがセットされている。
    -g  ファイルの setgid ビットがセットされている。
    -k  ファイルの sticky ビットがセットされている。
    -T  File is an ASCII or UTF-8 text file (heuristic guess).
    -B  File is a "binary" file (opposite of -T).
    -T  ファイルは ASCII または UTF-8 テキストファイル (発見的に推測します)。
    -B  ファイルは「バイナリ」ファイル (-T の反対)。
    -M  Script start time minus file modification time, in days.
    -A  Same for access time.
    -C  Same for inode change time (Unix, may differ for other
        platforms)
    -M  スクリプト実行開始時刻からファイル修正時刻を引いたもの(日単位)。
    -A  同様にアクセスがあってからの日数。
    -C  同様に(Unix では) inode が変更されてからの日数(それ以外の
        プラットフォームでは違うかもしれません)。

Example:

例:

    while (<>) {
        chomp;
        next unless -f $_;  # ignore specials
        #...
    }

Note that -s/a/b/ does not do a negated substitution. Saying -exp($foo) still works as expected, however: only single letters following a minus are interpreted as file tests.

-s/a/b は、置換演算 (s///) の符号反転ではありません。 しかし、-exp($foo) は期待どおりに動作します; しかし、マイナス記号の後に 英字が 1 字続くときにのみ、ファイルテストと解釈されます。

These operators are exempt from the "looks like a function rule" described above. That is, an opening parenthesis after the operator does not affect how much of the following code constitutes the argument. Put the opening parentheses before the operator to separate it from code that follows (this applies only to operators with higher precedence than unary operators, of course):

これらの演算子は上述の「関数のように見えるルール」から免除されます。 つまり、演算子の後の開きかっこは、引き続くコードのどこまでが引数を 構成するかに影響を与えません。 演算子を引き続くコードから分離するには、演算子の前に開きかっこを 置いてください (これはもちろん、単項演算子より高い優先順位を持つ 演算子にのみ適用されます):

    -s($file) + 1024   # probably wrong; same as -s($file + 1024)
    (-s $file) + 1024  # correct

The interpretation of the file permission operators -r, -R, -w, -W, -x, and -X is by default based solely on the mode of the file and the uids and gids of the user. There may be other reasons you can't actually read, write, or execute the file: for example network filesystem access controls, ACLs (access control lists), read-only filesystems, and unrecognized executable formats. Note that the use of these six specific operators to verify if some operation is possible is usually a mistake, because it may be open to race conditions.

ファイルのパーミッション演算子 -r, -R, -w, -W, -x, -X の解釈は、ファイルのモードとユーザの実効/実 uid と 実効/実 gid のみから判断されます。 実際にファイルが読めたり、書けたり、実行できたりするためには、 別の条件が必要かもしれません: 例えば、ネットワークファイルシステムアクセスコントロール、 ACL(アクセスコントロールリスト)、読み込み専用ファイルシステム、 認識できない実行ファイルフォーマット、などです。 これらの 6 つの演算子を、特定の操作が可能かどうかを確認するために使うのは 通常は誤りであることに注意してください; なぜなら、これらは競合条件を 招きやすいからです。

Also note that, for the superuser on the local filesystems, the -r, -R, -w, and -W tests always return 1, and -x and -X return 1 if any execute bit is set in the mode. Scripts run by the superuser may thus need to do a stat to determine the actual mode of the file, or temporarily set their effective uid to something else.

ローカルファイルシステムのスーパーユーザには、 -r, -R, -w, -W に対して、常に 1 が返り、モード中の いずれかの実行許可ビットが立っていれば、-x, -X にも 1 が 返ることにも注意してください。 スーパーユーザが実行するスクリプトでは、ファイルのモードを調べるためには、 stat を行なうか、実効 uid を一時的に別のものにする 必要があるでしょう。

If you are using ACLs, there is a pragma called filetest that may produce more accurate results than the bare stat mode bits. When under use filetest 'access', the above-mentioned filetests test whether the permission can(not) be granted using the access(2) family of system calls. Also note that the -x and -X tests may under this pragma return true even if there are no execute permission bits set (nor any extra execute permission ACLs). This strangeness is due to the underlying system calls' definitions. Note also that, due to the implementation of use filetest 'access', the _ special filehandle won't cache the results of the file tests when this pragma is in effect. Read the documentation for the filetest pragma for more information.

ACL を使っている場合は、生の stat モードビットより 精度の高い結果を作成する filetest プラグマがあります。 use filetest 'access' とした場合、上述したファイルテストは システムコールの access(2) ファミリーを使って権限が与えられているか どうかをテストします。 また、このプラグマが指定されている場合、-x-X テストは たとえ実行許可ビット(または追加の実行許可 ACL)がセットされていない 場合でも真を返すことに注意してください。 この挙動は使用するシステムコールの定義によるものです。 use filetest 'access' の実装により、このプラグマが有効の場合は _ 特殊ファイルハンドルはファイルテストの結果をキャッシュしないことに 注意してください。 さらなる情報については filetest プラグマのドキュメントを 参照してください。

The -T and -B tests work as follows. The first block or so of the file is examined to see if it is valid UTF-8 that includes non-ASCII characters. If so, it's a -T file. Otherwise, that same portion of the file is examined for odd characters such as strange control codes or characters with the high bit set. If more than a third of the characters are strange, it's a -B file; otherwise it's a -T file. Also, any file containing a zero byte in the examined portion is considered a binary file. (If executed within the scope of a use locale which includes LC_CTYPE, odd characters are anything that isn't a printable nor space in the current locale.) If -T or -B is used on a filehandle, the current IO buffer is examined rather than the first block. Both -T and -B return true on an empty file, or a file at EOF when testing a filehandle. Because you have to read a file to do the -T test, on most occasions you want to use a -f against the file first, as in next unless -f $file && -T $file.

ファイルテスト -T-B の動作原理は、次のようになっています。 ファイルの最初の数ブロックを調べて、非 ASCII 文字を含む妥当な UTF-8 かどうかを 調べます。 もしそうなら、それは -T ファイルです。 さもなければ、ファイルの同じ位置から、変わった制御コードや 上位ビットがセットされているような、通常のテキストには現れない文字を探します。 三分の一以上がおかしな文字なら、それは -B ファイルでです; さもなければ -T ファイルです。 また、調べた位置にヌル文字が含まれるファイルも、バイナリファイルと みなされます。 (LC_CTYPE を含む use locale のスコープの中で実行されると、 おかしな文字というのは現在のロケールで表示可能でもスペースでもないものです。) -T-B をファイルハンドルに対して用いると、 最初のブロックを調べる代わりに、IO バッファを調べます。 調べたファイルの中身が何もないときや、 ファイルハンドルを調べたときに EOF に達して いたときには、-T-B も「真」を返します。 -T テストをするためにはファイルを読み込まないといけないので、 たいていは next unless -f $file && -T $file というような形で まず調べたいファイルに対して -f を使いたいはずです。

If any of the file tests (or either the stat or lstat operator) is given the special filehandle consisting of a solitary underline, then the stat structure of the previous file test (or stat operator) is used, saving a system call. (This doesn't work with -t, and you need to remember that lstat and -l leave values in the stat structure for the symbolic link, not the real file.) (Also, if the stat buffer was filled by an lstat call, -T and -B will reset it with the results of stat _). Example:

どのファイルテスト (あるいは、statlstat) 演算子にも、 下線だけから成る特別なファイルハンドルを与えると、 前回のファイルテスト (や stat 演算子) の stat 構造体が使われ、システムコールを省きます。 (-t には使えませんし、lstat-l は 実ファイルではなく、シンボリックリンクの情報を stat 構造体に残すことを 覚えておく必要があります。) (また、stat バッファが lstat 呼び出しで埋まった場合、 -T-B の結果は stat _ の結果でリセットされます。 例:

    print "Can do.\n" if -r $a || -w _ || -x _;

    stat($filename);
    print "Readable\n" if -r _;
    print "Writable\n" if -w _;
    print "Executable\n" if -x _;
    print "Setuid\n" if -u _;
    print "Setgid\n" if -g _;
    print "Sticky\n" if -k _;
    print "Text\n" if -T _;
    print "Binary\n" if -B _;

As of Perl 5.10.0, as a form of purely syntactic sugar, you can stack file test operators, in a way that -f -w -x $file is equivalent to -x $file && -w _ && -f _. (This is only fancy syntax: if you use the return value of -f $file as an argument to another filetest operator, no special magic will happen.)

Perl 5.10.0 から、純粋にシンタックスシュガーとして、ファイルテスト演算子を スタックさせることができるので、-f -w -x $file-x $file && -w _ && -f _ と等価です。 (これは文法上だけの話です; もし -f $file の返り値を他のファイルテスト 演算子の引数として使う場合は、何の特別なことも起きません。)

Portability issues: "-X" in perlport.

移植性の問題: "-X" in perlport

To avoid confusing would-be users of your code with mysterious syntax errors, put something like this at the top of your script:

あなたのコードのユーザーが不思議な文法エラーで混乱することを 避けるために、スクリプトの先頭に以下のようなことを書いてください:

    use 5.010;  # so filetest ops can stack
abs VALUE
abs

Returns the absolute value of its argument. If VALUE is omitted, uses $_.

引数の絶対値を返します。 VALUE が省略された場合は、$_ を使います。

accept NEWSOCKET,GENERICSOCKET

Accepts an incoming socket connect, just as accept(2) does. Returns the packed address if it succeeded, false otherwise. See the example in "Sockets: Client/Server Communication" in perlipc.

accept(2) システムコールと同様に、着信するソケットの接続を受け付けます。 成功時にはパックされたアドレスを返し、失敗すれば偽を返します。 "Sockets: Client/Server Communication" in perlipc の例を参照してください。

On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor, as determined by the value of $^F. See "$^F" in perlvar.

ファイルに対する close-on-exec フラグをサポートしているシステムでは、 フラグは $^F の値で決定される、新しくオープンされた ファイル記述子に対してセットされます。 "$^F" in perlvar を参照してください。

alarm SECONDS
alarm

Arranges to have a SIGALRM delivered to this process after the specified number of wallclock seconds has elapsed. If SECONDS is not specified, the value stored in $_ is used. (On some machines, unfortunately, the elapsed time may be up to one second less or more than you specified because of how seconds are counted, and process scheduling may delay the delivery of the signal even further.)

指定した壁時計秒数が経過した後に、自プロセスに SIGALRM が 送られてくるようにします。 SECONDS が指定されていない場合は、$_ に格納されている値を 使います。 (マシンによっては、秒の数え方が異なるため、指定した秒数よりも最大で 1 秒ずれます。)

Only one timer may be counting at once. Each call disables the previous timer, and an argument of 0 may be supplied to cancel the previous timer without starting a new one. The returned value is the amount of time remaining on the previous timer.

一度には一つのタイマだけが設定可能です。 呼び出しを行なう度に、以前のタイマを無効にしますし、 新しくタイマを起動しないで以前のタイマをキャンセルするために 引数に 0 を指定して呼び出すことができます。 以前のタイマの残り時間が、返り値となります。

For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides ualarm. You may also use Perl's four-argument version of select leaving the first three arguments undefined, or you might be able to use the syscall interface to access setitimer(2) if your system supports it. See perlfaq8 for details.

1 秒より精度の高いスリープを行なうには、Time::HiRes モジュール(CPAN から、 また Perl 5.8 からは標準配布されています) が usleep を提供します。 Perl の 4 引数版 select を最初の 3 引数を未定義にして使うか、setitimer(2) をサポートしているシステムでは、 Perl の syscall インタフェースを使って アクセスすることもできます。 詳しくは perlfaq8 を参照してください。

It is usually a mistake to intermix alarm and sleep calls, because sleep may be internally implemented on your system with alarm.

alarmsleep を混ぜて使うのは 普通は間違いです; なぜなら、sleep は内部的に alarm を使って内部的に実装されているかも しれないからです。

If you want to use alarm to time out a system call you need to use an eval/die pair. You can't rely on the alarm causing the system call to fail with $! set to EINTR because Perl sets up signal handlers to restart system calls on some systems. Using eval/die always works, modulo the caveats given in "Signals" in perlipc.

alarm をシステムコールの時間切れのために使いたいなら、 eval/die のペアで使う必要があります。 システムコールが失敗したときに $!EINTR が セットされることに頼ってはいけません; なぜならシステムによっては Perl は システムコールを再開するためにシグナルハンドラを設定するからです。 eval/die は常にうまく動きます; 注意点については "Signals" in perlipc を参照してください。

    eval {
        local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
        alarm $timeout;
        my $nread = sysread $socket, $buffer, $size;
        alarm 0;
    };
    if ($@) {
        die unless $@ eq "alarm\n";   # propagate unexpected errors
        # timed out
    }
    else {
        # didn't
    }

For more information see perlipc.

さらなる情報については perlipc を参照してください。

Portability issues: "alarm" in perlport.

移植性の問題: "alarm" in perlport

atan2 Y,X

Returns the arctangent of Y/X in the range -PI to PI.

-πからπの範囲で Y/X の逆正接を返します。

For the tangent operation, you may use the Math::Trig::tan function, or use the familiar relation:

正接を求めたいときは、Math::Trig::tan を使うか、 以下のよく知られた関係を使ってください。

    sub tan { sin($_[0]) / cos($_[0])  }

The return value for atan2(0,0) is implementation-defined; consult your atan2(3) manpage for more information.

atan2(0,0) の返り値は実装依存です; さらなる情報については atan2(3) man ページを参照してください。

Portability issues: "atan2" in perlport.

移植性の問題: "atan2" in perlport

bind SOCKET,NAME

Binds a network address to a socket, just as bind(2) does. Returns true if it succeeded, false otherwise. NAME should be a packed address of the appropriate type for the socket. See the examples in "Sockets: Client/Server Communication" in perlipc.

bind(2) システムコールと同様に、ネットワークアドレスをソケットに 結び付けます。 成功時には真を、さもなければ偽を返します。 NAME は、ソケットに対する、適切な型のパックされた アドレスでなければなりません。 "Sockets: Client/Server Communication" in perlipc の例を参照してください。

binmode FILEHANDLE, LAYER
binmode FILEHANDLE

Arranges for FILEHANDLE to be read or written in "binary" or "text" mode on systems where the run-time libraries distinguish between binary and text files. If FILEHANDLE is an expression, the value is taken as the name of the filehandle. Returns true on success, otherwise it returns undef and sets $! (errno).

バイナリファイルとテキストファイルを区別する OS において、 FILEHANDLE を「バイナリ」または「テキスト」で読み書きするように 指定します。 FILEHANDLE が式である場合には、その式の値がファイルハンドルの 名前として使われます。 成功時には真を返し、失敗時には undef を返して $! (errno) を設定します。

On some systems (in general, DOS- and Windows-based systems) binmode is necessary when you're not working with a text file. For the sake of portability it is a good idea always to use it when appropriate, and never to use it when it isn't appropriate. Also, people can set their I/O to be by default UTF8-encoded Unicode, not bytes.

テキストファイルでないものを扱う場合に binmode が必要な システムもあります(一般的には DOS と Windows ベースのシステムです)。 移植性のために、適切なときには常にこれを使い、適切でないときには 決して使わないというのは良い考えです。 また、デフォルトとして I/O を bytes ではなく UTF-8 エンコードされた Unicode にセットすることも出来ます。

In other words: regardless of platform, use binmode on binary data, like images, for example.

言い換えると: プラットフォームに関わらず、 例えばイメージのようなバイナリファイルに対しては binmode を使ってください。

If LAYER is present it is a single string, but may contain multiple directives. The directives alter the behaviour of the filehandle. When LAYER is present, using binmode on a text file makes sense.

LAYER が存在すると、それは単一の文字列ですが、複数の指示子を 含むことができます。 指示子はファイルハンドルの振る舞いを変更します。 LAYER が存在すると、テキストファイルでの binmode が意味を持ちます。

If LAYER is omitted or specified as :raw the filehandle is made suitable for passing binary data. This includes turning off possible CRLF translation and marking it as bytes (as opposed to Unicode characters). Note that, despite what may be implied in "Programming Perl" (the Camel, 3rd edition) or elsewhere, :raw is not simply the inverse of :crlf. Other layers that would affect the binary nature of the stream are also disabled. See PerlIO, perlrun, and the discussion about the PERLIO environment variable.

LAYER が省略されたり、:raw が指定されると、ファイルハンドルはバイナリ データの通過に適するように設定されます。 これには CRLF 変換をオフにしたり、それぞれを(Unicode 文字ではなく) バイトであるとマークしたりすることを含みます。 "プログラミング Perl"(ラクダ本第三版) やその他で暗示されているにも関わらず、 :raw は単なる :crlf逆ではありません。 ストリームのバイナリとしての性質に影響を与える その他の層も無効にされますPerlIO, perlrun およびPERLIO 環境変数に関する議論を参照してください。

The :bytes, :crlf, :utf8, and any other directives of the form :..., are called I/O layers. The open pragma can be used to establish default I/O layers.

:bytes, :crlf, and :utf8, 及びその他の :... 形式の指示子は I/O が呼び出されます。 open プラグマはデフォルト I/O 層を指定するために使われます。

The LAYER parameter of the binmode function is described as "DISCIPLINE" in "Programming Perl, 3rd Edition". However, since the publishing of this book, by many known as "Camel III", the consensus of the naming of this functionality has moved from "discipline" to "layer". All documentation of this version of Perl therefore refers to "layers" rather than to "disciplines". Now back to the regularly scheduled documentation...

binmode 関数の LAYER パラメータは 「プログラミングPerl 第 3 版」では 「ディシプリン(DISCIPLINE)」と表現されていました。 しかし、「ラクダ本第 3 版」として知られているこの本の出版後、この機能の名前は 「ディシプリン」から「層」に変更することで合意されました。 従って、このバージョンの Perl の全ての文書では「ディシプリン」ではなく 「層」と記述されています。では通常の解説に戻ります…

To mark FILEHANDLE as UTF-8, use :utf8 or :encoding(UTF-8). :utf8 just marks the data as UTF-8 without further checking, while :encoding(UTF-8) checks the data for actually being valid UTF-8. More details can be found in PerlIO::encoding.

FILEHANDLE が UTF-8 であるというマークをつけるには、:utf8:encoding(UTF-8) を使ってください。 :utf8 は、さらなるチェックなしにデータが UTF-8 としてマークしますが、 :encoding(UTF-8) はデータが実際に有効な UTF-8 かどうかをチェックします。 さらなる詳細は PerlIO::encoding にあります。

In general, binmode should be called after open but before any I/O is done on the filehandle. Calling binmode normally flushes any pending buffered output data (and perhaps pending input data) on the handle. An exception to this is the :encoding layer that changes the default character encoding of the handle. The :encoding layer sometimes needs to be called in mid-stream, and it doesn't flush the stream. :encoding also implicitly pushes on top of itself the :utf8 layer because internally Perl operates on UTF8-encoded Unicode characters.

一般的に binmodeopen を呼び出した後、このファイルハンドルに対する I/O 操作をする前に呼び出すべきです。 binmode を呼び出すと、普通はこの ファイルハンドルに対してバッファリングされている全ての出力データ (およびおそらくは入力データ)をフラッシュします。 例外は、このハンドルに対するデフォルト文字エンコーディングを変更する :encoding 層です。 :encoding 層はストリームの途中で呼び出す必要があることがあり、 それによってストリームはフラッシュされません。 Perl は内部で UTF-8 エンコードされた Unicode 文字を操作しているので、 :encoding は暗黙のうちに自身を :utf8 層の上に押し上げます。

The operating system, device drivers, C libraries, and Perl run-time system all conspire to let the programmer treat a single character (\n) as the line terminator, irrespective of external representation. On many operating systems, the native text file representation matches the internal representation, but on some platforms the external representation of \n is made up of more than one character.

オペレーティングシステム、デバイスドライバ、C ライブラリ、 Perl ランタイムシステムは全て、プログラマが外部表現に関わらず 1 文字 (\n) を行終端として扱えるように協調作業します。 多くのオペレーティングシステムでは、ネイティブテキストファイル表現は 内部表現と同じですが、\n の外部表現が複数文字になる プラットフォームもあります。

All variants of Unix, Mac OS (old and new), and Stream_LF files on VMS use a single character to end each line in the external representation of text (even though that single character is CARRIAGE RETURN on old, pre-Darwin flavors of Mac OS, and is LINE FEED on Unix and most VMS files). In other systems like OS/2, DOS, and the various flavors of MS-Windows, your program sees a \n as a simple \cJ, but what's stored in text files are the two characters \cM\cJ. That means that if you don't use binmode on these systems, \cM\cJ sequences on disk will be converted to \n on input, and any \n in your program will be converted back to \cM\cJ on output. This is what you want for text files, but it can be disastrous for binary files.

全ての Unix 系、(新旧の)Mac OS、VMS の Stream_LF ファイルは テキストの外部表現として各行の末尾に一つの文字を 使っています(しかしその文字は古い Darwin 以前の Mac OS では復帰で、 Unix とほとんどのVMS のファイルでは改行です)。 VMS, MS-DOS, MS-Windows 系といったその他のシステムでは、 プログラムからは \n は単純に \cJ に見えますが、 テキストファイルとして保存される場合は \cM\cJ の 2 文字になります。 つまり、もしこれらのシステムで binmode を 使わないと、ディスク上の \cM\cJ という並びは入力時に \n に変換され、 プログラムが出力した全ての \n\cM\cJ に逆変換されます。 これはテキストファイルの場合は思い通りの結果でしょうが、 バイナリファイルの場合は悲惨です。

Another consequence of using binmode (on some systems) is that special end-of-file markers will be seen as part of the data stream. For systems from the Microsoft family this means that, if your binary data contain \cZ, the I/O subsystem will regard it as the end of the file, unless you use binmode.

binmode を(いくつかのシステムで) 使うことによるその他の作用としては、特別なファイル終端マーカーが データストリームの一部として見られることです。 Microsoft ファミリーのシステムでは、 binmode を使っていないと、 もしバイナリデータに \cZ が含まれていたときに、 I/O サブシステムがこれをファイル終端とみなすことを意味します。

binmode is important not only for readline and print operations, but also when using read, seek, sysread, syswrite and tell (see perlport for more details). See the $/ and $\ variables in perlvar for how to manually set your input and output line-termination sequences.

binmodereadlineprint 操作にだけではなく、 read, seek, sysread, syswrite, tell を使うときにも重要です (詳細は perlport を参照してください)。 入出力の行端末シーケンスを手動でセットする方法については perlvar$/ 変数と $\ 変数を参照してください。

Portability issues: "binmode" in perlport.

移植性の問題: "binmode" in perlport

bless REF,CLASSNAME
bless REF

This function tells the thingy referenced by REF that it is now an object in the CLASSNAME package. If CLASSNAME is an empty string, it is interpreted as referring to the main package. If CLASSNAME is omitted, the current package is used. Because a bless is often the last thing in a constructor, it returns the reference for convenience. Always use the two-argument version if a derived class might inherit the method doing the blessing. See perlobj for more about the blessing (and blessings) of objects.

この関数は、REF で渡された オブジェクトに対し、 CLASSNAME 内のオブジェクトとなったことを伝えます。 CLASSNAME が空文字列の場合、main パッケージを参照しているものと 解釈されます。 CLASSNAME が省略された場合には、その時点のパッケージとなります。 bless は通常、コンストラクタの最後に 置かれますので、簡便のためにそのリファレンスを返します。 派生クラスが bless されるメソッドを継承する場合は、 常に 2 引数版を使ってください。 オブジェクトの bless (や再 bless) について、詳しくは と perlobj を 参照してください。

Consider always blessing objects in CLASSNAMEs that are mixed case. Namespaces with all lowercase names are considered reserved for Perl pragmas. Builtin types have all uppercase names. To prevent confusion, you may wish to avoid such package names as well. It is advised to avoid the class name 0, because much code erroneously uses the result of ref as a truth value.

大文字小文字が混じっている CLASSNAME のオブジェクトは常に bless することを 考慮してください。 全て小文字の名前を持つ名前空間は Perl プラグマのために予約されています。 組み込みの型は全て大文字の名前を持ちます。 混乱を避けるために、 パッケージ名としてこのような名前は避けるべきです。 CLASSNAME は真の値を持つようにしてください。 クラス名として 0 は避けてください; 多くのコードが誤って ref の結果を真の値として使っているからです。

"Perl Modules" in perlmod を参照してください。

break

Break out of a given block.

given ブロックから脱出します。

break is available only if the "switch" feature is enabled or if it is prefixed with CORE::. The "switch" feature is enabled automatically with a use v5.10 (or higher) declaration in the current scope.

break は、"switch" 機能 が 有効か、CORE:: 接頭辞を使ったときにのみ利用可能です。 "switch" 機能 は、現在のスコープで use v5.10 (またはそれ以上) 宣言があると自動的に有効になります。

caller EXPR
caller

Returns the context of the current pure perl subroutine call. In scalar context, returns the caller's package name if there is a caller (that is, if we're in a subroutine or eval or require) and the undefined value otherwise. caller never returns XS subs and they are skipped. The next pure perl sub will appear instead of the XS sub in caller's return values. In list context, caller returns

その時点のピュア perl サブルーチン呼び出しのコンテキストを返します。 スカラコンテキストでは、呼び元が ある 場合 (サブルーチン、evalrequire の中に いるとき) には呼び出し元のパッケージ名を返し、 その他のときには未定義値を返します。 caller は XS サブルーチンを返すことはなく、それらは飛ばされます。 XS サブルーチンの代わりに次のピュア perl サブルーチンが caller の返り値に なります。 リストコンテキストでは、caller は以下を返します:

       # 0         1          2
    my ($package, $filename, $line) = caller;

With EXPR, it returns some extra information that the debugger uses to print a stack trace. The value of EXPR indicates how many call frames to go back before the current one.

EXPR を付けると、デバッガがスタックトレースを表示するために使う情報を返します。 EXPR の値は、現状から数えて、 いくつ前のコールフレームまで戻るかを示します。

    #  0         1          2      3            4
 my ($package, $filename, $line, $subroutine, $hasargs,

    #  5          6          7            8       9         10
    $wantarray, $evaltext, $is_require, $hints, $bitmask, $hinthash)
  = caller($i);

Here, $subroutine is the function that the caller called (rather than the function containing the caller). Note that $subroutine may be (eval) if the frame is not a subroutine call, but an eval. In such a case additional elements $evaltext and $is_require are set: $is_require is true if the frame is created by a require or use statement, $evaltext contains the text of the eval EXPR statement. In particular, for an eval BLOCK statement, $subroutine is (eval), but $evaltext is undefined. (Note also that each use statement creates a require frame inside an eval EXPR frame.) $subroutine may also be (unknown) if this particular subroutine happens to have been deleted from the symbol table. $hasargs is true if a new instance of @_ was set up for the frame. $hints and $bitmask contain pragmatic hints that the caller was compiled with. $hints corresponds to $^H, and $bitmask corresponds to ${^WARNING_BITS}. The $hints and $bitmask values are subject to change between versions of Perl, and are not meant for external use.

ここで、$subroutine は、(caller を含む関数ではなく) caller が呼び出した 関数です。 フレームがサブルーチン呼び出しではなく eval だった場合、この $subroutine は (eval) になることに注意してください。 この場合、追加の要素である $evaltext と $is_require がセットされます: $is_require はフレームが require または use で作られた場合に真になり、 $evaltext は eval EXPR のテキストが入ります。 特に、eval BLOCK の場合、$subroutine は (eval) になりますが、 $evaltext は未定義値になります。 (それぞれの useeval EXPR の中で require フレームを作ることに注意してください。) $subroutine は、そのサブルーチンがシンボルテーブルから削除された場合は (unknown) になります。 $hasargs はこのフレーム用に @_ の新しい実体が 設定された場合に真となります。 $hints$bitmask は caller がコンパイルされたときの 実際的なヒントを含みます。 $hints$^H に対応し、$bitmask${^WARNING_BITS} に 対応します。 $hints$bitmask は Perl のバージョンによって変更される 可能性があるので、外部での使用を想定していません。

$hinthash is a reference to a hash containing the value of %^H when the caller was compiled, or undef if %^H was empty. Do not modify the values of this hash, as they are the actual values stored in the optree.

$hinthash は、caller がコンパイルされた時の %^H の値を 含むハッシュへのリファレンスか、あるいは %^H が空の場合は undef です。 このハッシュの値は構文木に保管されている実際の値なので、変更しないで下さい。

Furthermore, when called from within the DB package in list context, and with an argument, caller returns more detailed information: it sets the list variable @DB::args to be the arguments with which the subroutine was invoked.

さらに、DB パッケージの中からリストコンテキストで引数付きで呼ばれた場合は、 caller はより詳細な情報を返します; サブルーチンが起動されたときの引数を 変数 @DB::args に設定します。

Be aware that the optimizer might have optimized call frames away before caller had a chance to get the information. That means that caller(N) might not return information about the call frame you expect it to, for N > 1. In particular, @DB::args might have information from the previous time caller was called.

caller が情報を得る前にオプティマイザが呼び出しフレームを 最適化してしまうかもしれないことに注意してください。 これは、caller(N)N > 1 のとき、 あなたが予測した呼び出しフレームの情報を返さないかもしれないことを意味します。 特に、@DB::argscaller が前回呼び出された時の情報を 持っているかもしれません。

Be aware that setting @DB::args is best effort, intended for debugging or generating backtraces, and should not be relied upon. In particular, as @_ contains aliases to the caller's arguments, Perl does not take a copy of @_, so @DB::args will contain modifications the subroutine makes to @_ or its contents, not the original values at call time. @DB::args, like @_, does not hold explicit references to its elements, so under certain cases its elements may have become freed and reallocated for other variables or temporary values. Finally, a side effect of the current implementation is that the effects of shift @_ can normally be undone (but not pop @_ or other splicing, and not if a reference to @_ has been taken, and subject to the caveat about reallocated elements), so @DB::args is actually a hybrid of the current state and initial state of @_. Buyer beware.

@DB::args の設定は ベストエフォート で、デバッグやバックトレースの 生成を目的としていて、これに依存するべきではないということにも 注意してください。 特に、@_ は呼び出し元の引数へのエイリアスを含んでいるので、 Perl は @_ のコピーを取らず、従って @DB::args は サブルーチンが @_ やその内容に行った変更を含んでいて、 呼び出し時の元の値ではありません。 @DB::args は、@_ と同様、その要素への明示的な リファレンスを保持しないので、ある種の状況では、解放されて他の変数や 一時的な値のために再割り当てされているかもしれません。 最後に、現在の実装の副作用は、shift @_ の効果は 普通は 行われない (しかし pop @_ やその他の splice は違い、そして もし @_ のリファレンスが取られると違い、そして 再割り当てされた 要素に関する問題になりやすいです)ことなので、@DB::args は実際には現在の 状態と @_ の初期状態との合成物となります。 ご用心を。

chdir EXPR
chdir FILEHANDLE
chdir DIRHANDLE
chdir

Changes the working directory to EXPR, if possible. If EXPR is omitted, changes to the directory specified by $ENV{HOME}, if set; if not, changes to the directory specified by $ENV{LOGDIR}. (Under VMS, the variable $ENV{'SYS$LOGIN'} is also checked, and used if it is set.) If neither is set, chdir does nothing and fails. It returns true on success, false otherwise. See the example under die.

(可能であれば、) カレントディレクトリを EXPR に移します。 EXPR を指定しないと、$ENV{HOME} が設定されていれば、そのディレクトリに 移ります; そうでなく、$ENV{LOGDIR}が設定されていれば、そのディレクトリに 移ります。 (VMS では $ENV{'SYS$LOGIN'} もチェックされ、もしセットされていれば 使われます。) どちらも設定されていなければ、chdir は何もせずに失敗します。 成功時には真を返し、そうでなければ偽を返します。 die の項の例を参照してください。

On systems that support fchdir(2), you may pass a filehandle or directory handle as the argument. On systems that don't support fchdir(2), passing handles raises an exception.

fchdir(2) に対応しているシステムでは、ファイルハンドルや ディレクトリハンドルを引数として渡せます。 fchdir(2) に対応していないシステムでは、ハンドルを渡すと例外が発生します。

chmod LIST

Changes the permissions of a list of files. The first element of the list must be the numeric mode, which should probably be an octal number, and which definitely should not be a string of octal digits: 0644 is okay, but "0644" is not. Returns the number of files successfully changed. See also oct if all you have is a string.

LIST に含まれるファイルの、パーミッションを変更します。 LIST の最初の要素は、数値表現のモードでなければなりません; 恐らく 8 進表記の数であるべきでしょう: しかし、8 進表記の 文字列では いけません: 0644 は OK ですが、 "0644" は だめ、ということです。 変更に成功したファイルの数を返します。 文字列を使いたい場合は、oct を参照してください。

    my $cnt = chmod 0755, "foo", "bar";
    chmod 0755, @executables;
    my $mode = "0644"; chmod $mode, "foo";      # !!! sets mode to
                                                # --w----r-T
    my $mode = "0644"; chmod oct($mode), "foo"; # this is better
    my $mode = 0644;   chmod $mode, "foo";      # this is best

On systems that support fchmod(2), you may pass filehandles among the files. On systems that don't support fchmod(2), passing filehandles raises an exception. Filehandles must be passed as globs or glob references to be recognized; barewords are considered filenames.

fchmod(2) に対応しているシステムでは、ファイルハンドルを引数として 渡せます。 fchmod(2) に対応していないシステムでは、ファイルハンドルを渡すと 例外が発生します。 ファイルハンドルを認識させるためには、グロブまたはリファレンスとして 渡されなければなりません; 裸の単語はファイル名として扱われます。

    open(my $fh, "<", "foo");
    my $perm = (stat $fh)[2] & 07777;
    chmod($perm | 0600, $fh);

You can also import the symbolic S_I* constants from the Fcntl module:

Fcntl モジュールから S_I* シンボル定数を インポートすることもできます:

    use Fcntl qw( :mode );
    chmod S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH, @executables;
    # Identical to the chmod 0755 of the example above.

Portability issues: "chmod" in perlport.

移植性の問題: "chmod" in perlport

chomp VARIABLE
chomp( LIST )
chomp

This safer version of chop removes any trailing string that corresponds to the current value of $/ (also known as $INPUT_RECORD_SEPARATOR in the English module). It returns the total number of characters removed from all its arguments. It's often used to remove the newline from the end of an input record when you're worried that the final record may be missing its newline. When in paragraph mode ($/ = ''), it removes all trailing newlines from the string. When in slurp mode ($/ = undef) or fixed-length record mode ($/ is a reference to an integer or the like; see perlvar), chomp won't remove anything. If VARIABLE is omitted, it chomps $_. Example:

より安全な chop (以下を参照してください) です; $/ (English モジュールでは、 $INPUT_RECORD_SEPARATOR とも言う) のその時点の 値に対応する行末文字を削除します。 全ての引数から削除した文字数の合計を返します。 入力レコードから、改行を削除したいのだけれど、最後のレコードには改行が 入っているのかわからないような場合に、使用できます。 段落モード ($/ = '') では、レコードの最後の改行をすべて取り除きます。 吸い込みモード ($/ = undef) や 固定長レコードモード ($/ が整数へのリファレンスや類似のものの場合; perlvarを参照してください)では、chomp は 何も取り除きません。 VARIABLE が省略されると、$_ を対象として chomp します。 例:

    while (<>) {
        chomp;  # avoid \n on last field
        my @array = split(/:/);
        # ...
    }

If VARIABLE is a hash, it chomps the hash's values, but not its keys, resetting the each iterator in the process.

VARIABLE がハッシュなら、ハッシュのキーではなく値について chomp し、 このプロセスの each 反復子をリセットします。

You can actually chomp anything that's an lvalue, including an assignment:

左辺値であれば、代入を含めて、任意のものを chomp できます:

    chomp(my $cwd = `pwd`);
    chomp(my $answer = <STDIN>);

If you chomp a list, each element is chomped, and the total number of characters removed is returned.

リストを chomp すると、個々の要素が chomp され、 削除された文字数の合計が返されます。

Note that parentheses are necessary when you're chomping anything that is not a simple variable. This is because chomp $cwd = `pwd`; is interpreted as (chomp $cwd) = `pwd`;, rather than as chomp( $cwd = `pwd` ) which you might expect. Similarly, chomp $a, $b is interpreted as chomp($a), $b rather than as chomp($a, $b).

単純な変数以外のものを chomp する場合はかっこが必要であることに 注意してください。 これは、chomp $cwd = `pwd`; は、予測している chomp( $cwd = `pwd` ) ではなく、(chomp $cwd) = `pwd`; と 解釈されるからです。 同様に、chomp $a, $bchomp($a, $b) ではなく chomp($a), $b と解釈されます。

chop VARIABLE
chop( LIST )
chop

Chops off the last character of a string and returns the character chopped. It is much more efficient than s/.$//s because it neither scans nor copies the string. If VARIABLE is omitted, chops $_. If VARIABLE is a hash, it chops the hash's values, but not its keys, resetting the each iterator in the process.

文字列の最後の文字を切り捨てて、その切り取った文字を返します。 文字列の検索もコピーも行ないませんので s/.$//s よりも、ずっと効率的です。 VARIABLE が省略されると、$_ を対象として chop します。 VARIABLE がハッシュの場合、ハッシュのキーではなく値について chop し、 このプロセスの each 反復子をリセットします。

You can actually chop anything that's an lvalue, including an assignment.

実際のところ、代入を含む左辺値となりうるなんでも chop できます。

If you chop a list, each element is chopped. Only the value of the last chop is returned.

リストを chop すると、個々の要素が chop されます。 最後の chop の値だけが返されます。

Note that chop returns the last character. To return all but the last character, use substr($string, 0, -1).

chop は最後の文字を返すことに注意してください。 最後以外の全ての文字を返すためには、substr($string, 0, -1) を 使ってください。

See also chomp.

chomp も参照してください。

chown LIST

Changes the owner (and group) of a list of files. The first two elements of the list must be the numeric uid and gid, in that order. A value of -1 in either position is interpreted by most systems to leave that value unchanged. Returns the number of files successfully changed.

LIST に含まれるファイルの所有者 (とグループ) を変更します。 LIST の最初の二つの要素には、数値表現 の uid と gid を この順序で与えなければなりません。 どちらかの値を -1 にすると、ほとんどのシステムではその値は 変更しないと解釈します。 変更に成功したファイルの数を返します。

    my $cnt = chown $uid, $gid, 'foo', 'bar';
    chown $uid, $gid, @filenames;

On systems that support fchown(2), you may pass filehandles among the files. On systems that don't support fchown(2), passing filehandles raises an exception. Filehandles must be passed as globs or glob references to be recognized; barewords are considered filenames.

fchown(2) に対応しているシステムでは、ファイルハンドルを引数として渡せます。 fchown(2) に対応していないシステムでは、ファイルハンドルを渡すと 例外が発生します。 ファイルハンドルを認識させるためには、グロブまたはリファレンスとして 渡されなければなりません; 裸の単語はファイル名として扱われます。

Here's an example that looks up nonnumeric uids in the passwd file:

passwd ファイルから数値表現でない uid を検索する例を 示します:

    print "User: ";
    chomp(my $user = <STDIN>);
    print "Files: ";
    chomp(my $pattern = <STDIN>);

    my ($login,$pass,$uid,$gid) = getpwnam($user)
        or die "$user not in passwd file";

    my @ary = glob($pattern);  # expand filenames
    chown $uid, $gid, @ary;

On most systems, you are not allowed to change the ownership of the file unless you're the superuser, although you should be able to change the group to any of your secondary groups. On insecure systems, these restrictions may be relaxed, but this is not a portable assumption. On POSIX systems, you can detect this condition this way:

ほとんどのシステムでは、スーパーユーザーだけがファイルの所有者を 変更できますが、グループは実行者の副グループに変更できるべきです。 安全でないシステムでは、この制限はゆるめられています; しかしこれは 移植性のある仮定ではありません。 POSIX システムでは、以下のようにしてこの条件を検出できます:

    use POSIX qw(sysconf _PC_CHOWN_RESTRICTED);
    my $can_chown_giveaway = ! sysconf(_PC_CHOWN_RESTRICTED);

Portability issues: "chown" in perlport.

移植性の問題: "chown" in perlport

chr NUMBER
chr

Returns the character represented by that NUMBER in the character set. For example, chr(65) is "A" in either ASCII or Unicode, and chr(0x263a) is a Unicode smiley face.

特定の文字セットでの NUMBER で表わされる文字を返します。 たとえば、chr(65) は ASCII と Unicode の両方で "A" となります; chr(0x263a) は Unicode のスマイリーフェイスです。

Negative values give the Unicode replacement character (chr(0xfffd)), except under the bytes pragma, where the low eight bits of the value (truncated to an integer) are used.

負の数は Unicode の置換文字 (chr(0xfffd)) を与えますが、 bytes プラグマの影響下では、(integer に切り詰められた)値の下位 8 ビットが 使われます。

If NUMBER is omitted, uses $_.

NUMBER が省略された場合、$_ を使います。

For the reverse, use ord.

逆を行うためには、ord を参照してください。

Note that characters from 128 to 255 (inclusive) are by default internally not encoded as UTF-8 for backward compatibility reasons.

128 から 255 までの文字は過去との互換性のために デフォルトでは UTF-8 Unicode にエンコードされません。

See perlunicode for more about Unicode.

Unicode については perlunicode を参照してください。

chroot FILENAME
chroot

This function works like the system call by the same name: it makes the named directory the new root directory for all further pathnames that begin with a / by your process and all its children. (It doesn't change your current working directory, which is unaffected.) For security reasons, this call is restricted to the superuser. If FILENAME is omitted, does a chroot to $_.

同じ名前のシステムコールと同じことをします: 現在のプロセス及び子プロセスに 対して、/で始まるパス名に関して指定されたディレクトリを新しい ルートディレクトリとして扱います。 (これはカレントディレクトリを変更しません; カレントディレクトリは そのままです。) セキュリティ上の理由により、この呼び出しはスーパーユーザーしか行えません。 FILENAME を省略すると、$_chroot します。

NOTE: It is good security practice to do chdir("/") (chdir to the root directory) immediately after a chroot.

注意: chroot の直後に (ルートディレクトリに chdir する) chdir("/") するのはセキュリティ上の良い習慣です。

Portability issues: "chroot" in perlport.

移植性の問題: "chroot" in perlport

close FILEHANDLE
close

Closes the file or pipe associated with the filehandle, flushes the IO buffers, and closes the system file descriptor. Returns true if those operations succeed and if no error was reported by any PerlIO layer. Closes the currently selected filehandle if the argument is omitted.

FILEHANDLE に対応したファイルまたはパイプをクローズして、 IO バッファをフラッシュし、システムファイル記述子をクローズします。 操作が成功し、PerlIO 層からエラーが報告されなかった場合に真を返します。 引数が省略された場合、現在選択されているファイルハンドルをクローズします。

You don't have to close FILEHANDLE if you are immediately going to do another open on it, because open closes it for you. (See open.) However, an explicit close on an input file resets the line counter ($.), while the implicit close done by open does not.

クローズしてすぐにまた、同じファイルハンドルに対してオープンを行なう 場合には、open が自動的に close を行ないますので、 close FILEHANDLE する必要はありません。 (open を参照してください。) ただし、明示的にクローズを行なったときにのみ入力ファイルの 行番号 ($.) のリセットが行なわれ、 open によって行なわれる 暗黙の close では行なわれません。

If the filehandle came from a piped open, close returns false if one of the other syscalls involved fails or if its program exits with non-zero status. If the only problem was that the program exited non-zero, $! will be set to 0. Closing a pipe also waits for the process executing on the pipe to exit--in case you wish to look at the output of the pipe afterwards--and implicitly puts the exit status value of that command into $? and ${^CHILD_ERROR_NATIVE}.

ファイルハンドルがパイプつきオープンなら、close は その他のシステムコールが失敗したりプログラムが非ゼロのステータスで終了した 場合にも偽を返します。 プログラムが非ゼロで終了しただけの場合は、$!0 に セットされます。 後でパイプの出力を見たい場合のために、パイプのクローズでは、パイプ上で 実行されているプロセスの終了を待ち、また自動的にコマンドのステータス値を $?${^CHILD_ERROR_NATIVE} に設定します。

If there are multiple threads running, close on a filehandle from a piped open returns true without waiting for the child process to terminate, if the filehandle is still open in another thread.

複数のスレッドがある場合、パイプで開かれたファイルハンドルに対する close は、そのファイルハンドルが他のスレッドで まだ開かれている場合、子プロセスの終了を待たずに真を返します。

Closing the read end of a pipe before the process writing to it at the other end is done writing results in the writer receiving a SIGPIPE. If the other end can't handle that, be sure to read all the data before closing the pipe.

書き込み側が閉じる前に途中でパイプの読み込み側が閉じた場合、 書き込み側に SIGPIPE が配送されます。 書き込み側がこれを扱えない場合、パイプを閉じる前に 確実に全てのデータが読み込まれるようにする必要があります。

Example:

例:

    open(OUTPUT, '|sort >foo')  # pipe to sort
        or die "Can't start sort: $!";
    #...                        # print stuff to output
    close OUTPUT                # wait for sort to finish
        or warn $! ? "Error closing sort pipe: $!"
                   : "Exit status $? from sort";
    open(INPUT, 'foo')          # get sort's results
        or die "Can't open 'foo' for input: $!";

FILEHANDLE may be an expression whose value can be used as an indirect filehandle, usually the real filehandle name or an autovivified handle.

FILEHANDLE は式でもかまいません; この場合、値は間接ファイルハンドルと して扱われ、普通は実際のファイルハンドル名か自動有効化されたハンドルです。

closedir DIRHANDLE

Closes a directory opened by opendir and returns the success of that system call.

opendir でオープンしたディレクトリをクローズし、 システムコールの返り値を返します。

connect SOCKET,NAME

Attempts to connect to a remote socket, just like connect(2). Returns true if it succeeded, false otherwise. NAME should be a packed address of the appropriate type for the socket. See the examples in "Sockets: Client/Server Communication" in perlipc.

connect(2) システムコールと同様に、リモートソケットへの接続を試みます。 成功時には真を、さもなければ偽を返します。 NAME は、ソケットに対する、適切な型のパックされた アドレスでなければなりません。 "Sockets: Client/Server Communication" in perlipc の例を参照してください。

continue BLOCK
continue

When followed by a BLOCK, continue is actually a flow control statement rather than a function. If there is a continue BLOCK attached to a BLOCK (typically in a while or foreach), it is always executed just before the conditional is about to be evaluated again, just like the third part of a for loop in C. Thus it can be used to increment a loop variable, even when the loop has been continued via the next statement (which is similar to the C continue statement).

BLOCK が引き続く場合、continue は実際には関数ではなく、 実行制御文です。 continue BLOCK が BLOCK (典型的には while または foreach の中)にあると、これは条件文が再評価される直前に常に実行されます; これは C における for ループの 3 番目の部分と同様です。 従って、これは next 文 (これは C の continue 文と似ています) を使って ループが繰り返されるときでもループ変数を増やしたいときに使えます。

last, next, or redo may appear within a continue block; last and redo behave as if they had been executed within the main block. So will next, but since it will execute a continue block, it may be more entertaining.

last, next, redocontinue ブロック内に現れる可能性があります; lastredo はメインブロックの中で 実行されたのと同じように振舞います。 next の場合は、continue ブロックを 実行することになるので、より面白いことになります。

    while (EXPR) {
        ### redo always comes here
        do_something;
    } continue {
        ### next always comes here
        do_something_else;
        # then back the top to re-check EXPR
    }
    ### last always comes here

Omitting the continue section is equivalent to using an empty one, logically enough, so next goes directly back to check the condition at the top of the loop.

continue 節を省略するのは、空の節を指定したのと同じで、 論理的には十分なので、この場合、next は直接ループ先頭の 条件チェックに戻ります。

When there is no BLOCK, continue is a function that falls through the current when or default block instead of iterating a dynamically enclosing foreach or exiting a lexically enclosing given. In Perl 5.14 and earlier, this form of continue was only available when the "switch" feature was enabled. See feature and "Switch Statements" in perlsyn for more information.

BLOCK がなければ、continue は動的に囲まれた foreach や レキシカルに囲まれた given で反復するのではなく、現在の when または default のブロックを通り抜けるための文です。 Perl 5.14 以前では、この形式の continue"switch" 機能 が有効の場合にのみ 利用可能です。 さらなる情報については feature"Switch Statements" in perlsyn を 参照してください。

cos EXPR
cos

Returns the cosine of EXPR (expressed in radians). If EXPR is omitted, takes the cosine of $_.

(ラジアンで示した) EXPR の余弦を返します。 EXPR が省略されたときには、$_ の余弦を取ります。

For the inverse cosine operation, you may use the Math::Trig::acos function, or use this relation:

逆余弦を求めるためには、Math::Trig::acos 関数を使うか、 以下の関係を使ってください。

    sub acos { atan2( sqrt(1 - $_[0] * $_[0]), $_[0] ) }
crypt PLAINTEXT,SALT

Creates a digest string exactly like the crypt(3) function in the C library (assuming that you actually have a version there that has not been extirpated as a potential munition).

C ライブラリの crypt(3) 関数と全く同じように、ダイジェスト文字列を 作成します(一時的な必需品として、まだ絶滅していないバージョンを 持っていると仮定しています)。

crypt is a one-way hash function. The PLAINTEXT and SALT are turned into a short string, called a digest, which is returned. The same PLAINTEXT and SALT will always return the same string, but there is no (known) way to get the original PLAINTEXT from the hash. Small changes in the PLAINTEXT or SALT will result in large changes in the digest.

crypt は一方向ハッシュ関数です。 PLAINTEXT と SALT はダイジェストと呼ばれる短い文字列に変えられて、 それが返されます。 PLAINTEXT と SALT が同じ場合は常に同じ文字列を返しますが、ハッシュから 元の PLAINTEXT を得る(既知の)方法はありません。 PLAINTEXT や SALT を少し変更してもダイジェストは大きく変更されます。

There is no decrypt function. This function isn't all that useful for cryptography (for that, look for Crypt modules on your nearby CPAN mirror) and the name "crypt" is a bit of a misnomer. Instead it is primarily used to check if two pieces of text are the same without having to transmit or store the text itself. An example is checking if a correct password is given. The digest of the password is stored, not the password itself. The user types in a password that is crypt'd with the same salt as the stored digest. If the two digests match, the password is correct.

復号化関数はありません。 この関数は暗号化のためにはまったく役に立ちません(このためには、 お近くの CPAN ミラーで Crypt モジュールを探してください)ので、 "crypt" という名前は少し間違った名前です。 その代わりに、一般的には二つのテキスト片が同じかどうかをテキストそのものを 転送したり保管したりせずにチェックするために使います。 例としては、正しいパスワードが与えられたかどうかをチェックがあります。 パスワード自身ではなく、パスワードのダイジェストが保管されます。 ユーザーがパスワードを入力すると、保管されているダイジェストと同じ salt で crypt します。 二つのダイジェストが同じなら、パスワードは正しいです。

When verifying an existing digest string you should use the digest as the salt (like crypt($plain, $digest) eq $digest). The SALT used to create the digest is visible as part of the digest. This ensures crypt will hash the new string with the same salt as the digest. This allows your code to work with the standard crypt and with more exotic implementations. In other words, assume nothing about the returned string itself nor about how many bytes of SALT may matter.

すでにあるダイジェスト文字列を検証するには、ダイジェストを (crypt($plain, $digest) eq $digest のようにして)salt として使います。 ダイジェストを作るのに使われた SALT はダイジェストの一部として見えます。 これにより、crypt は同じ salt で新しい文字列を ダイジェストとしてハッシュ化できるようにします。 これによって標準的な crypt や、より風変わりな 実装でも動作します。 言い換えると、返される文字列や、SALT が何バイトあるかといったことに対して、 どのような仮定もしてはいけません。

Traditionally the result is a string of 13 bytes: two first bytes of the salt, followed by 11 bytes from the set [./0-9A-Za-z], and only the first eight bytes of PLAINTEXT mattered. But alternative hashing schemes (like MD5), higher level security schemes (like C2), and implementations on non-Unix platforms may produce different strings.

伝統的には結果は 13 バイトの文字列です: 最初の 2 バイトは salt、引き続いて 集合 [./0-9A-Za-z] からの 11 バイトで、PLAINTEXT の最初の 8 バイトだけが意味があります。 しかし、(MD5 のように) 異なったハッシュ手法、 (C2 のような) 高レベルセキュリティ手法、非 Unix プラットフォームでの 実装などでは異なった文字列が生成されることがあります。

When choosing a new salt create a random two character string whose characters come from the set [./0-9A-Za-z] (like join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64]). This set of characters is just a recommendation; the characters allowed in the salt depend solely on your system's crypt library, and Perl can't restrict what salts crypt accepts.

新しい salt を選択する場合は、集合 [./0-9A-Za-z] から (join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64] の ようにして)ランダムに2 つの文字を選びます。 この文字集合は単なる推薦です; salt として許される文字はシステムの暗号化 ライブラリだけに依存し、Perl は crypt が どのような salt を受け付けるかについて制限しません。

Here's an example that makes sure that whoever runs this program knows their password:

プログラムを実行する人が、 自分のパスワードを知っていることを確認する例です:

    my $pwd = (getpwuid($<))[1];

    system "stty -echo";
    print "Password: ";
    chomp(my $word = <STDIN>);
    print "\n";
    system "stty echo";

    if (crypt($word, $pwd) ne $pwd) {
        die "Sorry...\n";
    } else {
        print "ok\n";
    }

Of course, typing in your own password to whoever asks you for it is unwise.

もちろん、自分自身のパスワードを誰にでも入力するのは賢明ではありません。

The crypt function is unsuitable for hashing large quantities of data, not least of all because you can't get the information back. Look at the Digest module for more robust algorithms.

crypt 関数は大量のデータのハッシュ化には 向いていません; これは情報を戻せないという理由だけではありません。 より頑強なアルゴリズムについては Digest モジュールを参照してください。

If using crypt on a Unicode string (which potentially has characters with codepoints above 255), Perl tries to make sense of the situation by trying to downgrade (a copy of) the string back to an eight-bit byte string before calling crypt (on that copy). If that works, good. If not, crypt dies with Wide character in crypt.

Unicode 文字列(潜在的には 255 を越えるコードポイントを持つ文字を 含みます)に crypt を使った場合、Perl は crypt を呼び出す前に与えられた 文字列を8 ビットバイト文字列にダウングレードする(文字列のコピーを作る) ことで状況のつじつまを合わせようとします。 うまく動けば、それでよし。 動かなければ、cryptWide character in crypt という メッセージと共に die します。

Portability issues: "crypt" in perlport.

移植性の問題: "crypt" in perlport

dbmclose HASH

[This function has been largely superseded by the untie function.]

[この関数は、untie 関数に大きくとって代わられました。]

Breaks the binding between a DBM file and a hash.

DBM ファイルとハッシュの連結をはずします。

Portability issues: "dbmclose" in perlport.

移植性の問題: "dbmclose" in perlport

dbmopen HASH,DBNAME,MASK

[This function has been largely superseded by the tie function.]

[この関数は、tie 関数に 大きくとって代わられました。]

This binds a dbm(3), ndbm(3), sdbm(3), gdbm(3), or Berkeley DB file to a hash. HASH is the name of the hash. (Unlike normal open, the first argument is not a filehandle, even though it looks like one). DBNAME is the name of the database (without the .dir or .pag extension if any). If the database does not exist, it is created with protection specified by MASK (as modified by the umask). To prevent creation of the database if it doesn't exist, you may specify a MODE of 0, and the function will return a false value if it can't find an existing database. If your system supports only the older DBM functions, you may make only one dbmopen call in your program. In older versions of Perl, if your system had neither DBM nor ndbm, calling dbmopen produced a fatal error; it now falls back to sdbm(3).

dbm(3), ndbm(3), sdbm(3), gdbm(3) ファイルまたは Berkeley DB ファイルを連想配列に結び付けます。 HASH は、その連想配列の名前です。 (普通の open とは違って、最初の引数は ファイルハンドル ではありません; まあ、似たようなものですが)。 DBNAME は、データベースの名前です (拡張子の .dir や .pag はもしあっても つけません)。 データベースが存在しなければ、MODE MASK (を umask で 修正したもの) で指定されたモードで作られます。 存在しないときにデータベースを作成しないようにするには、MODE に 0 を 設定でき、データベースを見つけられなかった場合は関数は偽を返します。 古い DBM 関数のみをサポートしているシステムでは、プログラム中で 1 度だけ dbmopen を実行することができます。 昔のバージョンの Perl では、DBM も ndbm も持っていないシステムでは、 dbmopen を呼び出すと致命的エラーになります; 現在では sdbm(3) にフォールバックします。

If you don't have write access to the DBM file, you can only read hash variables, not set them. If you want to test whether you can write, either use file tests or try setting a dummy hash entry inside an eval to trap the error.

DBM ファイルに対して、書き込み権が無いときには、ハッシュ 配列を読みだすことだけができ、設定することはできません。 書けるか否かを調べたい場合には、ファイルテスト 演算子を使うか、エラーをトラップするための eval の中で、 ダミーのハッシュエントリを設定してみることになります。

Note that functions such as keys and values may return huge lists when used on large DBM files. You may prefer to use the each function to iterate over large DBM files. Example:

大きな DBM ファイルを扱うときには、keysvalues のような関数は、巨大なリストを返します。 大きな DBM ファイルでは、each 関数を使って繰り返しを 行なった方が良いかもしれません。 例:

    # print out history file offsets
    dbmopen(%HIST,'/usr/lib/news/history',0666);
    while (($key,$val) = each %HIST) {
        print $key, ' = ', unpack('L',$val), "\n";
    }
    dbmclose(%HIST);

See also AnyDBM_File for a more general description of the pros and cons of the various dbm approaches, as well as DB_File for a particularly rich implementation.

様々な dbm 手法に対する利点欠点に関するより一般的な記述および 特にリッチな実装である DB_File に関しては AnyDBM_File も参照してください。

You can control which DBM library you use by loading that library before you call dbmopen:

dbmopen を呼び出す前にライブラリを 読み込むことで、どの DBM ライブラリを使うかを制御できます:

    use DB_File;
    dbmopen(%NS_Hist, "$ENV{HOME}/.netscape/history.db")
        or die "Can't open netscape history file: $!";

Portability issues: "dbmopen" in perlport.

移植性の問題: "dbmopen" in perlport

defined EXPR
defined

Returns a Boolean value telling whether EXPR has a value other than the undefined value undef. If EXPR is not present, $_ is checked.

左辺値 EXPR が未定義値 undef 以外の値を持つか否かを示す、 ブール値を返します。 EXPR がない場合は、$_ がチェックされます。

Many operations return undef to indicate failure, end of file, system error, uninitialized variable, and other exceptional conditions. This function allows you to distinguish undef from other values. (A simple Boolean test will not distinguish among undef, zero, the empty string, and "0", which are all equally false.) Note that since undef is a valid scalar, its presence doesn't necessarily indicate an exceptional condition: pop returns undef when its argument is an empty array, or when the element to return happens to be undef.

多くの演算子が、EOF や未初期化変数、システムエラーといった、 例外的な条件で undef を返すようになっています。 この関数は、他の値と undef とを区別するために使えます。 (単純な真偽値テストでは、undef、0、"0" のいずれも偽を 返すので、区別することができません。) undef は有効なスカラ値なので、その存在が 必ずしも 例外的な状況を表すとは限らないということに注意してください: pop は引数が空の配列だったときに undef を 返しますが、あるいは 返すべき要素がたまたま undef だったのかもしれません。

You may also use defined(&func) to check whether subroutine func has ever been defined. The return value is unaffected by any forward declarations of func. A subroutine that is not defined may still be callable: its package may have an AUTOLOAD method that makes it spring into existence the first time that it is called; see perlsub.

defined(&func) とすることでサブルーチン func の存在を、 確かめることもできます。 返り値は func の前方定義には影響されません。 定義されていないサブルーチンも呼び出し可能です: 最初に呼び出されたときに存在するようにするための AUTOLOAD メソッドを持ったパッケージかもしれません; perlsub を参照してください。

Use of defined on aggregates (hashes and arrays) is no longer supported. It used to report whether memory for that aggregate had ever been allocated. You should instead use a simple test for size:

集合(ハッシュや配列)への defined の使用は もはや対応していません。 これはその集合にメモリが割り当てられたかを報告するのに用いられていました。 代わりにサイズに対する簡単なテストを使うべきです。

    if (@an_array) { print "has array elements\n" }
    if (%a_hash)   { print "has hash members\n"   }

When used on a hash element, it tells you whether the value is defined, not whether the key exists in the hash. Use exists for the latter purpose.

ハッシュの要素に対して用いると、value が定義されているか否かを 返すものであって、ハッシュに key が存在するか否かを返すのではありません。 この用途には、exists を使ってください。

Examples:

例:

    print if defined $switch{D};
    print "$val\n" while defined($val = pop(@ary));
    die "Can't readlink $sym: $!"
        unless defined($value = readlink $sym);
    sub foo { defined &$bar ? $bar->(@_) : die "No bar"; }
    $debugging = 0 unless defined $debugging;

Note: Many folks tend to overuse defined and are then surprised to discover that the number 0 and "" (the zero-length string) are, in fact, defined values. For example, if you say

注意: 多くの人々が defined を使いすぎて、0""(空文字列) が実際のところ定義された値であることに驚くようです。 例えば、以下のように書くと:

    "ab" =~ /a(.*)b/;

The pattern match succeeds and $1 is defined, although it matched "nothing". It didn't really fail to match anything. Rather, it matched something that happened to be zero characters long. This is all very above-board and honest. When a function returns an undefined value, it's an admission that it couldn't give you an honest answer. So you should use defined only when questioning the integrity of what you're trying to do. At other times, a simple comparison to 0 or "" is what you want.

パターンマッチングが成功し、$1 が定義されても、実際には 「なし」にマッチしています。 しかしこれは何にもマッチしていないわけではありません。 何かにはマッチしているのですが、たまたまそれが長さ 0 だっただけです。 これは非常に率直で正直なことです。 関数が未定義値を返すとき、正直な答えを返すことができないことを 告白しています。 ですので、あなたが自分がしようとしていることの完全性を確認するときにだけ defined を使うべきです。 その他の場合では、単に 0 または "" と比較するというのがあなたの 求めているものです。

See also undef, exists, ref.

undef, exists, ref も 参照してください。

delete EXPR

Given an expression that specifies an element or slice of a hash, delete deletes the specified elements from that hash so that exists on that element no longer returns true. Setting a hash element to the undefined value does not remove its key, but deleting it does; see exists.

ハッシュの要素やスライスを指定する式を取り、delete は 指定された要素をハッシュから削除するので、 その要素に対する exists はもはや真を返さなくなります。 ハッシュ要素に未定義値をセットしてもそのキーは削除されませんが、 delete では削除されます; exists を参照してください。

In list context, usually returns the value or values deleted, or the last such element in scalar context. The return list's length corresponds to that of the argument list: deleting non-existent elements returns the undefined value in their corresponding positions. When a key/value hash slice is passed to delete, the return value is a list of key/value pairs (two elements for each item deleted from the hash).

リストコンテキストでは通常は削除された要素を返し、スカラコンテキストでは 削除された要素のうち最後のものを返します。 返されたリストの長さは常に引数リストの長さに対応します: 存在しない要素を削除すると、対応する位置に未定義値をセットして返します。 キー/値ハッシュスライスdelete に渡されると、返り値はキー/値の組(それぞれのアイテムについて 二つの要素が元のハッシュから削除されたもの)です。

delete may also be used on arrays and array slices, but its behavior is less straightforward. Although exists will return false for deleted entries, deleting array elements never changes indices of existing values; use shift or splice for that. However, if any deleted elements fall at the end of an array, the array's size shrinks to the position of the highest element that still tests true for exists, or to 0 if none do. In other words, an array won't have trailing nonexistent elements after a delete.

delete は配列や配列のスライスに対しても使えますが、その 振る舞いはあまり直感的ではありません。 削除されたエントリに対しては exists は偽を返しますが、 配列要素を削除しても、存在する値の添え字は変わりません; このためには shiftsplice を 使ってください。 しかし、削除された要素が配列の末尾であった場合、配列のサイズは exists が真となる最大位置の要素(それがない場合は 0)に 切り詰められます。 言い換えると、delete の後には配列の末尾に値のない要素はありません。

WARNING: Calling delete on array values is strongly discouraged. The notion of deleting or checking the existence of Perl array elements is not conceptually coherent, and can lead to surprising behavior.

警告: 配列の値に対して delete を呼び出すことは強く 非推奨です。 Perl の配列要素を削除したり存在を調べたりする記法は概念的に一貫しておらず、 驚くべき振る舞いを引き起こすことがあります。

Deleting from %ENV modifies the environment. Deleting from a hash tied to a DBM file deletes the entry from the DBM file. Deleting from a tied hash or array may not necessarily return anything; it depends on the implementation of the tied package's DELETE method, which may do whatever it pleases.

%ENV から削除を行なうと、実際に環境変数を変更します。 DBM ファイルに tie された配列からの削除は、その DBM ファイルからエントリを 削除します。 しかし、tie されたハッシュや配列からの 削除は、値を返すとは限りません; これは tie されたパッケージの DELETE メソッドの実装に依存するので、どんなことでも起こります。

The delete local EXPR construct localizes the deletion to the current block at run time. Until the block exits, elements locally deleted temporarily no longer exist. See "Localized deletion of elements of composite types" in perlsub.

delete local EXPR 構文は、現在のブロックの削除を実行時にローカル化します。 ブロックから出るまで、ローカルで削除された要素は存在しなくなります。 "Localized deletion of elements of composite types" in perlsub を 参照してください。

    my %hash = (foo => 11, bar => 22, baz => 33);
    my $scalar = delete $hash{foo};         # $scalar is 11
    $scalar = delete @hash{qw(foo bar)}; # $scalar is 22
    my @array  = delete @hash{qw(foo baz)}; # @array  is (undef,33)

The following (inefficiently) deletes all the values of %HASH and @ARRAY:

以下は、%HASH と @ARRAY のすべての値を(非効率的に)削除します:

    foreach my $key (keys %HASH) {
        delete $HASH{$key};
    }

    foreach my $index (0 .. $#ARRAY) {
        delete $ARRAY[$index];
    }

And so do these:

そして以下のようにもできます:

    delete @HASH{keys %HASH};

    delete @ARRAY[0 .. $#ARRAY];

But both are slower than assigning the empty list or undefining %HASH or @ARRAY, which is the customary way to empty out an aggregate:

しかし、これら二つは両方とも、構造を空にするための慣習的な方法である、 単に空リストを代入するか、%HASH や @ARRAY を undef するより遅いです:

    %HASH = ();     # completely empty %HASH
    undef %HASH;    # forget %HASH ever existed

    @ARRAY = ();    # completely empty @ARRAY
    undef @ARRAY;   # forget @ARRAY ever existed

The EXPR can be arbitrarily complicated provided its final operation is an element or slice of an aggregate:

最終的な操作が集合の要素かスライスである限りは、 いずれかである限りは、EXPR には任意の複雑な式を置くことができます:

    delete $ref->[$x][$y]{$key};
    delete @{$ref->[$x][$y]}{$key1, $key2, @morekeys};

    delete $ref->[$x][$y][$index];
    delete @{$ref->[$x][$y]}[$index1, $index2, @moreindices];
die LIST

die raises an exception. Inside an eval the exception is stuffed into $@ and the eval is terminated with the undefined value. If the exception is outside of all enclosing evals, then the uncaught exception is printed to STDERR and perl exits with an exit code indicating failure. If you need to exit the process with a specific exit code, see exit.

die は例外を発生させます。 eval の中で使用すると、例外が $@ に入り、eval は 未定義値を返して終了します。 例外が全ての eval の外側の場合は、捕捉されなかった例外は STDERR に表示され、perl は失敗を示す終了コードで終了します。 特定の終了コードでプロセスを終了させる必要がある場合は、 exit を参照してください。

Equivalent examples:

等価な例:

    die "Can't cd to spool: $!\n" unless chdir '/usr/spool/news';
    chdir '/usr/spool/news' or die "Can't cd to spool: $!\n"

Most of the time, die is called with a string to use as the exception. You may either give a single non-reference operand to serve as the exception, or a list of two or more items, which will be stringified and concatenated to make the exception.

ほとんどの場合、die は例外として使うための文字列と共に呼び出されます。 例外として圧から割れる単一の非リファレンスオペランドか、 例外を作るために文字列化されて連結される、二つ以上のアイテムのリストを 指定することができます。

If the string exception does not end in a newline, the current script line number and input line number (if any) and a newline are appended to it. Note that the "input line number" (also known as "chunk") is subject to whatever notion of "line" happens to be currently in effect, and is also available as the special variable $.. See "$/" in perlvar and "$." in perlvar.

文字列例外が改行で終わっていなければ、その時点のスクリプト名と スクリプトの行番号、(もしあれば) 入力ファイルの行番号と改行文字が それに追加されます。 「入力行番号」("chunk" とも呼ばれます)は「行」という概念が現在有効であると 仮定しています; また特殊変数 $. でも利用可能です。 "$/" in perlvar"$." in perlvar も参照してください。

Hint: sometimes appending ", stopped" to your message will cause it to make better sense when the string "at foo line 123" is appended. Suppose you are running script "canasta".

ヒント: メッセージの最後を ", stopped" のようなもので 終わるようにしておけば、"at foo line 123" のように 追加されて、わかりやすくなります。 "canasta" というスクリプトを実行しているとします。

    die "/etc/games is no good";
    die "/etc/games is no good, stopped";

produce, respectively

これは、それぞれ以下のように表示します。

    /etc/games is no good at canasta line 123.
    /etc/games is no good, stopped at canasta line 123.

If LIST was empty or made an empty string, and $@ already contains an exception value (typically from a previous eval), then that value is reused after appending "\t...propagated". This is useful for propagating exceptions:

出力が空か空文字列を作り、$@ が (典型的には前回の eval で) 既に例外値を持っている場合、 値は "\t...propagated" を追加した後再利用されます。 これは例外を伝播させる場合に有効です:

    eval { ... };
    die unless $@ =~ /Expected exception/;

If LIST was empty or made an empty string, and $@ contains an object reference that has a PROPAGATE method, that method will be called with additional file and line number parameters. The return value replaces the value in $@; i.e., as if $@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; were called.

出力が空か空文字列を作り、$@PROPAGATE メソッドを 含むオブジェクトへのリファレンスを含む場合、 このメソッドが追加ファイルと行番号を引数として呼び出されます。 返り値は $@ の値を置き換えます; つまり、$@ = eval { $@->PROPAGATE(__FILE__, __LINE__) }; が 呼び出されたかのようになります。

If LIST was empty or made an empty string, and $@ is also empty, then the string "Died" is used.

LIST が空か空文字列を作り、$@ も空の場合、 "Died" が使われます。

You can also call die with a reference argument, and if this is trapped within an eval, $@ contains that reference. This permits more elaborate exception handling using objects that maintain arbitrary state about the exception. Such a scheme is sometimes preferable to matching particular string values of $@ with regular expressions.

die はリファレンス引数と共に呼び出すこともでき、これが eval 内部でトラップされた場合、$@ は そのリファレンスを持ちます。 これは、例外の性質について任意の状態を管理するオブジェクトを使った より複雑な例外処理の実装を可能にします。 このようなスキームは $@ の特定の文字列値を正規表現を使って マッチングするときに時々好まれます。

Because Perl stringifies uncaught exception messages before display, you'll probably want to overload stringification operations on exception objects. See overload for details about that. The stringified message should be non-empty, and should end in a newline, in order to fit in with the treatment of string exceptions. Also, because an exception object reference cannot be stringified without destroying it, Perl doesn't attempt to append location or other information to a reference exception. If you want location information with a complex exception object, you'll have to arrange to put the location information into the object yourself.

perl は捕らえられなかった例外のメッセージを表示する前に文字列化するので、 このようなカスタム例外オブジェクトの文字列化をオーバーロードしたいと 思うかもしれません。 これに関する詳細は overload を参照してください。 文字列化されたメッセージは、文字列例外の扱いに合わせるために、 空ではなく、末尾は改行であるべきです。 また、例外オブジェクトリファレンスはそれを破壊することなく 文字列化することができないので、Perl はリファレンス例外に位置や その他の情報を追加しようとしません。 複雑な例外オブジェクトに位置情報が欲しい場合、 オブジェクト自身に位置情報を設定するように用意する必要があります。

Because $@ is a global variable, be careful that analyzing an exception caught by eval doesn't replace the reference in the global variable. It's easiest to make a local copy of the reference before any manipulations. Here's an example:

$@ はグローバル変数なので、 eval により補足された例外の解析はグローバル変数の リファレンスを置き換えないことに注意を払わなければなりません。 他の操作をする前にリファレンスのローカルコピーを 作るのが一番簡単です。 以下に例を示します:

    use Scalar::Util "blessed";

    eval { ... ; die Some::Module::Exception->new( FOO => "bar" ) };
    if (my $ev_err = $@) {
        if (blessed($ev_err)
            && $ev_err->isa("Some::Module::Exception")) {
            # handle Some::Module::Exception
        }
        else {
            # handle all other possible exceptions
        }
    }

If an uncaught exception results in interpreter exit, the exit code is determined from the values of $! and $? with this pseudocode:

例外が捕捉されないとインタプリタは終了し、終了コードは以下の 擬似コードのように、$!$? の値から 決定されます:

    exit $! if $!;              # errno
    exit $? >> 8 if $? >> 8;    # child exit status
    exit 255;                   # last resort

As with exit, $? is set prior to unwinding the call stack; any DESTROY or END handlers can then alter this value, and thus Perl's exit code.

exit と同様に、コールスタックを巻き戻す前に $? が設定されます; DESTROYEND のハンドラが それからこの値を変更して、これが Perl の終了コードになります。

The intent is to squeeze as much possible information about the likely cause into the limited space of the system exit code. However, as $! is the value of C's errno, which can be set by any system call, this means that the value of the exit code used by die can be non-predictable, so should not be relied upon, other than to be non-zero.

この意図は、できるだけ多くの似たような原因に関する情報を、システム終了 コードという限られた領域に圧縮することです。 しかし、$! はシステムコールによって設定される可能性がある C の errno の値であり、die によって使われる終了コードの値は 予測不能であることを意味するので、非 0 ということ以上にこの値に 依存するべきではありません。

You can arrange for a callback to be run just before the die does its deed, by setting the $SIG{__DIE__} hook. The associated handler is called with the exception as an argument, and can change the exception, if it sees fit, by calling die again. See "%SIG" in perlvar for details on setting %SIG entries, and eval for some examples. Although this feature was to be run only right before your program was to exit, this is not currently so: the $SIG{__DIE__} hook is currently called even inside evaled blocks/strings! If one wants the hook to do nothing in such situations, put

$SIG{__DIE__} フックをセットすることで、 die がその行動を行う 直前に実行されるコールバックを設定できます。 結び付けられたハンドラは例外を引数として呼び出され、 必要なら再び die を呼び出すことで例外を変更できます。 %SIG のエントリをセットする詳細については、 "%SIG" in perlvar を、例については eval を参照してください。 この機能はプログラムが終了しようとする前に 1 回だけ実行していましたが、 現在ではそうではありません: $SIG{__DIE__} フックは eval された ブロック/文字列の中でも呼ばれるのです! もしそのような状況で何もしなくない時は:

    die @_ if $^S;

as the first line of the handler (see "$^S" in perlvar). Because this promotes strange action at a distance, this counterintuitive behavior may be fixed in a future release.

をハンドラの最初の行に置いてください("$^S" in perlvar を参照してください)。 これは離れたところで不思議な行動を引き起こすので、 この直感的でない振る舞いは将来のリリースで修正されるかもしれません。

See also exit, warn, and the Carp module.

exitwarnCarp モジュールも 参照してください。

do BLOCK

Not really a function. Returns the value of the last command in the sequence of commands indicated by BLOCK. When modified by the while or until loop modifier, executes the BLOCK once before testing the loop condition. (On other statements the loop modifiers test the conditional first.)

実際は関数ではありません。 BLOCK で示されるコマンド列の最後の値を返します。 whileuntil ループ修飾子で修飾すると、 ループ条件を調べる前に 1 度、BLOCK を実行します。 (これ以外の実行文は、ループ修飾子により、条件が最初に 調べられます。)

do BLOCK does not count as a loop, so the loop control statements next, last, or redo cannot be used to leave or restart the block. See perlsyn for alternative strategies.

do BLOCK はループとしては 扱われません; 従って、next, last,redo といったループ制御文は ブロックから抜けたり再開することはできません。 その他の戦略については perlsyn を参照してください。

do EXPR

Uses the value of EXPR as a filename and executes the contents of the file as a Perl script:

EXPR の値をファイル名として用い、そのファイルの中身を Perl のスクリプトとして実行します:

    # load the exact specified file (./ and ../ special-cased)
    do '/foo/stat.pl';
    do './stat.pl';
    do '../foo/stat.pl';

    # search for the named file within @INC
    do 'stat.pl';
    do 'foo/stat.pl';

do './stat.pl' is largely like

do './stat.pl' はだいたい以下のものと同じようなものですが、

    eval `cat stat.pl`;

except that it's more concise, runs no external processes, and keeps track of the current filename for error messages. It also differs in that code evaluated with do FILE cannot see lexicals in the enclosing scope; eval STRING does. It's the same, however, in that it does reparse the file every time you call it, so you probably don't want to do this inside a loop.

より簡潔で、外部プログラムを起動せず、エラーメッセージでファイル名がわかる、 といったことがあります。 do FILE で評価されたコードは、入れ子のスコープにある レキシカル変数を見ることができないのに対し、eval STRINGではできる、 という違いがあります。 しかし、呼び出すたびにファイルを解析し直すという点では同じですから、 ループ内でこれを使おうなどとは、間違っても思ったりしないように。

Using do with a relative path (except for ./ and ../), like

次のように、do に (./../ 以外の) 相対パスを使うと:

    do 'foo/stat.pl';

will search the @INC directories, and update %INC if the file is found. See "@INC" in perlvar and "%INC" in perlvar for these variables. In particular, note that whilst historically @INC contained '.' (the current directory) making these two cases equivalent, that is no longer necessarily the case, as '.' is not included in @INC by default in perl versions 5.26.0 onwards. Instead, perl will now warn:

@INC ディレクトリを検索し、ファイルが見つかれば %INC を更新します。 これらの変数については "@INC" in perlvar"%INC" in perlvar を参照してください。 特に、歴史的には @INC に '.' (カレントディレクトリ) を 含んでいたのでこの二つの場合は等価でしたが、 perl バージョン 5.26.0 以降ではデフォルトでは @INC に '.' を 含んでいないので、もはやそうではないことに注意してください。 代わりに、perl は次のような警告を出します:

    do "stat.pl" failed, '.' is no longer in @INC;
    did you mean do "./stat.pl"?

If do can read the file but cannot compile it, it returns undef and sets an error message in $@. If do cannot read the file, it returns undef and sets $! to the error. Always check $@ first, as compilation could fail in a way that also sets $!. If the file is successfully compiled, do returns the value of the last expression evaluated.

do がファイルを読み込めたがコンパイルできなかった場合、 undef を返して $@ にエラーメッセージを 設定します。 doがファイルを読み込めなかった場合、undef を返して $! にエラーを設定します。 コンパイルに失敗したときにも $! が設定されるので、 常に $@ を先にチェックします。 ファイルのコンパイルに成功した場合、do は最後に評価した表現の 値を返します。

Inclusion of library modules is better done with the use and require operators, which also do automatic error checking and raise an exception if there's a problem.

ライブラリモジュールのインクルードには、 use 演算子や require 演算子を使った方がよいです; これらは自動的にエラーをチェックして、問題があれば例外を発生させます。

You might like to use do to read in a program configuration file. Manual error checking can be done this way:

do をプログラム設定ファイルを読み込むのに 使いたいかもしれません。 手動のエラーチェックは以下のようにして行えます:

    # Read in config files: system first, then user.
    # Beware of using relative pathnames here.
    for $file ("/share/prog/defaults.rc",
               "$ENV{HOME}/.someprogrc")
    {
        unless ($return = do $file) {
            warn "couldn't parse $file: $@" if $@;
            warn "couldn't do $file: $!"    unless defined $return;
            warn "couldn't run $file"       unless $return;
        }
    }
dump LABEL
dump EXPR
dump

This function causes an immediate core dump. See also the -u command-line switch in perlrun, which does the same thing. Primarily this is so that you can use the undump program (not supplied) to turn your core dump into an executable binary after having initialized all your variables at the beginning of the program. When the new binary is executed it will begin by executing a goto LABEL (with all the restrictions that goto suffers). Think of it as a goto with an intervening core dump and reincarnation. If LABEL is omitted, restarts the program from the top. The dump EXPR form, available starting in Perl 5.18.0, allows a name to be computed at run time, being otherwise identical to dump LABEL.

この関数は即座にコアダンプを行ないます。 同様のことを行う perlrun-u オプションも参照してください。 プログラムの先頭で、 すべての変数を初期化したあとのコアダンプを undump プログラム(提供していません)を使って実行ファイルに返ることができます。 この新しいバイナリが実行されると、goto LABEL から始めます (goto に関する制限はすべて適用されます)。 コアダンプをはさんで再生する goto と考えてください。 LABEL が省略されると、プログラムを先頭から再開します。 Perl 5.18.0 から利用可能な dump EXPR 形式では、実行時に計算される 名前が使えます; その他は dump LABEL と同一です。

WARNING: Any files opened at the time of the dump will not be open any more when the program is reincarnated, with possible resulting confusion by Perl.

警告: dump 時点でオープンされていたファイルは、プログラムが 再生されたときには、もはやオープンされて いません; Perl を 混乱させる可能性があります。

This function is now largely obsolete, mostly because it's very hard to convert a core file into an executable. As of Perl 5.30, it must be invoked as CORE::dump().

この関数は大幅に時代遅れのものです; 主な理由としては、コアファイルを 実行形式に変換するのが非常に困難であることです。 Perl 5.30 から、これは CORE::dump() として起動しなければなりません。

Unlike most named operators, this has the same precedence as assignment. It is also exempt from the looks-like-a-function rule, so dump ("foo")."bar" will cause "bar" to be part of the argument to dump.

ほとんどの名前付き演算子と異なり、これは代入と同じ優先順位を持ちます。 また、関数のように見えるものの規則からも免れるので、dump ("foo")."bar" と すると "bar" は dump への引数の一部になります。

Portability issues: "dump" in perlport.

移植性の問題: "dump" in perlport

each HASH
each ARRAY

When called on a hash in list context, returns a 2-element list consisting of the key and value for the next element of a hash. In Perl 5.12 and later only, it will also return the index and value for the next element of an array so that you can iterate over it; older Perls consider this a syntax error. When called in scalar context, returns only the key (not the value) in a hash, or the index in an array.

ハッシュに対してリストコンテキストで呼び出した場合は、次の要素に対する、 ハッシュのキーと値を返します。 Perl 5.12 以降でのみ、配列のインデックスと値からなる 2 要素のリストを返すので、反復を行えます; より古い Perl ではこれは 文法エラーと考えられます。 スカラコンテキストで呼び出した場合は、 ハッシュの場合は(値ではなく)キー、配列の場合はインデックスを返します。

Hash entries are returned in an apparently random order. The actual random order is specific to a given hash; the exact same series of operations on two hashes may result in a different order for each hash. Any insertion into the hash may change the order, as will any deletion, with the exception that the most recent key returned by each or keys may be deleted without changing the order. So long as a given hash is unmodified you may rely on keys, values and each to repeatedly return the same order as each other. See "Algorithmic Complexity Attacks" in perlsec for details on why hash order is randomized. Aside from the guarantees provided here the exact details of Perl's hash algorithm and the hash traversal order are subject to change in any release of Perl.

ハッシュ要素は見かけ上、ランダムな順序で返されます。 実際のランダムな順序はハッシュに固有です; 二つのハッシュに全く同じ一連の 操作を行っても、ハッシュによって異なった順序になります。 ハッシュへの挿入によって順序が変わることがあります; 削除も同様ですが、 each または keys によって返されたもっとも 最近のキーは順序を変えることなく削除できます。 ハッシュが変更されない限り、keys, values, each が繰り返し同じ順序で 返すことに依存してもかまいません。 なぜハッシュの順序がランダム化されているかの詳細については "Algorithmic Complexity Attacks" in perlsec を参照してください。 ここで保証したことを除いて、Perl のハッシュアルゴリズムとハッシュ横断順序の 正確な詳細は Perl のリリースによって変更される可能性があります。

After each has returned all entries from the hash or array, the next call to each returns the empty list in list context and undef in scalar context; the next call following that one restarts iteration. Each hash or array has its own internal iterator, accessed by each, keys, and values. The iterator is implicitly reset when each has reached the end as just described; it can be explicitly reset by calling keys or values on the hash or array, or by referencing the hash (but not array) in list context. If you add or delete a hash's elements while iterating over it, the effect on the iterator is unspecified; for example, entries may be skipped or duplicated--so don't do that. Exception: It is always safe to delete the item most recently returned by each, so the following code works properly:

each がハッシュをすべて読み込んでしまった後、 次の each 呼び出しでは、リストコンテキストでは空リストが 返され、スカラコンテキストでは undef が返されます; そのあと もう一度呼び出すと、再び反復を始めます。 ハッシュや配列毎にそれぞれ反復子があり、eachkeysvalues でアクセスされます。 反復子は、前述したように each が要素をすべて読むことによって 暗黙にリセットされます; また、ハッシュや配列に対して keys, values を呼び出すか、リストコンテキストで (配列ではなく)ハッシュを参照ことで明示的にリセットできます。 繰り返しを行なっている間に、ハッシュに要素を追加したり削除したりすると、 反復子の動作は未定義です; 例えば、要素が飛ばされたり重複したりします-- 従って、してはいけません。 例外: 一番最近に each から返されたものを削除するのは常に 安全です; これは以下のようなコードが正しく動くことを意味します:

    while (my ($key, $value) = each %hash) {
        print $key, "\n";
        delete $hash{$key};   # This is safe
    }

Tied hashes may have a different ordering behaviour to perl's hash implementation.

tie されたハッシュは、順序に関して Perl のハッシュと異なった振る舞いをします。

The iterator used by each is attached to the hash or array, and is shared between all iteration operations applied to the same hash or array. Thus all uses of each on a single hash or array advance the same iterator location. All uses of each are also subject to having the iterator reset by any use of keys or values on the same hash or array, or by the hash (but not array) being referenced in list context. This makes each-based loops quite fragile: it is easy to arrive at such a loop with the iterator already part way through the object, or to accidentally clobber the iterator state during execution of the loop body. It's easy enough to explicitly reset the iterator before starting a loop, but there is no way to insulate the iterator state used by a loop from the iterator state used by anything else that might execute during the loop body. To avoid these problems, use a foreach loop rather than while-each.

each で使われる反復子はハッシュや配列に付随し、 同じハッシュや配列に適用される全ての反復操作の間で共有されます。 従って、一つのハッシュや配列での each の全ての使用は同じ反復位置を 進めます。 また、全ての each は、同じハッシュまたはキーに対する keysvalues の使用によって、または (リストではなく)ハッシュがリストコンテキストで参照されることによって、 反復子がリセットされることになります。 これは、each を基にしたループをかなり不安定にします: そのようなループが既にオブジェクトを部分的に通りぬけた反復子で行われたり、 ループ本体の実行中に誤って反復子の状態を壊すことは容易です。 ループを始める前に反復子を明示的にリセットするのは十分容易ですが、 ループ本体の間に実行しているかもしれない他の何かによって使われている 反復子の状態から、 ループによって使われている反復子の状態を分離する方法はありません。 これらの問題を避けるには、while-each ではなく foreach ループを使ってください。

This prints out your environment like the printenv(1) program, but in a different order:

これは、printenv(1) プログラムのように環境変数を表示しますが、 順序は異なっています:

    while (my ($key,$value) = each %ENV) {
        print "$key=$value\n";
    }

Starting with Perl 5.14, an experimental feature allowed each to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.

Perl 5.14 から、each がスカラ式を取ることが出来るという 実験的機能がありました。 この実験は失敗と見なされ、Perl 5.24 で削除されました。

As of Perl 5.18 you can use a bare each in a while loop, which will set $_ on every iteration. If either an each expression or an explicit assignment of an each expression to a scalar is used as a while/for condition, then the condition actually tests for definedness of the expression's value, not for its regular truth value.

Perl 5.18 から while ループの中に裸の each を書けます; これは繰り返し毎に $_ を設定します。 each 式または each 式からスカラへの明示的な代入が while/for の条件部として使われた場合、 条件は通常の真の値かどうかではなく、式の値が定義されているかどうかを テストします。

    while (each %ENV) {
        print "$_=$ENV{$_}\n";
    }

To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work only on Perls of a recent vintage:

あなたのコードを以前のバージョンの Perl で実行したユーザーが不思議な 文法エラーで混乱することを避けるために、コードが最近のバージョンの Perl で のみ 動作することを示すためにファイルの先頭に以下のようなことを 書いてください:

    use 5.012;  # so keys/values/each work on arrays
    use 5.018;  # so each assigns to $_ in a lone while test

See also keys, values, and sort.

keysvaluessort も参照してください。

eof FILEHANDLE
eof ()
eof

Returns 1 if the next read on FILEHANDLE will return end of file or if FILEHANDLE is not open. FILEHANDLE may be an expression whose value gives the real filehandle. (Note that this function actually reads a character and then ungetcs it, so isn't useful in an interactive context.) Do not read from a terminal file (or call eof(FILEHANDLE) on it) after end-of-file is reached. File types such as terminals may lose the end-of-file condition if you do.

次に FILEHANDLE 上で読み込みを行なったときに、EOF が返されるときか、 または FILEHANDLE がオープンされていないと、1 を返します。 FILEHANDLE は、値が実際のファイルハンドルを示す式であってもかまいません。 (この関数は、実際に文字を読み、ungetc を行ないますので、 対話型の場合には有用ではありません。) 端末ファイルは EOF に達した後にさらに読み込んだり eof(FILEHANDLE) を 呼び出したりしてはいけません。 そのようなことをすると、端末のようなファイルタイプは EOF 状態を失ってしまうかもしれません。

An eof without an argument uses the last file read. Using eof() with empty parentheses is different. It refers to the pseudo file formed from the files listed on the command line and accessed via the <> operator. Since <> isn't explicitly opened, as a normal filehandle is, an eof() before <> has been used will cause @ARGV to be examined to determine if input is available. Similarly, an eof() after <> has returned end-of-file will assume you are processing another @ARGV list, and if you haven't set @ARGV, will read input from STDIN; see "I/O Operators" in perlop.

引数を省略した eof は、最後に読み込みを行なった ファイルを使います。 空の括弧をつけた eof() は異なります。 これはコマンドラインのファイルリストで構成され、<> 演算子経由で アクセスされる擬似ファイルを示すために用いられます。 通常のファイルハンドルと違って <> は明示的にオープンされないので、 <> を使う前に eof() を使うと、 入力が正常か確認するために @ARGV がテストされます。 同様に、<> が EOF を返した後の eof() は、 他の @ARGV リストを処理していると仮定し、もし @ARGV をセットしていないときは STDIN から読み込みます; "I/O Operators" in perlop を参照してください。

In a while (<>) loop, eof or eof(ARGV) can be used to detect the end of each file, whereas eof() will detect the end of the very last file only. Examples:

while (<>) ループの中では、個々のファイルの終わりを調べるには、 eofeof(ARGV) を用いるのに対して eof() は最後のファイルの終わりのみを調べます。 例:

    # reset line numbering on each input file
    while (<>) {
        next if /^\s*#/;  # skip comments
        print "$.\t$_";
    } continue {
        close ARGV if eof;  # Not eof()!
    }

    # insert dashes just before last line of last file
    while (<>) {
        if (eof()) {  # check for end of last file
            print "--------------\n";
        }
        print;
        last if eof();     # needed if we're reading from a terminal
    }

Practical hint: you almost never need to use eof in Perl, because the input operators typically return undef when they run out of data or encounter an error.

現実的なヒント: Perl で eof が必要となることは、 ほとんどありません; 基本的には、データがなくなったときやエラーがあったときに、入力演算子が undef を返してくれるからです。

eval EXPR
eval BLOCK
eval

eval in all its forms is used to execute a little Perl program, trapping any errors encountered so they don't crash the calling program.

どの型式の eval も、小さな Perl のプログラムであるかのように実行され、 遭遇した全てのエラーをトラップするので、呼び出したプログラムが クラッシュすることはありません。

Plain eval with no argument is just eval EXPR, where the expression is understood to be contained in $_. Thus there are only two real eval forms; the one with an EXPR is often called "string eval". In a string eval, the value of the expression (which is itself determined within scalar context) is first parsed, and if there were no errors, executed as a block within the lexical context of the current Perl program. This form is typically used to delay parsing and subsequent execution of the text of EXPR until run time. Note that the value is parsed every time the eval executes.

引数なしの eval は単に eval EXPR で、式は $_ に 含まれているものとして考えられます。 従って実際には二つだけの eval 形式があります: EXPR のものはしばしば「文字列 eval」(string eval) と呼ばれます。 「文字列 eval」では、 式の値(それ自身スカラコンテキストの中で決定されます)はまずパースされ、 エラーがなければ Perl プログラムのレキシカルコンテキストの中のブロックとして 実行されます。 この形は主に EXPR のテキストのパースと実行を実行時にまで 遅延させるのに用います。 返される値は eval が実行されるごとにパースされることに注意してください。

The other form is called "block eval". It is less general than string eval, but the code within the BLOCK is parsed only once (at the same time the code surrounding the eval itself was parsed) and executed within the context of the current Perl program. This form is typically used to trap exceptions more efficiently than the first, while also providing the benefit of checking the code within BLOCK at compile time. BLOCK is parsed and compiled just once. Since errors are trapped, it often is used to check if a given feature is available.

もう一つの型式は「ブロック eval」と呼ばれます。 これは文字列 eval ほど一般的ではありませんが、 BLOCK 内部のコードは一度だけパースされ (コードを 囲む eval 自身がパースされるのと同じ時点です) 現在の Perl プログラムのコンテキストで実行されます。 この形式は典型的には第一の形式より効率的に例外をトラップします; また BLOCK 内部のコードはコンパイル時にチェックされるという利点を提供します。 BLOCK は一度だけパース及びコンパイルされます。 エラーはトラップされてるので、しばしば与えられた機能が利用可能かを チェックするために使われます。

In both forms, the value returned is the value of the last expression evaluated inside the mini-program; a return statement may also be used, just as with subroutines. The expression providing the return value is evaluated in void, scalar, or list context, depending on the context of the eval itself. See wantarray for more on how the evaluation context can be determined.

どちらの形式でも、返される値はミニプログラムの内部で最後に評価された 表現の値です; サブルーチンと同様、return 文も使えます。 返り値として提供される表現は、eval 自身のコンテキストに 依存して無効・スカラ・リストのいずれかのコンテキストで評価されます。 評価コンテキストの決定方法についての詳細は wantarray を 参照してください。

If there is a syntax error or runtime error, or a die statement is executed, eval returns undef in scalar context, or an empty list in list context, and $@ is set to the error message. (Prior to 5.16, a bug caused undef to be returned in list context for syntax errors, but not for runtime errors.) If there was no error, $@ is set to the empty string. A control flow operator like last or goto can bypass the setting of $@. Beware that using eval neither silences Perl from printing warnings to STDERR, nor does it stuff the text of warning messages into $@. To do either of those, you have to use the $SIG{__WARN__} facility, or turn off warnings inside the BLOCK or EXPR using no warnings 'all'. See warn, perlvar, and warnings.

構文エラーや実行エラーが発生するか、die 文が実行されると、 eval はスカラコンテキストでは undef が、 リストコンテキストでは空リストが設定され、 $@ にエラーメッセージが設定されます。 (5.16 以前では、バグによって、リストコンテキストで構文エラーの時には undef を返していましたが、実行エラーの時には 返していませんでした。) エラーがなければ、$@ は空文字列に設定されます。 lastgoto のようなフロー制御演算子は $@ の設定を回避できます。 eval を、STDERR に警告メッセージを表示させない目的や、 警告メッセージを $@ に格納する目的では使わないでください。 そのような用途では、$SIG{__WARN__} 機能を使うか、 no warnings 'all' を使って BLOCK か EXPR の内部での警告を オフにする必要があります。 warn, perlvar, warnings を参照してください。

Note that, because eval traps otherwise-fatal errors, it is useful for determining whether a particular feature (such as socket or symlink) is implemented. It is also Perl's exception-trapping mechanism, where the die operator is used to raise exceptions.

eval は、致命的エラーとなるようなものを トラップすることができるので、 (socketsymlink といった) 特定の機能が 実装されているかを、 調べるために使うことができることに注意してください。 die 演算子が例外を発生させるものとすれば、これはまた、 Perl の例外捕捉機能と捉えることもできます。

Before Perl 5.14, the assignment to $@ occurred before restoration of localized variables, which means that for your code to run on older versions, a temporary is required if you want to mask some, but not all errors:

Perl 5.14 より前では、$@ への代入はローカル化された変数の 復帰の前に起きるので、古いバージョンで実行される場合は、全てではなく一部だけの エラーをマスクしたい場合には一時変数が必要です:

 # alter $@ on nefarious repugnancy only
 {
    my $e;
    {
      local $@; # protect existing $@
      eval { test_repugnancy() };
      # $@ =~ /nefarious/ and die $@; # Perl 5.14 and higher only
      $@ =~ /nefarious/ and $e = $@;
    }
    die $e if defined $e
 }

There are some different considerations for each form:

それぞれの型式について、異なった考慮事項があります:

String eval

(文字列 eval)

Since the return value of EXPR is executed as a block within the lexical context of the current Perl program, any outer lexical variables are visible to it, and any package variable settings or subroutine and format definitions remain afterwards.

EXPR の返り値は現在の Perl プログラムのレキシカルコンテキストの中で 実行されるので、外側のレキシカルスコープはそこから見え、 パッケージ変数設定やサブルーチンとフォーマット設定は後に残ります。

Under the "unicode_eval" feature

If this feature is enabled (which is the default under a use 5.16 or higher declaration), EXPR is considered to be in the same encoding as the surrounding program. Thus if use utf8 is in effect, the string will be treated as being UTF-8 encoded. Otherwise, the string is considered to be a sequence of independent bytes. Bytes that correspond to ASCII-range code points will have their normal meanings for operators in the string. The treatment of the other bytes depends on if the 'unicode_strings" feature is in effect.

この機能が有効の場合(これは use 5.16 またはそれ以上が 宣言されている場合はデフォルトです)、 EXPR は周りのプログラムと同じエンコーディングであるとして扱われます。 従って、use utf8 が有効の場合、 文字列は UTF-8 エンコードされているものとして扱われます。 さもなければ、この文字列は個々のバイト列として扱われます。 ASCII の範囲の符号位置に対応するバイトは、 文字列の操作に関して通常の意味を持ちます。 その他のバイトの扱いは、 <'unicode_strings" feature|feature/'unicode_strings' 機能> が有効の場合か どうかに依存します。

In a plain eval without an EXPR argument, being in use utf8 or not is irrelevant; the UTF-8ness of $_ itself determines the behavior.

EXPR 引数のない単なる eval の場合、use utf8 の有無は無関係です; $_ 自身の UTF-8 性が振る舞いを決定します。

Any use utf8 or no utf8 declarations within the string have no effect, and source filters are forbidden. (unicode_strings, however, can appear within the string.) See also the evalbytes operator, which works properly with source filters.

文字列中の use utf8no utf8 宣言は無効で、ソースフィルタは 禁止されます。 (しかし、unicode_strings は文字列の中に現れます。) ソースフィルタが適切に動作する evalbytes 演算子も参照してください。

Variables defined outside the eval and used inside it retain their original UTF-8ness. Everything inside the string follows the normal rules for a Perl program with the given state of use utf8.

Variables defined outside the eval の外側で定義され、内側で使われた変数は、 元の UTF-8 性を維持します。 内側の文字列は、use utf8 の状態によって Perl プログラムに適用される 通常の規則に従います。

Outside the "unicode_eval" feature

In this case, the behavior is problematic and is not so easily described. Here are two bugs that cannot easily be fixed without breaking existing programs:

この場合、振る舞いには問題があり、それほど簡単には説明できません。 既存のプログラムを壊さずに簡単に修正することが出来ない二つのバグがあります:

  • It can lose track of whether something should be encoded as UTF-8 or not.

    あるものが UTF-8 でエンコードされているかどうかを見失うことがあります。

  • Source filters activated within eval leak out into whichever file scope is currently being compiled. To give an example with the CPAN module Semi::Semicolons:

    eval の中で有効にされたソースフィルタは、現在どちらのファイルスコープで コンパイルされているかをリークさせます。 CPAN モジュール Semi::Semicolons を使った例は:

     BEGIN { eval "use Semi::Semicolons; # not filtered" }
     # filtered here!

    evalbytes fixes that to work the way one would expect:

    evalbytes は、人が想定するだろう手法で動作するように これを修正します:

     use feature "evalbytes";
     BEGIN { evalbytes "use Semi::Semicolons; # filtered" }
     # not filtered

Problems can arise if the string expands a scalar containing a floating point number. That scalar can expand to letters, such as "NaN" or "Infinity"; or, within the scope of a use locale, the decimal point character may be something other than a dot (such as a comma). None of these are likely to parse as you are likely expecting.

文字列をが小数点を含むスカラを展開するときに問題が起こることがあります。 そのようなスカラは "NaN""Infinity" のような文字に 展開されることがあります; または、use locale のスコープの中では、 小数点文字は (カンマのような) ドット以外の文字かもしれません。 これらはどれもあなたがおそらく予測しているようにはパースされません。

You should be especially careful to remember what's being looked at when:

以下のような場合に、何が調べられるかに特に注意しておくことが必要です:

    eval $x;        # CASE 1
    eval "$x";      # CASE 2

    eval '$x';      # CASE 3
    eval { $x };    # CASE 4

    eval "\$$x++";  # CASE 5
    $$x++;          # CASE 6

Cases 1 and 2 above behave identically: they run the code contained in the variable $x. (Although case 2 has misleading double quotes making the reader wonder what else might be happening (nothing is).) Cases 3 and 4 likewise behave in the same way: they run the code '$x', which does nothing but return the value of $x. (Case 4 is preferred for purely visual reasons, but it also has the advantage of compiling at compile-time instead of at run-time.) Case 5 is a place where normally you would like to use double quotes, except that in this particular situation, you can just use symbolic references instead, as in case 6.

上記の CASE 1 と CASE 2 の動作は同一で、変数 $x 内の コードを実行します。 (ただし、CASE 2 では、必要のないダブルクォートによって、 読む人が何が起こるか混乱することでしょう (何も起こりませんが)。) 同様に CASE 3 と CASE 4 の動作も等しく、$x の値を返す以外に 何もしない $x というコードを実行します (純粋に見た目の問題で、CASE 4 が好まれますが、 実行時でなくコンパイル時にコンパイルされるという利点もあります)。 CASE 5 の場合は、通常ダブルクォートを使用 します; この状況を除けば、CASE 6 のように、単に シンボリックリファレンスを使えば良いでしょう。

An eval '' executed within a subroutine defined in the DB package doesn't see the usual surrounding lexical scope, but rather the scope of the first non-DB piece of code that called it. You don't normally need to worry about this unless you are writing a Perl debugger.

DB パッケージで定義されたサブルーチン内で eval '' を実行すると、通常の レキシカルスコープではなく、これを呼び出した最初の非 DB コード片の スコープになります。 Perl デバッガを書いているのでない限り、普通はこれについて心配する必要は ありません。

The final semicolon, if any, may be omitted from the value of EXPR.

最後のセミコロンは、もしあれば、EXPR の値から省くことができます。

Block eval

If the code to be executed doesn't vary, you may use the eval-BLOCK form to trap run-time errors without incurring the penalty of recompiling each time. The error, if any, is still returned in $@. Examples:

実行するコードが変わらないのであれば、毎回多量の再コンパイルすることなしに、 実行時エラーのトラップを行なうために、 eval-BLOCK 形式を使うことができます。 エラーがあれば、やはり $@ に返されます。 例:

    # make divide-by-zero nonfatal
    eval { $answer = $a / $b; }; warn $@ if $@;

    # same thing, but less efficient
    eval '$answer = $a / $b'; warn $@ if $@;

    # a compile-time error
    eval { $answer = }; # WRONG

    # a run-time error
    eval '$answer =';   # sets $@

If you want to trap errors when loading an XS module, some problems with the binary interface (such as Perl version skew) may be fatal even with eval unless $ENV{PERL_DL_NONLAZY} is set. See perlrun.

XS モジュールのロード中のエラーをトラップしたいなら、 (Perl バージョンの違いのような) バイナリインターフェースに関する問題に ついては $ENV{PERL_DL_NONLAZY} がセットされていない eval でも致命的エラーになるかもしれません。 perlrun を参照してください。

Using the eval {} form as an exception trap in libraries does have some issues. Due to the current arguably broken state of __DIE__ hooks, you may wish not to trigger any __DIE__ hooks that user code may have installed. You can use the local $SIG{__DIE__} construct for this purpose, as this example shows:

eval{} 形式をライブラリの例外を捕捉するために使うときには 問題があります。 現在の __DIE__ フックの状態はほぼ確実に壊れているという理由で、 ユーザーのコードが設定した __DIE__ フックを実行したくないかもしれません。 この目的には以下の例のように、local $SIG{__DIE__} 構造が使えます。

    # a private exception trap for divide-by-zero
    eval { local $SIG{'__DIE__'}; $answer = $a / $b; };
    warn $@ if $@;

This is especially significant, given that __DIE__ hooks can call die again, which has the effect of changing their error messages:

これは特に顕著です; 与えられた __DIE__ フックは die を もう一度呼び出すことができ、これによってエラーメッセージを変える 効果があります:

    # __DIE__ hooks may modify error messages
    {
       local $SIG{'__DIE__'} =
              sub { (my $x = $_[0]) =~ s/foo/bar/g; die $x };
       eval { die "foo lives here" };
       print $@ if $@;                # prints "bar lives here"
    }

Because this promotes action at a distance, this counterintuitive behavior may be fixed in a future release.

これは距離の離れた行動であるため、この直感的でない振る舞いは 将来のリリースでは修正されるかもしれません。

eval BLOCK does not count as a loop, so the loop control statements next, last, or redo cannot be used to leave or restart the block.

eval BLOCK はループとして 扱われません; 従って、next, last, redo といったループ制御文で ブロックから離れたり再実行したりはできません。

The final semicolon, if any, may be omitted from within the BLOCK.

最後のセミコロンは、もしあれば、BLOCK の中から削除されます。

evalbytes EXPR
evalbytes

This function is similar to a string eval, except it always parses its argument (or $_ if EXPR is omitted) as a string of independent bytes.

この関数は 文字列 eval に似ていますが、引数(EXPR が 省略された場合は$_) を常にバイト単位のの文字列として 扱います。

If called when use utf8 is in effect, the string will be assumed to be encoded in UTF-8, and evalbytes will make a temporary copy to work from, downgraded to non-UTF-8. If this is not possible (because one or more characters in it require UTF-8), the evalbytes will fail with the error stored in $@.

use utf8 が有効のときに呼び出されると、 文字列は UTF-8 でエンコードされていると仮定され、 evalbytes は、非 UTF-8 にダウングレードした一時的なコピーを作ります。 (UTF-8 が必要な文字があるために) これが不可能な場合、 evalbytes は失敗し、エラーは $@ に保管されます。

Bytes that correspond to ASCII-range code points will have their normal meanings for operators in the string. The treatment of the other bytes depends on if the 'unicode_strings" feature is in effect.

ASCII の範囲の符号位置に対応するバイトは、 文字列の操作に関して通常の意味を持ちます。 その他のバイトの扱いは、 <'unicode_strings" feature|feature/'unicode_strings' 機能> が有効の場合か どうかに依存します。

Of course, variables that are UTF-8 and are referred to in the string retain that:

もちろん、UTF-8 で文字列の中で参照されている変数はそのままです:

 my $a = "\x{100}";
 evalbytes 'print ord $a, "\n"';

prints

というのは、次を表示し、

 256

and $@ is empty.

$@ は空になります。

Source filters activated within the evaluated code apply to the code itself.

eval されたコード内で有効になったソースフィルタはコード自体に適用されます。

evalbytes is available starting in Perl v5.16. To access it, you must say CORE::evalbytes, but you can omit the CORE:: if the "evalbytes" feature is enabled. This is enabled automatically with a use v5.16 (or higher) declaration in the current scope.

evalbytes は Perl v5.16 から利用可能です。 これにアクセスするには CORE::evalbytes とする必要がありますが、 "evalbytes" 機能 が 有効なら CORE:: を省略できます。 これは現在のスコープで use v5.16 (またはそれ以上) 宣言があると 自動的に有効になります。

exec LIST
exec PROGRAM LIST

The exec function executes a system command and never returns; use system instead of exec if you want it to return. It fails and returns false only if the command does not exist and it is executed directly instead of via your system's command shell (see below).

exec 関数は、システムのコマンドを実行し、戻ってはきません; 戻って欲しい場合には、execではなく system 関数を使ってください。 コマンドが存在せず、しかも システムのコマンドシェル経由でなく 直接コマンドを実行しようとした場合にのみこの関数は失敗して偽を返します。

Since it's a common mistake to use exec instead of system, Perl warns you if exec is called in void context and if there is a following statement that isn't die, warn, or exit (if warnings are enabled--but you always do that, right?). If you really want to follow an exec with some other statement, you can use one of these styles to avoid the warning:

system の代わりに exec を使うという よくある間違いを防ぐために、exec が無効コンテキストで 呼び出されて、引き続く文が die, warn, exit 以外の場合、Perl は警告を出します(warnings が 有効の場合 -- でもいつもセットしてますよね?)。 もし 本当に exec の後に他の文を書きたい場合、以下の どちらかのスタイルを使うことで警告を回避できます:

    exec ('foo')   or print STDERR "couldn't exec foo: $!";
    { exec ('foo') }; print STDERR "couldn't exec foo: $!";

If there is more than one argument in LIST, this calls execvp(3) with the arguments in LIST. If there is only one element in LIST, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is /bin/sh -c on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to execvp, which is more efficient. Examples:

LIST に複数の引数がある場合は、LIST の引数を使って execvp(3) を 呼び出します。 LIST に要素が一つのみの場合には、その引数からシェルのメタ文字をチェックし、 もしメタ文字があれば、引数全体をシステムのコマンドシェル(これはUnix では /bin/sh -c ですが、システムによって異なります)に渡して解析させます。 シェルのメタ文字がなかった場合、引数は単語に分解されて直接 execvp に 渡されます; この方がより効率的です。 例:

    exec '/bin/echo', 'Your arguments are: ', @ARGV;
    exec "sort $outfile | uniq";

If you don't really want to execute the first argument, but want to lie to the program you are executing about its own name, you can specify the program you actually want to run as an "indirect object" (without a comma) in front of the LIST, as in exec PROGRAM LIST. (This always forces interpretation of the LIST as a multivalued list, even if there is only a single scalar in the list.) Example:

第一引数に指定するものを本当に実行したいが、実行するプログラムに対して別の 名前を教えたい場合には、exec PROGRAM LIST のように、LIST の前に 「間接オブジェクト」(コンマなし) として実際に実行したいプログラムを 指定することができます。 (これによって、LIST に単一のスカラしかなくても、複数値のリストであるように、 LIST の解釈を行ないます。) 例:

    my $shell = '/bin/csh';
    exec $shell '-sh';    # pretend it's a login shell

or, more directly,

あるいは、より直接的に、

    exec {'/bin/csh'} '-sh';  # pretend it's a login shell

When the arguments get executed via the system shell, results are subject to its quirks and capabilities. See "`STRING`" in perlop for details.

引数がシステムシェルで実行されるとき、結果はシェルの奇癖と能力によって 変わります。 詳細については "`STRING`" in perlop を参照してください。

Using an indirect object with exec or system is also more secure. This usage (which also works fine with system) forces interpretation of the arguments as a multivalued list, even if the list had just one argument. That way you're safe from the shell expanding wildcards or splitting up words with whitespace in them.

execsystem で間接オブジェクトを 使うのもより安全です。 この使い方(system でも同様にうまく動きます)は、たとえ 引数が一つだけの場合も、複数の値を持つリストとして引数を解釈することを 強制します。 この方法で、シェルによるワイルドカード展開や、空白による単語の分割から 守られます。

    my @args = ( "echo surprise" );

    exec @args;               # subject to shell escapes
                                # if @args == 1
    exec { $args[0] } @args;  # safe even with one-arg list

The first version, the one without the indirect object, ran the echo program, passing it "surprise" an argument. The second version didn't; it tried to run a program named "echo surprise", didn't find it, and set $? to a non-zero value indicating failure.

間接オブジェクトなしの一つ目のバージョンでは、echo プログラムが実行され、 "surprise" が引数として渡されます。 二つ目のバージョンでは違います; "echo surprise" という名前の プログラムを実行しようとして、見つからないので、失敗したことを示すために $? に非 0 がセットされます。

On Windows, only the exec PROGRAM LIST indirect object syntax will reliably avoid using the shell; exec LIST, even with more than one element, will fall back to the shell if the first spawn fails.

Windows では、exec PROGRAM LIST 間接オブジェクト構文のみが、シェルを 使うのを回避するための信頼できる方法です; exec LIST は、複数の要素が あっても、最初の spawn が失敗したときにシェルに フォールバックすることがあります。

Perl attempts to flush all files opened for output before the exec, but this may not be supported on some platforms (see perlport). To be safe, you may need to set $| ($AUTOFLUSH in English) or call the autoflush method of IO::Handle on any open handles to avoid lost output.

v5.6.0 から、Perl は exec の前に出力用に開かれている全てのファイルを フラッシュしようとしますが、これに対応していないプラットフォームもあります (perlport を参照してください)。 安全のためには、出力が重複するのを避けるために、全てのオープンしている ハンドルに対して $| (English モジュールでは $AUTOFLUSH) を設定するか、 IO::Handle モジュールの autoflush メソッドを 呼ぶ必要があるかもしれません。

Note that exec will not call your END blocks, nor will it invoke DESTROY methods on your objects.

execEND ブロックや、オブジェクトの DESTROY メソッドを起動しないことに注意してください。

Portability issues: "exec" in perlport.

移植性の問題: "exec" in perlport

exists EXPR

Given an expression that specifies an element of a hash, returns true if the specified element in the hash has ever been initialized, even if the corresponding value is undefined.

ハッシュ要素を示す表現が与えられ、指定された要素が、ハッシュに存在すれば、 たとえ対応する値が未定義でも真を返します。

    print "Exists\n"    if exists $hash{$key};
    print "Defined\n"   if defined $hash{$key};
    print "True\n"      if $hash{$key};

exists may also be called on array elements, but its behavior is much less obvious and is strongly tied to the use of delete on arrays.

exists は配列の要素に対しても呼び出せますが、その振る舞いははるかに 不明確で、配列に対する delete の使用と強く 結びついています。

WARNING: Calling exists on array values is strongly discouraged. The notion of deleting or checking the existence of Perl array elements is not conceptually coherent, and can lead to surprising behavior.

警告: 配列の値に対して exists を呼び出すことは強く 非推奨です。 Perl の配列要素を削除したり存在を調べたりする記法は概念的に一貫しておらず、 驚くべき振る舞いを引き起こすことがあります。

    print "Exists\n"    if exists $array[$index];
    print "Defined\n"   if defined $array[$index];
    print "True\n"      if $array[$index];

A hash or array element can be true only if it's defined and defined only if it exists, but the reverse doesn't necessarily hold true.

ハッシュまたは配列要素は、定義されているときにのみ真となり、 存在しているときにのみ定義されますが、逆は必ずしも真ではありません。

Given an expression that specifies the name of a subroutine, returns true if the specified subroutine has ever been declared, even if it is undefined. Mentioning a subroutine name for exists or defined does not count as declaring it. Note that a subroutine that does not exist may still be callable: its package may have an AUTOLOAD method that makes it spring into existence the first time that it is called; see perlsub.

引数としてサブルーチンの名前が指定された場合、 指定されたサブルーチンが宣言されていれば(たとえ未定義でも) 真を返します。 exists や defined のために言及されているサブルーチン名は 宣言としてのカウントに入りません。 存在しないサブルーチンでも呼び出し可能かもしれないことに注意してください: パッケージが AUTOLOAD メソッドを持っていて、最初に呼び出された時に 存在を作り出すかもしれません; perlsub を参照してください。

    print "Exists\n"  if exists &subroutine;
    print "Defined\n" if defined &subroutine;

Note that the EXPR can be arbitrarily complicated as long as the final operation is a hash or array key lookup or subroutine name:

最終的な操作がハッシュや配列の key による検索または サブルーチン名である限りは、EXPR には任意の複雑な式を置くことができます:

    if (exists $ref->{A}->{B}->{$key})  { }
    if (exists $hash{A}{B}{$key})       { }

    if (exists $ref->{A}->{B}->[$ix])   { }
    if (exists $hash{A}{B}[$ix])        { }

    if (exists &{$ref->{A}{B}{$key}})   { }

Although the most deeply nested array or hash element will not spring into existence just because its existence was tested, any intervening ones will. Thus $ref->{"A"} and $ref->{"A"}->{"B"} will spring into existence due to the existence test for the $key element above. This happens anywhere the arrow operator is used, including even here:

最も深くネストした配列やハッシュの要素は、その存在をテストしただけでは 存在するようにはなりませんが、途中のものは存在するようになります。 従って $ref->{"A"}$ref->{"A"}->{"B"} は上記の $key の 存在をテストしたことによって存在するようになります。 これは、矢印演算子が使われるところでは、以下のようなものを含むどこででも 起こります。

    undef $ref;
    if (exists $ref->{"Some key"})    { }
    print $ref;  # prints HASH(0x80d3d5c)

Use of a subroutine call, rather than a subroutine name, as an argument to exists is an error.

exists の引数としてサブルーチン名でなくサブルーチン 呼び出しを使うと、エラーになります。

    exists &sub;    # OK
    exists &sub();  # Error
exit EXPR
exit

Evaluates EXPR and exits immediately with that value. Example:

EXPR を評価し、即座にその値を持って終了します。 例:

    my $ans = <STDIN>;
    exit 0 if $ans =~ /^[Xx]/;

See also die. If EXPR is omitted, exits with 0 status. The only universally recognized values for EXPR are 0 for success and 1 for error; other values are subject to interpretation depending on the environment in which the Perl program is running. For example, exiting 69 (EX_UNAVAILABLE) from a sendmail incoming-mail filter will cause the mailer to return the item undelivered, but that's not true everywhere.

die も参照してください。 EXPR が省略された場合には、ステータスを 0 として終了します。 EXPR の値として広く利用可能なのは 0 が成功で 1 が エラーということだけです; その他の値は、 Perl が実行される環境によって異なる 解釈がされる可能性があります。 例えば、sendmail 到着メールフィルタから 69 (EX_UNAVAILABLE) で終了すると メーラーはアイテムを配達せずに差し戻しますが、 これはいつでも真ではありません。

Don't use exit to abort a subroutine if there's any chance that someone might want to trap whatever error happened. Use die instead, which can be trapped by an eval.

誰かが発生したエラーをトラップしようと考えている可能性がある場合は、 サブルーチンの中断に exit を使わないでください。 代わりに eval でトラップできる die を 使ってください。

The exit function does not always exit immediately. It calls any defined END routines first, but these END routines may not themselves abort the exit. Likewise any object destructors that need to be called are called before the real exit. END routines and destructors can change the exit status by modifying $?. If this is a problem, you can call POSIX::_exit($status) to avoid END and destructor processing. See perlmod for details.

exit 関数は常に直ちに終了するわけではありません。 まず、定義されている END ルーチンを呼び出しますが、 END ルーチン自身は exit を止められません。 同様に、呼び出す必要のあるオブジェクトデストラクタは すべて、実際の終了前に呼び出されます。 END ルーチンとデストラクタは $? を修正することで 終了コードを変更できます。 これが問題になる場合は、END やデストラクタが実行されることを 防ぐために POSIX::_exit($status) を呼び出してください。 詳しくは perlmod を参照してください。

Portability issues: "exit" in perlport.

移植性の問題: "exit" in perlport

exp EXPR
exp

Returns e (the natural logarithm base) to the power of EXPR. If EXPR is omitted, gives exp($_).

e (自然対数の底) の EXPR 乗を返します。 EXPR を省略した場合には、exp($_) を返します。

fc EXPR
fc

Returns the casefolded version of EXPR. This is the internal function implementing the \F escape in double-quoted strings.

EXPR の畳み込み版を返します。 これは、ダブルクォート文字列における、\F エスケープを 実装する内部関数です。

Casefolding is the process of mapping strings to a form where case differences are erased; comparing two strings in their casefolded form is effectively a way of asking if two strings are equal, regardless of case.

畳み込みは大文字小文字の違いを消した形式に文字列をマッピングする処理です; 畳み込み形式で二つの文字列を比較するのは二つの文字列が大文字小文字に 関わらず等しいかどうかを比較する効率的な方法です。

Roughly, if you ever found yourself writing this

おおよそ、自分自身で以下のように書いていたとしても

    lc($this) eq lc($that)    # Wrong!
        # or
    uc($this) eq uc($that)    # Also wrong!
        # or
    $this =~ /^\Q$that\E\z/i  # Right!

Now you can write

今では以下のように書けます

    fc($this) eq fc($that)

And get the correct results.

そして正しい結果を得られます。

Perl only implements the full form of casefolding, but you can access the simple folds using "casefold()" in Unicode::UCD and "prop_invmap()" in Unicode::UCD. For further information on casefolding, refer to the Unicode Standard, specifically sections 3.13 Default Case Operations, 4.2 Case-Normative, and 5.18 Case Mappings, available at http://www.unicode.org/versions/latest/, as well as the Case Charts available at http://www.unicode.org/charts/case/.

Perl は完全な形式の畳み込みのみを実装していますが、 "casefold()" in Unicode::UCD"prop_invmap()" in Unicode::UCD を使って 単純なたたみ込みにアクセスできます。 畳み込みに関するさらなる情報については、 http://www.unicode.org/versions/latest/ で利用可能な Unicode 標準、特に 3.13 Default Case Operations, 4.2 Case-Normative, 5.18 Case Mappings および、http://www.unicode.org/charts/case/ で 利用可能なケース表を参照してください。

If EXPR is omitted, uses $_.

EXPR が省略されると、$_ を使います。

This function behaves the same way under various pragmas, such as within "use feature 'unicode_strings", as lc does, with the single exception of fc of LATIN CAPITAL LETTER SHARP S (U+1E9E) within the scope of use locale. The foldcase of this character would normally be "ss", but as explained in the lc section, case changes that cross the 255/256 boundary are problematic under locales, and are hence prohibited. Therefore, this function under locale returns instead the string "\x{17F}\x{17F}", which is the LATIN SMALL LETTER LONG S. Since that character itself folds to "s", the string of two of them together should be equivalent to a single U+1E9E when foldcased.

この関数は、 "use feature 'unicode_strings" のようなさまざまなプラグマの影響下では、lc と同様に 振る舞います; 但し、use locale のスコープ内での LATIN CAPITAL LETTER SHARP S (U+1E9E) の fc は例外です。 この文字の畳み込み文字は普通は "ss" ですが、lc の節で 説明しているように、ロケールの基での255/256 境界をまたぐ大文字小文字の変更は 問題があるので、禁止されています。 従って、ロケールの基ではこの関数は代わりに LATIN SMALL LETTER LONG S である "\x{17F}\x{17F}" を返します。 この文字自体は "s" の畳み込みなので、これら二つを合わせた文字列は 畳み込まれた場合は単一の U+1E9E と等価になります。

While the Unicode Standard defines two additional forms of casefolding, one for Turkic languages and one that never maps one character into multiple characters, these are not provided by the Perl core. However, the CPAN module Unicode::Casing may be used to provide an implementation.

Unicode 標準はさらに二つの畳み込み形式、一つはツルキ語、もう一つは決して 一つの文字が複数の文字にマッピングされないもの、を定義していますが、 これらは Perl コアでは提供されません。 しかし、CPAN モジュール Unicode::Casing が実装を 提供しています。

fc is available only if the "fc" feature is enabled or if it is prefixed with CORE::. The "fc" feature is enabled automatically with a use v5.16 (or higher) declaration in the current scope.

fc"fc" 機能 が有効か CORE:: が前置されたときにのみ利用可能です。 "fc" 機能 は現在のスコープで use v5.16 (またはそれ以上) が宣言されると自動的に有効になります。

fcntl FILEHANDLE,FUNCTION,SCALAR

Implements the fcntl(2) function. You'll probably have to say

fcntl(2) 関数を実装します。 正しい定数定義を得るために、まず

    use Fcntl;

first to get the correct constant definitions. Argument processing and value returned work just like ioctl below. For example:

と書くことが必要でしょう。 引数の処理と返り値については、下記の ioctl と同様に動作します。 例えば:

    use Fcntl;
    my $flags = fcntl($filehandle, F_GETFL, 0)
        or die "Can't fcntl F_GETFL: $!";

You don't have to check for defined on the return from fcntl. Like ioctl, it maps a 0 return from the system call into "0 but true" in Perl. This string is true in boolean context and 0 in numeric context. It is also exempt from the normal Argument "..." isn't numeric warnings on improper numeric conversions.

fcntl からの返り値のチェックに defined を使う必要はありません。 ioctl と違って、これは システムコールの結果が 0 だった場合は "0 だが真" を返します。 この文字列は真偽値コンテキストでは真となり、 数値コンテキストでは 0 になります。 これはまた、不適切な数値変換に関する通常の Argument "..." isn't numeric warnings を回避します。

Note that fcntl raises an exception if used on a machine that doesn't implement fcntl(2). See the Fcntl module or your fcntl(2) manpage to learn what functions are available on your system.

fcntl(2) が実装されていないマシンでは、 fcntl は例外を 引き起こすことに注意してください。 システムでどの関数が利用可能かについては Fcntl モジュールや fcntl(2) man ページを参照してください。

Here's an example of setting a filehandle named $REMOTE to be non-blocking at the system level. You'll have to negotiate $| on your own, though.

これは $REMOTE というファイルハンドルをシステムレベルで 非ブロックモードにセットする例です。 ただし、 $| を自分で管理しなければなりません。

    use Fcntl qw(F_GETFL F_SETFL O_NONBLOCK);

    my $flags = fcntl($REMOTE, F_GETFL, 0)
        or die "Can't get flags for the socket: $!\n";

    fcntl($REMOTE, F_SETFL, $flags | O_NONBLOCK)
        or die "Can't set flags for the socket: $!\n";

Portability issues: "fcntl" in perlport.

移植性の問題: "fcntl" in perlport

__FILE__

A special token that returns the name of the file in which it occurs.

これが書いてあるファイルの名前を返す特殊トークン。

fileno FILEHANDLE
fileno DIRHANDLE

Returns the file descriptor for a filehandle or directory handle, or undefined if the filehandle is not open. If there is no real file descriptor at the OS level, as can happen with filehandles connected to memory objects via open with a reference for the third argument, -1 is returned.

ファイルハンドルやディレクトリハンドルに対するファイル記述子を返します; ファイルハンドルがオープンしていない場合は未定義値を返します。 OS レベルで実際のファイル記述子がない(open の 第 3 引数にリファレンスを 指定してファイルハンドルがメモリオブジェクトと結びつけられたときに 起こります)場合、-1 が返されます。

This is mainly useful for constructing bitmaps for select and low-level POSIX tty-handling operations. If FILEHANDLE is an expression, the value is taken as an indirect filehandle, generally its name.

これは主に select や低レベル POSIX tty 操作に対する、ビットマップを構成するときに便利です。 FILEHANDLE が式であれば、 その値が間接ファイルハンドル(普通は名前)として使われます。

You can use this to find out whether two handles refer to the same underlying descriptor:

これを、二つのハンドルが同じ識別子を参照しているかどうかを見つけるのに 使えます:

    if (fileno($this) != -1 && fileno($this) == fileno($that)) {
        print "\$this and \$that are dups\n";
    } elsif (fileno($this) != -1 && fileno($that) != -1) {
        print "\$this and \$that have different " .
            "underlying file descriptors\n";
    } else {
        print "At least one of \$this and \$that does " .
            "not have a real file descriptor\n";
    }

The behavior of fileno on a directory handle depends on the operating system. On a system with dirfd(3) or similar, fileno on a directory handle returns the underlying file descriptor associated with the handle; on systems with no such support, it returns the undefined value, and sets $! (errno).

ディレクトリハンドルに対する fileno の振る舞いは オペレーティングシステムに依存します。 dirfd(3) のようなものがあるシステムでは、ディレクトリハンドルに対する fileno はハンドルに関連付けられた基となる ファイル記述子を返します; そのような対応がないシステムでは、未定義値を返し、 $! (errno) を設定します。

flock FILEHANDLE,OPERATION

Calls flock(2), or an emulation of it, on FILEHANDLE. Returns true for success, false on failure. Produces a fatal error if used on a machine that doesn't implement flock(2), fcntl(2) locking, or lockf(3). flock is Perl's portable file-locking interface, although it locks entire files only, not records.

FILEHANDLE に対して flock(2)、またはそのエミュレーションを呼び出します。 成功時には真を、失敗時には偽を返します。 flock(2), fcntl(2) ロック, lockf(3) のいずれかを実装していない マシンで使うと、致命的エラーが発生します。 flock は Perl の移植性のある ファイルロックインターフェースです; しかしレコードではなく、ファイル全体のみをロックします。

Two potentially non-obvious but traditional flock semantics are that it waits indefinitely until the lock is granted, and that its locks are merely advisory. Such discretionary locks are more flexible, but offer fewer guarantees. This means that programs that do not also use flock may modify files locked with flock. See perlport, your port's specific documentation, and your system-specific local manpages for details. It's best to assume traditional behavior if you're writing portable programs. (But if you're not, you should as always feel perfectly free to write for your own system's idiosyncrasies (sometimes called "features"). Slavish adherence to portability concerns shouldn't get in the way of your getting your job done.)

明白ではないものの、伝統的な flock の 動作としては、ロックが得られるまで 無限に待ち続けるものと、単に勧告的に ロックするものの二つがあります。 このような自由裁量のロックはより柔軟ですが、保障されるものはより少ないです。 これは、flock を使わないプログラムが flock でロックされたファイルを 書き換えるかもしれないことを意味します。 詳細については、perlport、システム固有のドキュメント、システム固有の ローカルの man ページを参照してください。 移植性のあるプログラムを書く場合は、伝統的な振る舞いを仮定するのが ベストです。 (しかし移植性のないプログラムを書く場合は、自身のシステムの性癖(しばしば 「仕様」と呼ばれます)に合わせて書くことも完全に自由です。 盲目的に移植性に固執することで、あなたの作業を仕上げるのを邪魔するべきでは ありません。)

OPERATION is one of LOCK_SH, LOCK_EX, or LOCK_UN, possibly combined with LOCK_NB. These constants are traditionally valued 1, 2, 8 and 4, but you can use the symbolic names if you import them from the Fcntl module, either individually, or as a group using the :flock tag. LOCK_SH requests a shared lock, LOCK_EX requests an exclusive lock, and LOCK_UN releases a previously requested lock. If LOCK_NB is bitwise-or'ed with LOCK_SH or LOCK_EX, then flock returns immediately rather than blocking waiting for the lock; check the return status to see if you got it.

OPERATION は LOCK_SH, LOCK_EX, LOCK_UN のいずれかで、LOCK_NB と 組み合わされることもあります。 これらの定数は伝統的には 1, 2, 8, 4 の値を持ちますが、Fcntl モジュールから シンボル名を独立してインポートするか、:flock タグを使うグループとして、 シンボル名をを使うことができます。 LOCK_SH は共有ロックを要求し、LOCK_EX は排他ロックを要求し、LOCK_UN は 前回要求したロックを開放します。 LOCK_NB と LOCK_SH か LOCK_EX がビット単位の論理和されると、 flock は ロックを取得するまで待つのではなく、すぐに返ります; ロックが取得できたかどうかは返り値を調べます。

To avoid the possibility of miscoordination, Perl now flushes FILEHANDLE before locking or unlocking it.

不一致の可能性を避けるために、Perl はファイルをロック、アンロックする前に FILEHANDLE をフラッシュします。

Note that the emulation built with lockf(3) doesn't provide shared locks, and it requires that FILEHANDLE be open with write intent. These are the semantics that lockf(3) implements. Most if not all systems implement lockf(3) in terms of fcntl(2) locking, though, so the differing semantics shouldn't bite too many people.

lockf(3) で作成されたエミュレーションは共有ロックを提供せず、 FILEHANDLE が書き込みモードで開いていることを必要とすることに 注意してください。 これは lockf(3) が実装している動作です。 しかし、全てではないにしてもほとんどのシステムでは fcntl(2) を使って lockf(3) を実装しているので、異なった動作で多くの人々を混乱させることは ないはずです。

Note that the fcntl(2) emulation of flock(3) requires that FILEHANDLE be open with read intent to use LOCK_SH and requires that it be open with write intent to use LOCK_EX.

flock(3)fcntl(2) エミュレーションは、 LOCK_SH を使うためには FILEHANDLE を読み込みで開いている必要があり、LOCK_EX を使うためには 書き込みで開いている必要があることに注意してください。

Note also that some versions of flock cannot lock things over the network; you would need to use the more system-specific fcntl for that. If you like you can force Perl to ignore your system's flock(2) function, and so provide its own fcntl(2)-based emulation, by passing the switch -Ud_flock to the Configure program when you configure and build a new Perl.

ネットワーク越しにはロックできない flock も あることに注意してください; このためには、よりシステム依存な fcntl を使う必要があります。 Perl にシステムの flock(2) 関数を無視させ、自身の fcntl(2) ベースの エミュレーションを使う場合は、新しい Perl を設定およびビルドするときに Configure プログラムに -Ud_flock オプションを渡してください。

Here's a mailbox appender for BSD systems.

BSD システムでのメールボックスへの追加処理の例を示します。

    # import LOCK_* and SEEK_END constants
    use Fcntl qw(:flock SEEK_END);

    sub lock {
        my ($fh) = @_;
        flock($fh, LOCK_EX) or die "Cannot lock mailbox - $!\n";
        # and, in case we're running on a very old UNIX
        # variant without the modern O_APPEND semantics...
        seek($fh, 0, SEEK_END) or die "Cannot seek - $!\n";
    }

    sub unlock {
        my ($fh) = @_;
        flock($fh, LOCK_UN) or die "Cannot unlock mailbox - $!\n";
    }

    open(my $mbox, ">>", "/usr/spool/mail/$ENV{'USER'}")
        or die "Can't open mailbox: $!";

    lock($mbox);
    print $mbox $msg,"\n\n";
    unlock($mbox);

On systems that support a real flock(2), locks are inherited across fork calls, whereas those that must resort to the more capricious fcntl(2) function lose their locks, making it seriously harder to write servers.

真の flock(2) に対応しているシステムではロックは fork を通して 継承されるのに対して、より不安定な fcntl(2) に頼らなければならない場合、 サーバを書くのは本当により難しくなります。

See also DB_File for other flock examples.

その他の flock の例としては DB_File も 参照してください。

Portability issues: "flock" in perlport.

移植性の問題: "flock" in perlport

fork

Does a fork(2) system call to create a new process running the same program at the same point. It returns the child pid to the parent process, 0 to the child process, or undef if the fork is unsuccessful. File descriptors (and sometimes locks on those descriptors) are shared, while everything else is copied. On most systems supporting fork(2), great care has gone into making it extremely efficient (for example, using copy-on-write technology on data pages), making it the dominant paradigm for multitasking over the last few decades.

同じプログラムの同じ地点から開始する新しいプロセスを作成するために システムコール fork(2) を行ないます。 親プロセスには、チャイルドプロセスの pid を、 チャイルドプロセスに 0 を返しますが、 fork に失敗したときには、undefを返します。 ファイル記述子(および記述子に関連するロック)は共有され、 その他の全てはコピーされます。 fork(2) に対応するほとんどのシステムでは、 これを極めて効率的にするために多大な努力が払われてきました (例えば、データページへの copy-on-write テクノロジーなどです); これはここ 20 年にわたるマルチタスクに関する主要なパラダイムとなっています。

Perl attempts to flush all files opened for output before forking the child process, but this may not be supported on some platforms (see perlport). To be safe, you may need to set $| ($AUTOFLUSH in English) or call the autoflush method of IO::Handle on any open handles to avoid duplicate output.

v5.6.0 から、Perl は子プロセスを fork する前に出力用にオープンしている全ての ファイルをフラッシュしようとしますが、これに対応していないプラットフォームも あります(perlport を参照してください)。 安全のためには、出力が重複するのを避けるために、 全てのオープンしているハンドルに対して $| (English モジュールでは $AUTOFLUSH) を設定するか、 IO::Handle モジュールの autoflush メソッドを 呼ぶ必要があるかもしれません。

If you fork without ever waiting on your children, you will accumulate zombies. On some systems, you can avoid this by setting $SIG{CHLD} to "IGNORE". See also perlipc for more examples of forking and reaping moribund children.

チャイルドプロセスの終了を待たずに、fork を繰り返せば、 ゾンビをためこむことになります。 $SIG{CHLD}"IGNORE" を指定することでこれを 回避できるシステムもあります。 fork と消滅しかけている子プロセスを回収するための更なる例については perlipc も参照してください。

Note that if your forked child inherits system file descriptors like STDIN and STDOUT that are actually connected by a pipe or socket, even if you exit, then the remote server (such as, say, a CGI script or a backgrounded job launched from a remote shell) won't think you're done. You should reopen those to /dev/null if it's any issue.

fork した子プロセスが STDIN や STDOUT といったシステムファイル記述子を 継承する場合、(CGI スクリプトやリモートシェルといった バックグラウンドジョブのような)リモートサーバは考え通りに 動かないであろうことに注意してください。 このような場合ではこれらを /dev/null として再オープンするべきです。

On some platforms such as Windows, where the fork(2) system call is not available, Perl can be built to emulate fork in the Perl interpreter. The emulation is designed, at the level of the Perl program, to be as compatible as possible with the "Unix" fork(2). However it has limitations that have to be considered in code intended to be portable. See perlfork for more details.

Windows のような fork(2) が利用不能なシステムでは、Perl は fork を Perl インタプリタでエミュレートします。 エミュレーションは Perl プログラムのレベルではできるだけ "Unix" fork(2) と 互換性があるように設計されています。 しかしコードが移植性があると考えられるように制限があります。 さらなる詳細については perlfork を参照してください。

Portability issues: "fork" in perlport.

移植性の問題: "fork" in perlport

format

Declare a picture format for use by the write function. For example:

write 関数で使うピクチャーフォーマットを宣言します。 例えば:

    format Something =
        Test: @<<<<<<<< @||||| @>>>>>
              $str,     $%,    '$' . int($num)
    .

    $str = "widget";
    $num = $cost/$quantity;
    $~ = 'Something';
    write;

See perlform for many details and examples.

詳細と例については perlform を参照してください。

formline PICTURE,LIST

This is an internal function used by formats, though you may call it, too. It formats (see perlform) a list of values according to the contents of PICTURE, placing the output into the format output accumulator, $^A (or $ACCUMULATOR in English). Eventually, when a write is done, the contents of $^A are written to some filehandle. You could also read $^A and then set $^A back to "". Note that a format typically does one formline per line of form, but the formline function itself doesn't care how many newlines are embedded in the PICTURE. This means that the ~ and ~~ tokens treat the entire PICTURE as a single line. You may therefore need to use multiple formlines to implement a single record format, just like the format compiler.

これは、format が使用する内部関数ですが、直接呼び出すことも できます。 これは、PICTURE の内容にしたがって、LIST の値を整形し (perlform を 参照してください)、結果をフォーマット出力アキュムレータ$^A (English モジュールでは $ACCUMULATOR) に納めます。 最終的に、write が実行されると、 $^A の中身が、何らかのファイルハンドルに書き出されます。 また、自分で $^A を読んで、$^A の内容を "" に戻してもかまいません。 format は通常、1 行ごとに formline を 行ないますが、formline 関数自身は、PICTURE の中に いくつの改行が入っているかは、関係がありません。 これは、~~~トークンは PICTURE 全体を一行として扱うことを意味します。 従って、1 レコードフォーマットを実装するためには format コンパイラのような複数 formline を使う必要があります。

Be careful if you put double quotes around the picture, because an @ character may be taken to mean the beginning of an array name. formline always returns true. See perlform for other examples.

ダブルクォートで PICTURE を囲む場合には、@ という文字が 配列名の始まりと解釈されますので、注意してください。 formline は常に真を返します。 その他の例については perlform を参照してください。

If you are trying to use this instead of write to capture the output, you may find it easier to open a filehandle to a scalar (open my $fh, ">", \$output) and write to that instead.

出力を捕捉するために write の代わりにこれを 使おうとした場合、スカラにファイルハンドルを開いて (open my $fh, ">", \$output)、 代わりにここに出力する方が簡単であることに気付くでしょう。

getc FILEHANDLE
getc

Returns the next character from the input file attached to FILEHANDLE, or the undefined value at end of file or if there was an error (in the latter case $! is set). If FILEHANDLE is omitted, reads from STDIN. This is not particularly efficient. However, it cannot be used by itself to fetch single characters without waiting for the user to hit enter. For that, try something more like:

FILEHANDLE につながれている入力ファイルから、次の一文字を返します; ファイルの最後、またはエラーが発生した場合は、未定義値を返します (後者の場合は $! がセットされます)。 FILEHANDLE が省略された場合には、STDIN から読み込みを行ないます。 これは特に効率的ではありません。 しかし、これはユーザーがリターンキーを押すのを待つことなく 一文字を読み込む用途には使えません。 そのような場合には、以下のようなものを試して見てください:

    if ($BSD_STYLE) {
        system "stty cbreak </dev/tty >/dev/tty 2>&1";
    }
    else {
        system "stty", '-icanon', 'eol', "\001";
    }

    my $key = getc(STDIN);

    if ($BSD_STYLE) {
        system "stty -cbreak </dev/tty >/dev/tty 2>&1";
    }
    else {
        system 'stty', 'icanon', 'eol', '^@'; # ASCII NUL
    }
    print "\n";

Determination of whether $BSD_STYLE should be set is left as an exercise to the reader.

$BSD_STYLE をセットするべきかどうかを決定する方法については 読者への宿題として残しておきます。

The POSIX::getattr function can do this more portably on systems purporting POSIX compliance. See also the Term::ReadKey module on CPAN.

POSIX::getattr 関数は POSIX 準拠を主張するシステムで これをより移植性のある形で行います。 CPAN にある Term::ReadKey モジュールも 参照してください。

getlogin

This implements the C library function of the same name, which on most systems returns the current login from /etc/utmp, if any. If it returns the empty string, use getpwuid.

これは同じ名前の C ライブラリ関数を実装していて、 多くのシステムでは、もしあれば、/etc/utmp から現在のログイン名を返します。 もし空文字列が返ってきた場合は、getpwuid を 使ってください。

    my $login = getlogin || getpwuid($<) || "Kilroy";

Do not consider getlogin for authentication: it is not as secure as getpwuid.

getlogin を認証に使ってはいけません: これは getpwuid のように安全ではありません。

Portability issues: "getlogin" in perlport.

移植性の問題: "getlogin" in perlport

getpeername SOCKET

Returns the packed sockaddr address of the other end of the SOCKET connection.

SOCKET コネクションの向こう側のパックされた aockaddr アドレスを返します。

    use Socket;
    my $hersockaddr    = getpeername($sock);
    my ($port, $iaddr) = sockaddr_in($hersockaddr);
    my $herhostname    = gethostbyaddr($iaddr, AF_INET);
    my $herstraddr     = inet_ntoa($iaddr);
getpgrp PID

Returns the current process group for the specified PID. Use a PID of 0 to get the current process group for the current process. Will raise an exception if used on a machine that doesn't implement getpgrp(2). If PID is omitted, returns the process group of the current process. Note that the POSIX version of getpgrp does not accept a PID argument, so only PID==0 is truly portable.

指定された PID の現在のプロセスグループを返します。 PID に 0 を与えるとカレントプロセスの指定となります。 getpgrp(2) を実装していないマシンで実行した場合には、例外が発生します。 PID を省略するとカレントプロセスのプロセスグループを返します。 POSIX 版の getpgrp は PID 引数を受け付けないので、 PID==0 のみが完全に移植性があります。

Portability issues: "getpgrp" in perlport.

移植性の問題: "getpgrp" in perlport

getppid

Returns the process id of the parent process.

親プロセスのプロセス id を返します。

Note for Linux users: Between v5.8.1 and v5.16.0 Perl would work around non-POSIX thread semantics the minority of Linux systems (and Debian GNU/kFreeBSD systems) that used LinuxThreads, this emulation has since been removed. See the documentation for $$ for details.

Linux ユーザーへの注意: v5.8.1 から v5.16.0 の間 Perl は LinuxThreads という非 POSIX なスレッド文法を使っているマイナーな Linux システム (および Debian GNU/kFreeBSD システム) に対応していました。 このエミュレーションは削除されました; 詳しくは $$ の文書を参照してください。

Portability issues: "getppid" in perlport.

移植性の問題: "getppid" in perlport

getpriority WHICH,WHO

Returns the current priority for a process, a process group, or a user. (See getpriority(2).) Will raise a fatal exception if used on a machine that doesn't implement getpriority(2).

プロセス、プロセスグループ、ユーザに対する現在の優先度を返します。 (getpriority(2) を参照してください。) getpriority(2) を実装していない マシンで実行した場合には、致命的例外が発生します。

WHICH can be any of PRIO_PROCESS, PRIO_PGRP or PRIO_USER imported from "RESOURCE CONSTANTS" in POSIX.

WHICH"RESOURCE CONSTANTS" in POSIX からインポートされた PRIO_PROCESS, PRIO_PGRP, PRIO_USER のいずれかです。

Portability issues: "getpriority" in perlport.

移植性の問題: "getpriority" in perlport

getpwnam NAME
getgrnam NAME
gethostbyname NAME
getnetbyname NAME
getprotobyname NAME
getpwuid UID
getgrgid GID
getservbyname NAME,PROTO
gethostbyaddr ADDR,ADDRTYPE
getnetbyaddr ADDR,ADDRTYPE
getprotobynumber NUMBER
getservbyport PORT,PROTO
getpwent
getgrent
gethostent
getnetent
getprotoent
getservent
setpwent
setgrent
sethostent STAYOPEN
setnetent STAYOPEN
setprotoent STAYOPEN
setservent STAYOPEN
endpwent
endgrent
endhostent
endnetent
endprotoent
endservent

These routines are the same as their counterparts in the system C library. In list context, the return values from the various get routines are as follows:

これらのルーチンは、システムの C ライブラリの同名の関数と同じです。 リストコンテキストでは、さまざまな get ルーチンからの返り値は、次のようになります:

 #    0        1          2           3         4
 my ( $name,   $passwd,   $gid,       $members  ) = getgr*
 my ( $name,   $aliases,  $addrtype,  $net      ) = getnet*
 my ( $name,   $aliases,  $port,      $proto    ) = getserv*
 my ( $name,   $aliases,  $proto                ) = getproto*
 my ( $name,   $aliases,  $addrtype,  $length,  @addrs ) = gethost*
 my ( $name,   $passwd,   $uid,       $gid,     $quota,
    $comment,  $gcos,     $dir,       $shell,   $expire ) = getpw*
 #    5        6          7           8         9

(If the entry doesn't exist, the return value is a single meaningless true value.)

(エントリが存在しなければ、返り値は単一の意味のない真の値です。)

The exact meaning of the $gcos field varies but it usually contains the real name of the user (as opposed to the login name) and other information pertaining to the user. Beware, however, that in many system users are able to change this information and therefore it cannot be trusted and therefore the $gcos is tainted (see perlsec). The $passwd and $shell, user's encrypted password and login shell, are also tainted, for the same reason.

$gcos フィールドの正確な意味はさまざまですが、通常は(ログイン名ではなく) ユーザーの実際の名前とユーザーに付随する情報を含みます。 但し、多くのシステムではユーザーがこの情報を変更できるので、この情報は 信頼できず、従って $gcos は汚染されます(perlsec を参照してください)。 ユーザーの暗号化されたパスワードとログインシェルである $passwd と $shell も、同様の理由で汚染されます。

In scalar context, you get the name, unless the function was a lookup by name, in which case you get the other thing, whatever it is. (If the entry doesn't exist you get the undefined value.) For example:

スカラコンテキストでは、*nam、*byname といった NAME で検索するもの以外は、 name を返し、NAME で検索するものは、何か別のものを返します。 (エントリが存在しなければ、未定義値が返ります。) 例えば:

    my $uid   = getpwnam($name);
    my $name  = getpwuid($num);
    my $name  = getpwent();
    my $gid   = getgrnam($name);
    my $name  = getgrgid($num);
    my $name  = getgrent();
    # etc.

In getpw*() the fields $quota, $comment, and $expire are special in that they are unsupported on many systems. If the $quota is unsupported, it is an empty scalar. If it is supported, it usually encodes the disk quota. If the $comment field is unsupported, it is an empty scalar. If it is supported it usually encodes some administrative comment about the user. In some systems the $quota field may be $change or $age, fields that have to do with password aging. In some systems the $comment field may be $class. The $expire field, if present, encodes the expiration period of the account or the password. For the availability and the exact meaning of these fields in your system, please consult getpwnam(3) and your system's pwd.h file. You can also find out from within Perl what your $quota and $comment fields mean and whether you have the $expire field by using the Config module and the values d_pwquota, d_pwage, d_pwchange, d_pwcomment, and d_pwexpire. Shadow password files are supported only if your vendor has implemented them in the intuitive fashion that calling the regular C library routines gets the shadow versions if you're running under privilege or if there exists the shadow(3) functions as found in System V (this includes Solaris and Linux). Those systems that implement a proprietary shadow password facility are unlikely to be supported.

getpw*() では、$quota, $comment, $expire フィールドは、 多くのシステムでは対応していないので特別な処理がされます。 $quota が非対応の場合、空のスカラになります。 対応している場合、通常はディスククォータの値が入ります。 $comment フィールドが非対応の場合、空のスカラになります。 対応している場合、通常はユーザーに関する管理上のコメントが入ります。 $quota フィールドはパスワードの寿命を示す $change や $age である システムもあります。 $comment フィールドは $class であるシステムもあります。 $expire フィールドがある場合は、アカウントやパスワードが時間切れになる 期間が入ります。 動作させるシステムでのこれらのフィールドの有効性と正確な意味については、 getpwnam(3) のドキュメントと pwd.h ファイルを参照してください。 $quota と $comment フィールドが何を意味しているかと、$expire フィールドが あるかどうかは、Config モジュールを使って、d_pwquota, d_pwage, d_pwchange, d_pwcomment, d_pwexpire の値を 調べることによって Perl 自身で調べることも出来ます。 シャドウパスワードは、通常の C ライブラリルーチンを権限がある状態で 呼び出すことでシャドウ版が取得できるか、System V にあるような (Solaris と Linux を含みます) shadow(3) 関数があるといった、 直感的な方法で実装されている場合にのみ対応されます。 独占的なシャドウパスワード機能を実装しているシステムでは、 それに対応されることはないでしょう。

The $members value returned by getgr*() is a space-separated list of the login names of the members of the group.

getgr*() によって返る値 $members は、グループのメンバの ログイン名をスペースで区切ったものです。

For the gethost*() functions, if the h_errno variable is supported in C, it will be returned to you via $? if the function call fails. The @addrs value returned by a successful call is a list of raw addresses returned by the corresponding library call. In the Internet domain, each address is four bytes long; you can unpack it by saying something like:

gethost*() 関数では、C で h_errno 変数がサポートされていれば、 関数呼出が失敗したときに、$? を通して、その値が返されます。 成功時に返される @addrs 値は、対応するシステムコールが返す、 生のアドレスのリストです。 インターネットドメインでは、個々のアドレスは、4 バイト長です; 以下のようにして unpack することができます:

    my ($w,$x,$y,$z) = unpack('W4',$addr[0]);

The Socket library makes this slightly easier:

Socket ライブラリを使うともう少し簡単になります。

    use Socket;
    my $iaddr = inet_aton("127.1"); # or whatever address
    my $name  = gethostbyaddr($iaddr, AF_INET);

    # or going the other way
    my $straddr = inet_ntoa($iaddr);

In the opposite way, to resolve a hostname to the IP address you can write this:

逆方向に、ホスト名から IP アドレスを解決するには以下のように書けます:

    use Socket;
    my $packed_ip = gethostbyname("www.perl.org");
    my $ip_address;
    if (defined $packed_ip) {
        $ip_address = inet_ntoa($packed_ip);
    }

Make sure gethostbyname is called in SCALAR context and that its return value is checked for definedness.

gethostbyname はスカラコンテキストで 呼び出すようにして、返り値が定義されているかを必ずチェックしてください。

The getprotobynumber function, even though it only takes one argument, has the precedence of a list operator, so beware:

getprotobynumber 関数は、一つの引数しか 取らないにも関わらず、リスト演算子の優先順位を持ちます; 従って 注意してください:

    getprotobynumber $number eq 'icmp'   # WRONG
    getprotobynumber($number eq 'icmp')  # actually means this
    getprotobynumber($number) eq 'icmp'  # better this way

If you get tired of remembering which element of the return list contains which return value, by-name interfaces are provided in standard modules: File::stat, Net::hostent, Net::netent, Net::protoent, Net::servent, Time::gmtime, Time::localtime, and User::grent. These override the normal built-ins, supplying versions that return objects with the appropriate names for each field. For example:

返り値のリストの何番目がどの要素かを覚えるのに疲れたなら、 名前ベースのインターフェースが標準モジュールで提供されています: File::stat, Net::hostent, Net::netent, Net::protoent, Net::servent, Time::gmtime, Time::localtime, User::grent です。 これらは通常の組み込みを上書きし、 それぞれのフィールドに適切な名前をつけたオブジェクトを返します。 例えば:

   use File::stat;
   use User::pwent;
   my $is_his = (stat($filename)->uid == pwent($whoever)->uid);

Even though it looks as though they're the same method calls (uid), they aren't, because a File::stat object is different from a User::pwent object.

同じメソッド(uid)を呼び出しているように見えますが、違います; なぜなら File::stat オブジェクトは User::pwent オブジェクトとは 異なるからです。

Many of these functions are not safe in a multi-threaded environment where more than one thread can be using them. In particular, functions like getpwent() iterate per-process and not per-thread, so if two threads are simultaneously iterating, neither will get all the records.

これらの関数の多くは、複数のスレッドがこれらを使うような マルチスレッド環境では安全ではありません。 特に、 getpwent() のような関数はスレッド単位ではなくプロセス単位で 反復するので、二つのスレッドが同時に反復すると、 どちらも全てのレコードを得られません。

Some systems have thread-safe versions of some of the functions, such as getpwnam_r() instead of getpwnam(). There, Perl automatically and invisibly substitutes the thread-safe version, without notice. This means that code that safely runs on some systems can fail on others that lack the thread-safe versions.

一部のシステムは、 getpwnam() の代わりの getpwnam_r() のように、一部の関数について スレッドセーフ版を持っています。 その場合、Perl は自動的かつ目に見えないように、通知なしで スレッドセーフ版に置き換えます。 つまり、一部のシステムで安全に実行できるコードが スレッドセーフ版のないその他のシステムでは失敗することがあるということです。

移植性の問題: "getpwnam" in perlport から "endservent" in perlport

getsockname SOCKET

Returns the packed sockaddr address of this end of the SOCKET connection, in case you don't know the address because you have several different IPs that the connection might have come in on.

SOCKET 接続のこちら側の pack された sockaddr アドレスを返します; 複数の異なる IP から接続されるためにアドレスがわからない場合に使います。

    use Socket;
    my $mysockaddr = getsockname($sock);
    my ($port, $myaddr) = sockaddr_in($mysockaddr);
    printf "Connect to %s [%s]\n",
       scalar gethostbyaddr($myaddr, AF_INET),
       inet_ntoa($myaddr);
getsockopt SOCKET,LEVEL,OPTNAME

Queries the option named OPTNAME associated with SOCKET at a given LEVEL. Options may exist at multiple protocol levels depending on the socket type, but at least the uppermost socket level SOL_SOCKET (defined in the Socket module) will exist. To query options at another level the protocol number of the appropriate protocol controlling the option should be supplied. For example, to indicate that an option is to be interpreted by the TCP protocol, LEVEL should be set to the protocol number of TCP, which you can get using getprotobyname.

与えられた LEVEL で SOCKET に関連付けられた OPTNAME と言う名前のオプションを 問い合わせます。 オプションはソケットの種類に依存しした複数のプロトコルレベルに存在することも ありますが、少なくとも最上位ソケットレベル SOL_SOCKET (Socket モジュールで定義されています)は存在します。 その他のレベルのオプションを問い合わせるには、そのオプションを制御する 適切なプロトコルのプロトコル番号を指定します。 例えば、オプションが TCP プロトコルで解釈されるべきであることを示すためには、 LEVEL は getprotobyname で得られる TCP の プロトコル番号を設定します。

The function returns a packed string representing the requested socket option, or undef on error, with the reason for the error placed in $!. Just what is in the packed string depends on LEVEL and OPTNAME; consult getsockopt(2) for details. A common case is that the option is an integer, in which case the result is a packed integer, which you can decode using unpack with the i (or I) format.

この関数は、要求されたソケットオプションの pack された文字列表現か、 あるいはエラーの場合は undef を返し、エラーの理由は $! にあります。 pack された文字列の中身は LEVEL と OPTNAME に依存します; 詳細については getsockopt(2) を確認してください。 一般的な場合はオプションが整数の場合で、この場合結果は unpacki (あるいは I)フォーマットでデコードできる pack された整数です。

Here's an example to test whether Nagle's algorithm is enabled on a socket:

あるソケットで Nagle のアルゴリズム有効かどうかを調べる例です:

    use Socket qw(:all);

    defined(my $tcp = getprotobyname("tcp"))
        or die "Could not determine the protocol number for tcp";
    # my $tcp = IPPROTO_TCP; # Alternative
    my $packed = getsockopt($socket, $tcp, TCP_NODELAY)
        or die "getsockopt TCP_NODELAY: $!";
    my $nodelay = unpack("I", $packed);
    print "Nagle's algorithm is turned ",
           $nodelay ? "off\n" : "on\n";

Portability issues: "getsockopt" in perlport.

移植性の問題: "getsockopt" in perlport

glob EXPR
glob

In list context, returns a (possibly empty) list of filename expansions on the value of EXPR such as the standard Unix shell /bin/csh would do. In scalar context, glob iterates through such filename expansions, returning undef when the list is exhausted. This is the internal function implementing the <*.c> operator, but you can use it directly. If EXPR is omitted, $_ is used. The <*.c> operator is discussed in more detail in "I/O Operators" in perlop.

リストコンテキストでは、 EXPR の値を、標準 Unix シェル /bin/csh が行なうように ファイル名の展開を行なった結果のリスト(空かもしれません)を返します。 スカラコンテキストでは、glob はこのようなファイル名展開を繰り返し、 リストがなくなったら undef を返します。 これは、<*.c> 演算子を実装する内部関数ですが、 直接使用することもできます。 EXPR が省略されると、$_ が使われます。 <*.c>演算子については "I/O Operators" in perlop でより詳細に議論しています。

Note that glob splits its arguments on whitespace and treats each segment as separate pattern. As such, glob("*.c *.h") matches all files with a .c or .h extension. The expression glob(".* *") matches all files in the current working directory. If you want to glob filenames that might contain whitespace, you'll have to use extra quotes around the spacey filename to protect it. For example, to glob filenames that have an e followed by a space followed by an f, use one of:

glob は引数を空白で分割して、それぞれを分割された パターンとして扱います。 従って、glob("*.c *.h").c または .h 拡張子を持つ全てのファイルに マッチングします。 式 glob(".* *") はカレントワーキングディレクトリの全てのファイルに マッチングします。 空白を含んでいるかも知れないファイル名をグロブしたい場合、それを守るために 空白入りファイル名の周りに追加のクォートを使う必要があります。 例えば、e の後に空白、その後に f というファイル名をグロブするには 以下の一つを使います:

    my @spacies = <"*e f*">;
    my @spacies = glob '"*e f*"';
    my @spacies = glob q("*e f*");

If you had to get a variable through, you could do this:

変数を通す必要があった場合、以下のようにできました:

    my @spacies = glob "'*${var}e f*'";
    my @spacies = glob qq("*${var}e f*");

If non-empty braces are the only wildcard characters used in the glob, no filenames are matched, but potentially many strings are returned. For example, this produces nine strings, one for each pairing of fruits and colors:

空でない中かっこが glob で使われている唯一の ワイルドカード文字列の場合、ファイル名とはマッチングせず、 可能性のある文字列が返されます。 例えば、これは 9 個の文字列を生成し、それぞれは果物と色の組み合わせに なります:

    my @many = glob "{apple,tomato,cherry}={green,yellow,red}";

This operator is implemented using the standard File::Glob extension. See File::Glob for details, including bsd_glob, which does not treat whitespace as a pattern separator.

v5.6.0 から、この演算子は標準の File::Glob 拡張を使って 実装されています。 空白をパターンのセパレータとして扱わない bsd_glob を含めた 詳細は File::Glob を参照してください。

If a glob expression is used as the condition of a while or for loop, then it will be implicitly assigned to $_. If either a glob expression or an explicit assignment of a glob expression to a scalar is used as a while/for condition, then the condition actually tests for definedness of the expression's value, not for its regular truth value.

glob 式が whilefor ループの条件として使われた場合、 これは暗黙に $_ に代入されます。 glob 式または glob 式からスカラへの明示的な代入が while/for の条件部として使われた場合、 条件は通常の真の値かどうかではなく、式の値が定義されているかどうかを テストします。

Portability issues: "glob" in perlport.

移植性の問題: "glob" in perlport

gmtime EXPR
gmtime

Works just like localtime but the returned values are localized for the standard Greenwich time zone.

localtime と同様に働きますが、返り値はグリニッジ標準時に ローカライズされています。

Note: When called in list context, $isdst, the last value returned by gmtime, is always 0. There is no Daylight Saving Time in GMT.

注意: リストコンテキストで呼び出した時、gmtime が返す末尾の値である $isdst は常に 0 です。 GMT には夏時間はありません。

Portability issues: "gmtime" in perlport.

移植性の問題: "gmtime" in perlport

goto LABEL
goto EXPR
goto &NAME

The goto LABEL form finds the statement labeled with LABEL and resumes execution there. It can't be used to get out of a block or subroutine given to sort. It can be used to go almost anywhere else within the dynamic scope, including out of subroutines, but it's usually better to use some other construct such as last or die. The author of Perl has never felt the need to use this form of goto (in Perl, that is; C is another matter). (The difference is that C does not offer named loops combined with loop control. Perl does, and this replaces most structured uses of goto in other languages.)

goto LABEL の形式は、LABEL というラベルの付いた文を 探して、そこへ実行を移すものです。 sort で与えられたブロックやサブルーチンから外へ 出ることはできません。 これ以外は、サブルーチンの外を含む、動的スコープ内の ほとんどすべての場所へ行くために使用できますが、普通は、 lastdie といった別の構造を使った方が 良いでしょう。 Perl の作者はこの形式の goto を使う必要を感じたことは、 1 度もありません (Perl では; C は別のお話です)。 (違いは、C にはループ制御と結びついた名前つきのループがないことです。 Perl にはあり、これが他の言語でのほとんどの構造的な goto の 使用法を置き換えます。)

The goto EXPR form expects to evaluate EXPR to a code reference or a label name. If it evaluates to a code reference, it will be handled like goto &NAME, below. This is especially useful for implementing tail recursion via goto __SUB__.

goto EXPR の形式は、EXPR をコードリファレンスまたはラベル名として 評価することを想定します。 コードリファレンスとして評価する場合、後述する goto &NAME のように 扱います。 これは特に、goto __SUB__ による末尾再帰の実装に有用です。

If the expression evaluates to a label name, its scope will be resolved dynamically. This allows for computed gotos per FORTRAN, but isn't necessarily recommended if you're optimizing for maintainability:

式がラベル名に評価される場合、このスコープは動的に解決されます。 これにより FORTRAN のような算術 goto が可能になりますが、 保守性を重視するならお勧めしません。

    goto ("FOO", "BAR", "GLARCH")[$i];

As shown in this example, goto EXPR is exempt from the "looks like a function" rule. A pair of parentheses following it does not (necessarily) delimit its argument. goto("NE")."XT" is equivalent to goto NEXT. Also, unlike most named operators, this has the same precedence as assignment.

この例で示したように、goto EXPR は「関数のように見える」ルールから 除外されます。 これに引き続くかっこの組は引数の区切りとは(必ずしも)なりません。 goto("NE")."XT"goto NEXT と等価です。 また、ほとんどの名前付き演算子と異なり、これは代入と同じ優先順位を持ちます。

Use of goto LABEL or goto EXPR to jump into a construct is deprecated and will issue a warning. Even then, it may not be used to go into any construct that requires initialization, such as a subroutine, a foreach loop, or a given block. In general, it may not be used to jump into the parameter of a binary or list operator, but it may be used to jump into the first parameter of a binary operator. (The = assignment operator's "first" operand is its right-hand operand.) It also can't be used to go into a construct that is optimized away.

構造の中に飛び込むために goto LABELgoto EXPR を使うことは 非推奨で、警告が発生します。 それでも、サブルーチンや foreach ループや given ブロックのような、 初期化が必要な 構造の中に入るために使うことは出来ません。 一般的に、2 項演算子やリスト演算子の引数に飛び込むことはできませんが、 2 項演算子の 最初の 引数に飛び込むために使われていました。 (= 代入演算子の「最初の」オペランドはその右オペランドです。) また、最適化してなくなってしまった構造の中へ入るために使うことも出来ません。

The goto &NAME form is quite different from the other forms of goto. In fact, it isn't a goto in the normal sense at all, and doesn't have the stigma associated with other gotos. Instead, it exits the current subroutine (losing any changes set by local) and immediately calls in its place the named subroutine using the current value of @_. This is used by AUTOLOAD subroutines that wish to load another subroutine and then pretend that the other subroutine had been called in the first place (except that any modifications to @_ in the current subroutine are propagated to the other subroutine.) After the goto, not even caller will be able to tell that this routine was called first.

goto &NAME の形式は、その他の goto の形式とはかなり 異なったものです。 実際、これは普通の感覚でいうところのどこかへ行くものでは全くなく、 他の goto が持つ不名誉を持っていません。 現在のサブルーチンを終了し (local による変更は失われます)、 直ちに現在の @_ の値を使って指定された名前のサブルーチンを 呼び出します。 これは、AUTOLOAD サブルーチンが別のサブルーチンをロードして、 その別のサブルーチンが最初に呼ばれたようにするために使われます (ただし、現在のサブルーチンで @_ を修正した場合には、 その別のサブルーチンに伝えられます)。 goto のあとは、caller でさえも、現在の サブルーチンが最初に呼び出されたと言うことができません。

NAME needn't be the name of a subroutine; it can be a scalar variable containing a code reference or a block that evaluates to a code reference.

NAME はサブルーチンの名前である必要はありません; コードリファレンスを 含むスカラ値や、コードリファレンスと評価されるブロックでも構いません。

grep BLOCK LIST
grep EXPR,LIST

This is similar in spirit to, but not the same as, grep(1) and its relatives. In particular, it is not limited to using regular expressions.

これは grep(1) とその親類と同じようなものですが、同じではありません。 特に、正規表現の使用に制限されません。

Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and returns the list value consisting of those elements for which the expression evaluated to true. In scalar context, returns the number of times the expression was true.

LIST の個々の要素に対して、BLOCK か EXPR を評価し ($_ は、ローカルに個々の要素が設定されます) 、 その要素のうち、評価した式が真となったものからなるリスト値が返されます。 スカラコンテキストでは、式が真となった回数を返します。

    my @foo = grep(!/^#/, @bar);    # weed out comments

or equivalently,

あるいは等価な例として:

    my @foo = grep {!/^#/} @bar;    # weed out comments

Note that $_ is an alias to the list value, so it can be used to modify the elements of the LIST. While this is useful and supported, it can cause bizarre results if the elements of LIST are not variables. Similarly, grep returns aliases into the original list, much as a for loop's index variable aliases the list elements. That is, modifying an element of a list returned by grep (for example, in a foreach, map or another grep) actually modifies the element in the original list. This is usually something to be avoided when writing clear code.

$_ は、LIST の値へのエイリアスですので、LIST の要素を 変更するために使うことができます。 これは、便利でサポートされていますが、 LIST の要素が変数でないと、おかしな結果になります。 同様に、grep は元のリストへのエイリアスを返します; for ループの インデックス変数がリスト要素のエイリアスであるのと同様です。 つまり、grep で返されたリストの要素を (foreach, map, または他の grep で)修正すると元のリストの要素が変更されます。 これはきれいなコードを書くときには普通は回避されます。

See also map for a list composed of the results of the BLOCK or EXPR.

BLOCK や EXPR の結果をリストの形にしたい場合は map を 参照してください。

hex EXPR
hex

Interprets EXPR as a hex string and returns the corresponding numeric value. If EXPR is omitted, uses $_.

EXPR を 16 進数の文字列と解釈して、対応する数値を返します。 EXPR が省略されると、$_ を使います。

    print hex '0xAf'; # prints '175'
    print hex 'aF';   # same
    $valid_input =~ /\A(?:0?[xX])?(?:_?[0-9a-fA-F])*\z/

A hex string consists of hex digits and an optional 0x or x prefix. Each hex digit may be preceded by a single underscore, which will be ignored. Any other character triggers a warning and causes the rest of the string to be ignored (even leading whitespace, unlike oct). Only integers can be represented, and integer overflow triggers a warning.

16 進文字列は 16 進数と、オプションの 0x または x 接頭辞からなります。 それぞれの 16 進数は一つの下線を前に置くことができ、これは無視されます。 その他の文字は警告を引き起こし、(例え先頭の空白でも、oct と 異なり)文字列の残りの部分は無視されます。 整数のみを表現でき、整数オーバーフローは警告を引き起こします。

To convert strings that might start with any of 0, 0x, or 0b, see oct. To present something as hex, look into printf, sprintf, and unpack.

0, 0x, 0b のいずれかで始まるかもしれない文字列を変換するには、 oct を参照してください。 何かを 16 進で表現したい場合は、printf, sprintf, unpack を 参照してください。

import LIST

There is no builtin import function. It is just an ordinary method (subroutine) defined (or inherited) by modules that wish to export names to another module. The use function calls the import method for the package used. See also use, perlmod, and Exporter.

組み込みの import 関数というものはありません。 これは単に、別のモジュールに名前をエクスポートしたいモジュールが 定義した(または継承した)、通常のメソッド(サブルーチン)です。 use 関数はパッケージを使う時に import メソッドを呼び出します。 use, perlmod, Exporter も 参照してください。

index STR,SUBSTR,POSITION
index STR,SUBSTR

The index function searches for one string within another, but without the wildcard-like behavior of a full regular-expression pattern match. It returns the position of the first occurrence of SUBSTR in STR at or after POSITION. If POSITION is omitted, starts searching from the beginning of the string. POSITION before the beginning of the string or after its end is treated as if it were the beginning or the end, respectively. POSITION and the return value are based at zero. If the substring is not found, index returns -1.

index 関数は ある文字列をもうひとつの文字列から検索しますが、 完全正規表現パターンマッチのワイルドカード的な振る舞いはしません。 STR の中の POSITION の位置以降で、最初に SUBSTR が見つかった位置を返します。 POSITION が省略された場合には、STR の最初から探し始めます。 POSITION が文字列の先頭より前、あるいは末尾より後ろを指定した場合は、 それぞれ先頭と末尾を指定されたものとして扱われます。 POSITION と返り値のベースは、0 です。 SUBSTR が見つからなかった場合には、index は -1 が返されます。

int EXPR
int

Returns the integer portion of EXPR. If EXPR is omitted, uses $_. You should not use this function for rounding: one because it truncates towards 0, and two because machine representations of floating-point numbers can sometimes produce counterintuitive results. For example, int(-6.725/0.025) produces -268 rather than the correct -269; that's because it's really more like -268.99999999999994315658 instead. Usually, the sprintf, printf, or the POSIX::floor and POSIX::ceil functions will serve you better than will int.

EXPR の整数部を返します。 EXPR が省略されると、$_ を使います。 この関数を丸めのために使うべきではありません: 第一の理由として 0 の 方向への切捨てを行うから、第二の理由として浮動小数点数の機械表現は時々直感に 反した結果を生み出すからです。 たとえば、int(-6.725/0.025) は正しい結果である -269 ではなく -268 を 返します: これは実際には -268.99999999999994315658 というような値に なっているからです。 通常、sprintf, printf, POSIX::floor, POSIX::ceil の方が int より便利です。

ioctl FILEHANDLE,FUNCTION,SCALAR

Implements the ioctl(2) function. You'll probably first have to say

ioctl(2) 関数を実装します。 正しい関数の定義を得るために、おそらく最初に

    require "sys/ioctl.ph";  # probably in
                             # $Config{archlib}/sys/ioctl.ph

to get the correct function definitions. If sys/ioctl.ph doesn't exist or doesn't have the correct definitions you'll have to roll your own, based on your C header files such as <sys/ioctl.h>. (There is a Perl script called h2ph that comes with the Perl kit that may help you in this, but it's nontrivial.) SCALAR will be read and/or written depending on the FUNCTION; a C pointer to the string value of SCALAR will be passed as the third argument of the actual ioctl call. (If SCALAR has no string value but does have a numeric value, that value will be passed rather than a pointer to the string value. To guarantee this to be true, add a 0 to the scalar before using it.) The pack and unpack functions may be needed to manipulate the values of structures used by ioctl.

としなくてはならないでしょう。 sys/ioctl.ph がないか、間違った定義をしている場合には、 <sys/ioctl.h>のような C のヘッダファイルをもとに、 自分で作らなければなりません。 (Perl の配布キットに入っている h2ph という Perl スクリプトが これを手助けしてくれるでしょうが、これは自明ではありません。) FOUNCTION に応じて SCALAR が読み書きされます; SCALAR の文字列値へのポインタが、実際の ioctl コールの 3 番目の引数として渡されます。 (SCALAR が文字列値を持っておらず、数値を持っている場合には、 文字列値へのポインタの代わりに、その値が渡されます。 このことを保証するためには、使用する前に SCALAR に0 を足してください。) ioctl で使われる構造体の値を 操作するには、pack 関数と unpack 関数が必要となるでしょう。

The return value of ioctl (and fcntl) is as follows:

ioctl (と fcntl) の返り値は、 以下のようになります:

    if OS returns:      then Perl returns:
        -1               undefined value
         0              string "0 but true"
    anything else           that number
    OS が返した値:      Perl が返す値:
        -1               未定義値
         0               「0 だが真」の文字列
    その他                  その値そのもの

Thus Perl returns true on success and false on failure, yet you can still easily determine the actual value returned by the operating system:

つまり Perl は、成功時に「真」、失敗時に「偽」を返す ことになり、OS が実際に返した値も、以下のように簡単に知ることができます。

    my $retval = ioctl(...) || -1;
    printf "System returned %d\n", $retval;

The special string "0 but true" is exempt from Argument "..." isn't numeric warnings on improper numeric conversions.

特別な文字列 "0 だが真" は、不適切な数値変換に関する Argument "..." isn't numeric warnings 警告を回避します。

Portability issues: "ioctl" in perlport.

移植性の問題: "ioctl" in perlport

join EXPR,LIST

Joins the separate strings of LIST into a single string with fields separated by the value of EXPR, and returns that new string. Example:

LIST の個別の文字列を、EXPR の値で区切って 1 つの文字列につなげ、その文字列を返します。 例:

   my $rec = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);

Beware that unlike split, join doesn't take a pattern as its first argument. Compare split.

split と違って、 join は最初の引数にパターンは取れないことに 注意してください。 split と比較してください。

keys HASH
keys ARRAY

Called in list context, returns a list consisting of all the keys of the named hash, or in Perl 5.12 or later only, the indices of an array. Perl releases prior to 5.12 will produce a syntax error if you try to use an array argument. In scalar context, returns the number of keys or indices.

リストコンテキストで呼び出されると、指定したハッシュのすべてのキー、あるいは Perl 5.12 以降でのみ、配列のインデックスからなるリストを返します。 5.12 より前の Perl は配列引数を使おうとすると文法エラーを出力します。 スカラコンテキストでは、キーやインデックスの数を返します。

Hash entries are returned in an apparently random order. The actual random order is specific to a given hash; the exact same series of operations on two hashes may result in a different order for each hash. Any insertion into the hash may change the order, as will any deletion, with the exception that the most recent key returned by each or keys may be deleted without changing the order. So long as a given hash is unmodified you may rely on keys, values and each to repeatedly return the same order as each other. See "Algorithmic Complexity Attacks" in perlsec for details on why hash order is randomized. Aside from the guarantees provided here the exact details of Perl's hash algorithm and the hash traversal order are subject to change in any release of Perl. Tied hashes may behave differently to Perl's hashes with respect to changes in order on insertion and deletion of items.

ハッシュ要素は見かけ上、ランダムな順序で返されます。 実際のランダムな順序はハッシュに固有です; 二つのハッシュに全く同じ一連の 操作を行っても、ハッシュによって異なった順序になります。 ハッシュへの挿入によって順序が変わることがあります; 削除も同様ですが、 each または keys によって返されたもっとも 最近のキーは順序を変えることなく削除できます。 ハッシュが変更されない限り、keys, values, each が繰り返し同じ順序で 返すことに依存してもかまいません。 なぜハッシュの順序がランダム化されているかの詳細については "Algorithmic Complexity Attacks" in perlsec を参照してください。 ここで保証したことを除いて、Perl のハッシュアルゴリズムとハッシュ横断順序の 正確な詳細は Perl のリリースによって変更される可能性があります。 tie されたハッシュは、アイテムの挿入と削除の順序に関して Perl のハッシュと 異なった振る舞いをします。

As a side effect, calling keys resets the internal iterator of the HASH or ARRAY (see each) before yielding the keys. In particular, calling keys in void context resets the iterator with no other overhead.

副作用として、keys の呼び出しは、 キーを取り出す前に HASH や ARRAY の反復子を 初期化します (each を参照してください)。 特に、無効コンテキストで keys を呼び出すと オーバーヘッドなしで反復子を初期化します。

Here is yet another way to print your environment:

環境変数を表示する別の例です:

    my @keys = keys %ENV;
    my @values = values %ENV;
    while (@keys) {
        print pop(@keys), '=', pop(@values), "\n";
    }

or how about sorted by key:

key でソートしてもいいでしょう:

    foreach my $key (sort(keys %ENV)) {
        print $key, '=', $ENV{$key}, "\n";
    }

The returned values are copies of the original keys in the hash, so modifying them will not affect the original hash. Compare values.

返される値はハッシュにある元のキーのコピーなので、 これを変更しても元のハッシュには影響を与えません。 values と比較してください。

To sort a hash by value, you'll need to use a sort function. Here's a descending numeric sort of a hash by its values:

ハッシュを値でソートするためには、sort 関数を使う 必要があります。 以下ではハッシュの値を数値の降順でソートしています:

    foreach my $key (sort { $hash{$b} <=> $hash{$a} } keys %hash) {
        printf "%4d %s\n", $hash{$key}, $key;
    }

Used as an lvalue, keys allows you to increase the number of hash buckets allocated for the given hash. This can gain you a measure of efficiency if you know the hash is going to get big. (This is similar to pre-extending an array by assigning a larger number to $#array.) If you say

左辺値として使うことで、keys を使うことで与えられたハッシュに 割り当てられたハッシュ表の大きさを増やすことができます。 これによって、ハッシュが大きくなっていくなっていくときの 効率の測定ができます。 (これは大きい値を $#array に代入することで配列を予め拡張することに 似ています。) 以下のようにすると:

    keys %hash = 200;

then %hash will have at least 200 buckets allocated for it--256 of them, in fact, since it rounds up to the next power of two. These buckets will be retained even if you do %hash = (), use undef %hash if you want to free the storage while %hash is still in scope. You can't shrink the number of buckets allocated for the hash using keys in this way (but you needn't worry about doing this by accident, as trying has no effect). keys @array in an lvalue context is a syntax error.

%hash は少なくとも 200 の大きさの表が割り当てられます -- 実際には 2 のべき乗に切り上げられるので、256 が割り当てられます。 この表はたとえ %hash = () としても残るので、 もし %hash がスコープにいるうちにこの領域を開放したい場合は undef %hash を使います。 この方法で keys を使うことで、表の大きさを小さくすることは できません (間違えてそのようなことをしても何も起きないので気にすることはありません)。 左辺値コンテキストでの keys @array は文法エラーとなります。

Starting with Perl 5.14, an experimental feature allowed keys to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.

Perl 5.14 から、keys がスカラ式を取ることが出来るという 実験的機能がありました。 この実験は失敗と見なされ、Perl 5.24 で削除されました。

To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work only on Perls of a recent vintage:

あなたのコードを以前のバージョンの Perl で実行したユーザーが不思議な 文法エラーで混乱することを避けるために、コードが最近のバージョンの Perl で のみ 動作することを示すためにファイルの先頭に以下のようなことを 書いてください:

    use 5.012;  # so keys/values/each work on arrays

See also each, values, and sort.

each, values, sort も参照してください。

kill SIGNAL, LIST
kill SIGNAL

Sends a signal to a list of processes. Returns the number of arguments that were successfully used to signal (which is not necessarily the same as the number of processes actually killed, e.g. where a process group is killed).

プロセスのリストにシグナルを送ります。 シグナル送信に使われた引数の数を返します (例えばプロセスグループが kill された場合のように、実際に kill された プロセスの数と同じとは限りません)。

    my $cnt = kill 'HUP', $child1, $child2;
    kill 'KILL', @goners;

SIGNAL may be either a signal name (a string) or a signal number. A signal name may start with a SIG prefix, thus FOO and SIGFOO refer to the same signal. The string form of SIGNAL is recommended for portability because the same signal may have different numbers in different operating systems.

SIGNAL はシグナル名(文字列)かシグナル番号のどちらかです。 シグナル名は SIG 接頭辞で始まることがあるので、FOOSIGFOO は同じ シグナルを意味します。 移植性から文字列形式の SIGNAL が推奨されます; 同じシグナルが異なった オペレーティングシステムでは異なった番号になることがあるからです。

A list of signal names supported by the current platform can be found in $Config{sig_name}, which is provided by the Config module. See Config for more details.

現在のプラットフォームが対応しているシグナル名の一覧は、Config モジュールによって提供される $Config{sig_name} にあります。 さらなる詳細については Config を参照してください。

A negative signal name is the same as a negative signal number, killing process groups instead of processes. For example, kill '-KILL', $pgrp and kill -9, $pgrp will send SIGKILL to the entire process group specified. That means you usually want to use positive not negative signals.

負のシグナル名は負のシグナル番号と同じで、 プロセスではなくプロセスグループに対して kill を行ないます。 たとえば、kill '-KILL', $pgrpkill -9, $pgrp は指定された プロセスグループ全体に SIGKILL を送ります。 すなわち、通常は、負のシグナルは用いず、正のシグナルを使うことになります。

If SIGNAL is either the number 0 or the string ZERO (or SIGZERO), no signal is sent to the process, but kill checks whether it's possible to send a signal to it (that means, to be brief, that the process is owned by the same user, or we are the super-user). This is useful to check that a child process is still alive (even if only as a zombie) and hasn't changed its UID. See perlport for notes on the portability of this construct.

SIGNAL が数値 0 か文字列 ZERO (または SIGZERO の場合、プロセスに シグナルは送られませんが、kill は、 シグナルを送ることが 可能 かどうかを調べます (これは、簡単に言うと、 プロセスが同じユーザーに所有されているか、自分がスーパーユーザーであることを 意味します)。 これは子プロセスが(ゾンビとしてだけでも)まだ生きていて、 UID が 変わっていないことを調べる時に有用です。 この構成の移植性に関する注意については perlport を参照してください。

The behavior of kill when a PROCESS number is zero or negative depends on the operating system. For example, on POSIX-conforming systems, zero will signal the current process group, -1 will signal all processes, and any other negative PROCESS number will act as a negative signal number and kill the entire process group specified.

PROCESS 番号が 0 あるいは負数の場合の kill の振る舞いは オペレーティングシステムに依存します。 例えば、POSIX 準拠のシステムでは、0 は現在のプロセスグループにシグナルを送り、 -1 は全てのプロセスにシグナルを送り、それ以外の負数の PROCESS 番号は 負数のシグナル番号として動作し、指定されたプロセスグループ全体を kill します。

If both the SIGNAL and the PROCESS are negative, the results are undefined. A warning may be produced in a future version.

SIGNAL と PROCESS の両方が負数の場合、結果は未定義です。 将来のバージョンでは警告が出るかも知れません。

See "Signals" in perlipc for more details.

詳細は "Signals" in perlipc を参照してください。

On some platforms such as Windows where the fork(2) system call is not available, Perl can be built to emulate fork at the interpreter level. This emulation has limitations related to kill that have to be considered, for code running on Windows and in code intended to be portable.

Windows のような fork(2) が利用不能なシステムでは、Perl は fork をインタプリタレベルでエミュレートします。 エミュレーションは kill に関連して、コードが Windows で実行されて しかしコードが移植性があると考えられるように制限があります。

See perlfork for more details.

さらなる詳細については perlfork を参照してください。

If there is no LIST of processes, no signal is sent, and the return value is 0. This form is sometimes used, however, because it causes tainting checks to be run. But see "Laundering and Detecting Tainted Data" in perlsec.

処理する LIST がない場合、シグナルは送られず、返り値は 0 です。 しかし、この形式は時々使われます; 実行するために汚染チェックを 引き起こすからです。 しかし "Laundering and Detecting Tainted Data" in perlsec を参照してください。

Portability issues: "kill" in perlport.

移植性の問題: "kill" in perlport

last LABEL
last EXPR
last

The last command is like the break statement in C (as used in loops); it immediately exits the loop in question. If the LABEL is omitted, the command refers to the innermost enclosing loop. The last EXPR form, available starting in Perl 5.18.0, allows a label name to be computed at run time, and is otherwise identical to last LABEL. The continue block, if any, is not executed:

last コマンドは、(ループ内で使った) C の break 文と 同じようなもので、LABEL で指定されるループを即座に抜けます。 LABEL が省略されると、コマンドは一番内側のループを参照します。 Perl 5.18.0 から利用可能な last EXPR 形式では、実行時に計算される ラベル名を使えます; それ以外は last LABEL と同一です。 continue ブロックがあっても実行されません:

    LINE: while (<STDIN>) {
        last LINE if /^$/;  # exit when done with header
        #...
    }

last cannot return a value from a block that typically returns a value, such as eval {}, sub {}, or do {}. It will perform its flow control behavior, which precludes any return value. It should not be used to exit a grep or map operation.

lasteval {}, sub {}, do {} といった 典型的には値を返すブロックから値を返せません。 これは、返り値を不可能にするフロー制御の振る舞いを実行します。 grepmap 操作を終了するのに 使うべきではありません。

Note that a block by itself is semantically identical to a loop that executes once. Thus last can be used to effect an early exit out of such a block.

ブロック自身は一回だけ実行されるループと文法的に同一であることに 注意してください。 従って、last でそのようなブロックを途中で 抜け出すことができます。

See also continue for an illustration of how last, next, and redo work.

last, next, redo が どのように働くかについては continue も参照してください。

Unlike most named operators, this has the same precedence as assignment. It is also exempt from the looks-like-a-function rule, so last ("foo")."bar" will cause "bar" to be part of the argument to last.

ほとんどの名前付き演算子と異なり、これは代入と同じ優先順位を持ちます。 また、関数のように見えるものの規則からも免れるので、last ("foo")."bar" と すると "bar" は last への引数の一部となります。

lc EXPR
lc

Returns a lowercased version of EXPR. This is the internal function implementing the \L escape in double-quoted strings.

EXPR を小文字に変換したものを返します。 これは、ダブルクォート文字列における、 \L エスケープを実装する内部関数です。

If EXPR is omitted, uses $_.

EXPR が省略されると、$_ を使います。

What gets returned depends on several factors:

返り値として得られるものは色々な要素に依存します:

If use bytes is in effect:

(use bytes が有効の場合)

The results follow ASCII rules. Only the characters A-Z change, to a-z respectively.

結果は ASCII の規則に従います。 A-Z のみが変換され、それぞれ a-z になります。

Otherwise, if use locale for LC_CTYPE is in effect:

(それ以外の場合で、LC_CTYPE に対して use locale が有効の場合)

Respects current LC_CTYPE locale for code points < 256; and uses Unicode rules for the remaining code points (this last can only happen if the UTF8 flag is also set). See perllocale.

符号位置 < 256 に対しては現在の LC_CTYPE ロケールに従います; そして 残りの符号位置に付いては Unicode の規則を使います (これは UTF8 フラグも 設定されている場合にのみ起こります)。 perllocale を参照してください。

Starting in v5.20, Perl uses full Unicode rules if the locale is UTF-8. Otherwise, there is a deficiency in this scheme, which is that case changes that cross the 255/256 boundary are not well-defined. For example, the lower case of LATIN CAPITAL LETTER SHARP S (U+1E9E) in Unicode rules is U+00DF (on ASCII platforms). But under use locale (prior to v5.20 or not a UTF-8 locale), the lower case of U+1E9E is itself, because 0xDF may not be LATIN SMALL LETTER SHARP S in the current locale, and Perl has no way of knowing if that character even exists in the locale, much less what code point it is. Perl returns a result that is above 255 (almost always the input character unchanged), for all instances (and there aren't many) where the 255/256 boundary would otherwise be crossed; and starting in v5.22, it raises a locale warning.

v5.20 から、ロケールが UTF-8 の場合は Perl は完全な Unicode の規則を使います。 さもなければ、この手法には、255/266 の境界をまたぐ大文字小文字の変換は 未定義であるという欠点があります。 例えば、Unicode での LATIN CAPITAL LETTER SHARP S (U+1E9E) の小文字は (ASCII プラットフォームでは) U+00DF です。 しかし use locale が有効(v5.20 より前か、UTF-8 ロケール以外)なら、U+1E9E の 小文字は自分自身です; なぜなら 0xDF は現在のロケールでは LATIN SMALL LETTER SHARP S ではなく、Perl は例えこのロケールに文字が 存在するかどうかを知る方法がなく、ましてどの符号位置かを知る方法が ないからです。 Perl は 255/256 境界をまたぐ全ての(多くはありません)実体については (ほとんど常に入力文字を変更せずに)256 以上の値を返します; そして v5.22 から locale 警告を出力します。

Otherwise, If EXPR has the UTF8 flag set:

(その他の場合で、EXPR に UTF8 フラグがセットされている場合)

Unicode rules are used for the case change.

大文字小文字変換には Unicode の規則が使われます。

Otherwise, if use feature 'unicode_strings' or use locale ':not_characters' is in effect:

(それ以外の場合で、use feature 'unicode_strings'use locale ':not_characters' が有効の場合)

Unicode rules are used for the case change.

大文字小文字変換には Unicode の規則が使われます。

Otherwise:

(それ以外の場合)

ASCII rules are used for the case change. The lowercase of any character outside the ASCII range is the character itself.

大文字小文字変換には ASCII の規則が使われます。 ASCII の範囲外の文字の「小文字」はその文字自身です。

lcfirst EXPR
lcfirst

Returns the value of EXPR with the first character lowercased. This is the internal function implementing the \l escape in double-quoted strings.

最初の文字だけを小文字にした、EXPR を返します。 これは、ダブルクォート文字列における、\l エスケープを 実装する内部関数です。

If EXPR is omitted, uses $_.

EXPR が省略されると、$_ を使います。

This function behaves the same way under various pragmas, such as in a locale, as lc does.

この関数は、ロケールのようなさまざまなプラグマの影響下では、 lc と同様に振る舞います。

length EXPR
length

Returns the length in characters of the value of EXPR. If EXPR is omitted, returns the length of $_. If EXPR is undefined, returns undef.

EXPR の値の 文字 の長さを返します。 EXPR が省略されたときには、$_ の長さを返します。 EXPR が未定義値の場合、undef を返します。

This function cannot be used on an entire array or hash to find out how many elements these have. For that, use scalar @array and scalar keys %hash, respectively.

この関数は配列やハッシュ全体に対してどれだけの要素を含んでいるかを 調べるためには使えません。 そのような用途には、それぞれ scalar @arrayscalar keys %hash を 利用してください。

Like all Perl character operations, length normally deals in logical characters, not physical bytes. For how many bytes a string encoded as UTF-8 would take up, use length(Encode::encode('UTF-8', EXPR)) (you'll have to use Encode first). See Encode and perlunicode.

全ての Perl の文字操作と同様、length は通常物理的な バイトではなく論理文字を扱います。 UTF-8 でエンコードされた文字列が何バイトかを知るには、 length(Encode::encode('UTF-8', EXPR)) を使ってください (先に use Encode する必要があります)。 Encodeperlunicode を参照してください。

__LINE__

A special token that compiles to the current line number.

現在の行番号にコンパイルされる特殊トークン。

link OLDFILE,NEWFILE

Creates a new filename linked to the old filename. Returns true for success, false otherwise.

OLDFILE にリンクされた、新しいファイル NEWFILE を作ります。 成功時には真を、さもなければ偽を返します。

Portability issues: "link" in perlport.

移植性の問題: "link" in perlport

listen SOCKET,QUEUESIZE

Does the same thing that the listen(2) system call does. Returns true if it succeeded, false otherwise. See the example in "Sockets: Client/Server Communication" in perlipc.

listen(2) システムコールと同じことをします。 成功時には真を、さもなければ偽を返します。 "Sockets: Client/Server Communication" in perlipc の例を参照してください。

local EXPR

You really probably want to be using my instead, because local isn't what most people think of as "local". See "Private Variables via my()" in perlsub for details.

あなたはが本当に望んでいるのは my の方でしょう; local はほとんどの人々が「ローカル」と考えるものと 違うからです。 詳細は "Private Variables via my()" in perlsub を参照してください。

A local modifies the listed variables to be local to the enclosing block, file, or eval. If more than one value is listed, the list must be placed in parentheses. See "Temporary Values via local()" in perlsub for details, including issues with tied arrays and hashes.

"local" はリストアップされた変数を、囲っているブロック、 ファイル、eval の中で、ローカルなものにします。 複数の値を指定する場合は、リストはかっこでくくらなければなりません。 tie した配列とハッシュに関する事項を含む詳細については "Temporary Values via local()" in perlsub を参照してください。

The delete local EXPR construct can also be used to localize the deletion of array/hash elements to the current block. See "Localized deletion of elements of composite types" in perlsub.

delete local EXPR 構文は、配列/ハッシュの要素の削除を現在の ブロックにローカル化するためにも使われていました。 "Localized deletion of elements of composite types" in perlsub を 参照してください。

localtime EXPR
localtime

Converts a time as returned by the time function to a 9-element list with the time analyzed for the local time zone. Typically used as follows:

time 関数が返す時刻を、ローカルなタイムゾーンで測った時刻として、 9 要素の配列に変換します。 普通は、以下のようにして使います:

    #     0    1    2     3     4    5     6     7     8
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
                                                localtime(time);

All list elements are numeric and come straight out of the C `struct tm'. $sec, $min, and $hour are the seconds, minutes, and hours of the specified time.

すべてのリスト要素は数値で、C の `struct tm' 構造体から 直接持ってきます。 $sec, $min, $hour は指定された時刻の秒、分、時です。

$mday is the day of the month and $mon the month in the range 0..11, with 0 indicating January and 11 indicating December. This makes it easy to get a month name from a list:

$mday は月の何日目か、$mon は月の値です; 月の値は 0..11 で、0 が 1 月、11 が 12 月です。 これにより、リストから月の名前を得るのが簡単になります:

    my @abbr = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
    print "$abbr[$mon] $mday";
    # $mon=9, $mday=18 gives "Oct 18"

$year contains the number of years since 1900. To get a 4-digit year write:

$year は 1900 年からの年数を持ちます。 4 桁の年を得るには以下のようにします:

    $year += 1900;

To get the last two digits of the year (e.g., "01" in 2001) do:

西暦の下 2 桁(2001 年では "01")がほしい場合は以下のようにします:

    $year = sprintf("%02d", $year % 100);

$wday is the day of the week, with 0 indicating Sunday and 3 indicating Wednesday. $yday is the day of the year, in the range 0..364 (or 0..365 in leap years.)

$wday は曜日で、0 が日曜日、3 が水曜日です。 $yday はその年の何日目かで、0..364 の値を取ります (うるう年は 0..365 です。)

$isdst is true if the specified time occurs during Daylight Saving Time, false otherwise.

$isdst は指定された時刻が夏時間の場合は真、そうでなければ偽です。

If EXPR is omitted, localtime uses the current time (as returned by time).

EXPR が省略されると、localtime は (time によって返される) 現在時刻を使います。

In scalar context, localtime returns the ctime(3) value:

スカラコンテキストでは、localtimectime(3) の値を 返します:

    my $now_string = localtime;  # e.g., "Thu Oct 13 04:54:34 1994"

The format of this scalar value is not locale-dependent but built into Perl. For GMT instead of local time use the gmtime builtin. See also the Time::Local module (for converting seconds, minutes, hours, and such back to the integer value returned by time), and the POSIX module's strftime and mktime functions.

このスカラ値の形式はロケール依存 ではなく、Perl の組み込みの値です。 ローカル時刻ではなく GMT がほしい場合は gmtime 組み込み 関数を使ってください。 また、(秒、分、時などの形から、time が返す値である 1970 年 1 月 1 日の真夜中からの秒数に変換する) Time::Local モジュール及び POSIX モジュールで提供される strftimemktime 関数も 参照してください。

To get somewhat similar but locale-dependent date strings, set up your locale environment variables appropriately (please see perllocale) and try for example:

似たような、しかしロケール依存の日付文字列がほしい場合は、 ロケール環境変数を適切に設定して(perllocale を参照してください)、 以下の例を試してください:

    use POSIX qw(strftime);
    my $now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;
    # or for GMT formatted appropriately for your locale:
    my $now_string = strftime "%a %b %e %H:%M:%S %Y", gmtime;

Note that %a and %b, the short forms of the day of the week and the month of the year, may not necessarily be three characters wide.

曜日と月の短い表現である %a%b は、3 文字とは限らないことに 注意してください。

The Time::gmtime and Time::localtime modules provide a convenient, by-name access mechanism to the gmtime and localtime functions, respectively.

Time::gmtime モジュールと Time::localtime モジュールは、それぞれ gmtime 関数と localtime 関数に、 名前でアクセスする機構を提供する便利なモジュールです。

For a comprehensive date and time representation look at the DateTime module on CPAN.

包括的な日付と時刻の表現については、CPAN の DateTime モジュールを 参照してください。

Portability issues: "localtime" in perlport.

移植性の問題: "localtime" in perlport

lock THING

This function places an advisory lock on a shared variable or referenced object contained in THING until the lock goes out of scope.

この関数は THING が含む共有変数またはリファレンスされたオブジェクトに、 スコープから出るまでアドバイサリロックを掛けます.

The value returned is the scalar itself, if the argument is a scalar, or a reference, if the argument is a hash, array or subroutine.

返される値は、引数がスカラならそのスカラ自身、引数がハッシュ、配列、 サブルーチンならリファレンスです。

lock is a "weak keyword"; this means that if you've defined a function by this name (before any calls to it), that function will be called instead. If you are not under use threads::shared this does nothing. See threads::shared.

lock は「弱いキーワード」です; もしユーザーが(呼び出し前に) この名前で関数を定義すると、定義された関数の方が呼び出されます。 use threads::shared の影響下でない場合は、これは何もしません。 threads::shared を参照してください。

log EXPR
log

Returns the natural logarithm (base e) of EXPR. If EXPR is omitted, returns the log of $_. To get the log of another base, use basic algebra: The base-N log of a number is equal to the natural log of that number divided by the natural log of N. For example:

EXPR の (e を底とする) 自然対数を返します。 EXPR が省略されると、$_ の対数を返します。 底の異なる対数を求めるためには、基礎代数を利用してください: ある数の N を底とする対数は、その数の自然対数を N の自然対数で割ったものです。 例えば:

    sub log10 {
        my $n = shift;
        return log($n)/log(10);
    }

See also exp for the inverse operation.

逆操作については exp を参照してください。

lstat FILEHANDLE
lstat EXPR
lstat DIRHANDLE
lstat

Does the same thing as the stat function (including setting the special _ filehandle) but stats a symbolic link instead of the file the symbolic link points to. If symbolic links are unimplemented on your system, a normal stat is done. For much more detailed information, please see the documentation for stat.

(特別なファイルハンドルである _ の設定を含めて) stat 関数と同じことをしますが、シンボリックリンクが 指しているファイルではなく、シンボリックリンク自体の stat をとります。 シンボリックリンクがシステムに実装されていないと、通常の stat が行なわれます。 さらにより詳細な情報については、stat の文書を 参照してください。

If EXPR is omitted, stats $_.

EXPR が省略されると、$_ の stat をとります。

Portability issues: "lstat" in perlport.

移植性の問題: "lstat" in perlport

m//

The match operator. See "Regexp Quote-Like Operators" in perlop.

マッチ演算子です。 "Regexp Quote-Like Operators" in perlop を参照してください。

map BLOCK LIST
map EXPR,LIST

Evaluates the BLOCK or EXPR for each element of LIST (locally setting $_ to each element) and composes a list of the results of each such evaluation. Each element of LIST may produce zero, one, or more elements in the generated list, so the number of elements in the generated list may differ from that in LIST. In scalar context, returns the total number of elements so generated. In list context, returns the generated list.

LIST の個々の要素に対して、BLOCK か EXPR を評価し ($_ は、ローカルに個々の要素が設定されます) 、 それぞれの評価結果からなるリストを作ります。 LIST の個々の要素によって作られる、生成されたリストの要素数は、 0 個の場合もあれば、複数の場合もあるので、 生成されたリストの要素数は LIST の要素数と異なるかも知れません。 スカラコンテキストでは、生成された要素の数を返します。 リストコンテキストでは、生成されたリストを返します。

    my @chars = map(chr, @numbers);

translates a list of numbers to the corresponding characters.

は、数のリストを対応する文字に変換します。

    my @squares = map { $_ * $_ } @numbers;

translates a list of numbers to their squared values.

これは数値のリストを、その 2 乗に変換します。

    my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers;

shows that number of returned elements can differ from the number of input elements. To omit an element, return an empty list (). This could also be achieved by writing

のように、返された要素の数が入力要素の数と異なる場合もあります。 要素を省略するには、空リスト () を返します。 これは以下のように書くことでも達成できて

    my @squares = map { $_ * $_ } grep { $_ > 5 } @numbers;

which makes the intention more clear.

この方が目的がよりはっきりします。

Map always returns a list, which can be assigned to a hash such that the elements become key/value pairs. See perldata for more details.

map は常にリストを返し、要素がキー/値の組になるようなハッシュに 代入できます。 さらなる詳細については perldata を参照してください。

    my %hash = map { get_a_key_for($_) => $_ } @array;

is just a funny way to write

は以下のものをちょっと変わった書き方で書いたものです。

    my %hash;
    foreach (@array) {
        $hash{get_a_key_for($_)} = $_;
    }

Note that $_ is an alias to the list value, so it can be used to modify the elements of the LIST. While this is useful and supported, it can cause bizarre results if the elements of LIST are not variables. Using a regular foreach loop for this purpose would be clearer in most cases. See also grep for a list composed of those items of the original list for which the BLOCK or EXPR evaluates to true.

$_ は、LIST の値へのエイリアスですので、LIST の要素を 変更するために使うことができます。 これは、便利でサポートされていますが、 LIST の要素が変数でないと、おかしな結果になります。 この目的には通常の foreach ループを使うことで、ほとんどの場合は より明確になります。 BLOCK や EXPR が真になる元のリストの要素からなるリストについては、 grep も参照してください。

{ starts both hash references and blocks, so map { ... could be either the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look ahead for the closing } it has to take a guess at which it's dealing with based on what it finds just after the {. Usually it gets it right, but if it doesn't it won't realize something is wrong until it gets to the } and encounters the missing (or unexpected) comma. The syntax error will be reported close to the }, but you'll need to change something near the { such as using a unary + or semicolon to give Perl some help:

{ はハッシュリファレンスとブロックの両方の開始文字なので、 map { ... は map BLOCK LIST の場合と map EXPR, LIST の場合があります。 Perl は終了文字の } を先読みしないので、{ の直後の文字を見て どちらとして扱うかを推測します。 通常この推測は正しいですが、もし間違った場合は、} まで読み込んで カンマが足りない(または多い)ことがわかるまで、何かがおかしいことに 気付きません。 } の近くで文法エラーが出ますが、Perl を助けるために単項の + や セミコロンを使うというように、{ の近くの何かを変更する必要があります。

 my %hash = map {  "\L$_" => 1  } @array # perl guesses EXPR. wrong
 my %hash = map { +"\L$_" => 1  } @array # perl guesses BLOCK. right
 my %hash = map {; "\L$_" => 1  } @array # this also works
 my %hash = map { ("\L$_" => 1) } @array # as does this
 my %hash = map {  lc($_) => 1  } @array # and this.
 my %hash = map +( lc($_) => 1 ), @array # this is EXPR and works!

 my %hash = map  ( lc($_), 1 ),   @array # evaluates to (1, @array)

or to force an anon hash constructor use +{:

または +{ を使って無名ハッシュコンストラクタを強制します:

    my @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs
                                              # comma at end

to get a list of anonymous hashes each with only one entry apiece.

こうするとそれぞれ 1 要素だけの無名ハッシュのリストを得られます。

mkdir FILENAME,MODE
mkdir FILENAME
mkdir

Creates the directory specified by FILENAME, with permissions specified by MODE (as modified by umask). If it succeeds it returns true; otherwise it returns false and sets $! (errno). MODE defaults to 0777 if omitted, and FILENAME defaults to $_ if omitted.

FILENAME で指定したディレクトリを、MODE で指定した許可モード(を umask で修正したもの) で作成します。 成功時には真を返します; さもなければ偽を返して $! (errno) を設定します。 MODE を省略すると、0777 とみなし、 FILENAME を省略すると、$_ を使います。

In general, it is better to create directories with a permissive MODE and let the user modify that with their umask than it is to supply a restrictive MODE and give the user no way to be more permissive. The exceptions to this rule are when the file or directory should be kept private (mail files, for instance). The documentation for umask discusses the choice of MODE in more detail.

一般的に、制限された MODE を使ってユーザーがより寛容にする方法を 与えないより、寛容な MODE でディレクトリを作り、ユーザーが自身の umask で修正するようにした方がよいです。 例外は、(例えばメールファイルのような)プライベートに保つべきファイルや ディレクトリを書く場合です。 umask の文書で、MODE の選択に関して詳細に議論しています。

Note that according to the POSIX 1003.1-1996 the FILENAME may have any number of trailing slashes. Some operating and filesystems do not get this right, so Perl automatically removes all trailing slashes to keep everyone happy.

POSIX 1003.1-1996 によれば、FILENAME には末尾に任意の数のスラッシュを つけることができます。 このようには動かない OS やファイルシステムもあるので、Perl はみんなが 幸せになれるように、自動的に末尾のスラッシュを削除します。

To recursively create a directory structure, look at the make_path function of the File::Path module.

ディレクトリ構造を再帰的に作成するには、File::Path モジュールの make_path 関数を 参照してください。

msgctl ID,CMD,ARG

Calls the System V IPC function msgctl(2). You'll probably have to say

System V IPC 関数 msgctl(2) を呼び出します。 正しい定数定義を得るために、まず

    use IPC::SysV;

first to get the correct constant definitions. If CMD is IPC_STAT, then ARG must be a variable that will hold the returned msqid_ds structure. Returns like ioctl: the undefined value for error, "0 but true" for zero, or the actual return value otherwise. See also "SysV IPC" in perlipc and the documentation for IPC::SysV and IPC::Semaphore.

と書くことが必要でしょう。 CMD が IPC_STAT であれば、ARG は返される msqid_ds 構造体を 納める変数でなければなりません。 ioctl と同じように、エラー時には 未定義値、ゼロのときは "0 but true"、それ以外なら、その値そのものを 返します。 "SysV IPC" in perlipc および、IPC::SysV, IPC::Semaphore の文書も参照してください。

Portability issues: "msgctl" in perlport.

移植性の問題: "msgctl" in perlport

msgget KEY,FLAGS

Calls the System V IPC function msgget(2). Returns the message queue id, or undef on error. See also "SysV IPC" in perlipc and the documentation for IPC::SysV and IPC::Msg.

System V IPC 関数 msgget(2) を呼び出します。 メッセージキューの ID か、エラー時には undef を返します。 "SysV IPC" in perlipc および、IPC::SysV, IPC::Msg の文書も参照してください。

Portability issues: "msgget" in perlport.

移植性の問題: "msgget" in perlport

msgrcv ID,VAR,SIZE,TYPE,FLAGS

Calls the System V IPC function msgrcv to receive a message from message queue ID into variable VAR with a maximum message size of SIZE. Note that when a message is received, the message type as a native long integer will be the first thing in VAR, followed by the actual message. This packing may be opened with unpack("l! a*"). Taints the variable. Returns true if successful, false on error. See also "SysV IPC" in perlipc and the documentation for IPC::SysV and IPC::Msg.

System V IPC 関数 msgrcv を呼び出し、メッセージキュー ID から、 変数 VAR に最大メッセージ長 SIZE のメッセージを受信します。 メッセージが受信された時、ネイティブな long 整数のメッセージタイプが VAR の先頭となり、実際のメッセージが続きます。 このパッキングは unpack("l! a*") で展開できます。 変数は汚染されます。 成功時には真を、エラー時には偽を返します。 "SysV IPC" in perlipc および、IPC::SysV, IPC::Msg の文書も参照してください。

Portability issues: "msgrcv" in perlport.

移植性の問題: "msgrcv" in perlport

msgsnd ID,MSG,FLAGS

Calls the System V IPC function msgsnd to send the message MSG to the message queue ID. MSG must begin with the native long integer message type, be followed by the length of the actual message, and then finally the message itself. This kind of packing can be achieved with pack("l! a*", $type, $message). Returns true if successful, false on error. See also "SysV IPC" in perlipc and the documentation for IPC::SysV and IPC::Msg.

System V IPC 関数 msgsnd を呼び出し、メッセージキュー ID に メッセージ MSG を送信します。 MSG の先頭は、ネイティブな long 整数のメッセージタイプでなければならず、 メッセージの長さ、メッセージ本体と続きます。 これは、pack("l! a*", $type, $message) として生成できます。 成功時には真を、エラー時には偽を返します。 "SysV IPC" in perlipc および、IPC::SysV, IPC::Msg の文書も参照してください。

Portability issues: "msgsnd" in perlport.

移植性の問題: "msgsnd" in perlport

my VARLIST
my TYPE VARLIST
my VARLIST : ATTRS
my TYPE VARLIST : ATTRS

A my declares the listed variables to be local (lexically) to the enclosing block, file, or eval. If more than one variable is listed, the list must be placed in parentheses.

my はリストアップされた変数を、囲っているブロック、ファイル、 eval の中でローカルな (レキシカルな) ものにします。 複数の変数を指定する場合は、リストはかっこでくくらなければなりません。

The exact semantics and interface of TYPE and ATTRS are still evolving. TYPE may be a bareword, a constant declared with use constant, or __PACKAGE__. It is currently bound to the use of the fields pragma, and attributes are handled using the attributes pragma, or starting from Perl 5.8.0 also via the Attribute::Handlers module. See "Private Variables via my()" in perlsub for details.

TYPE と ATTRS の正確な文法とインターフェースは今でも進化しています。 TYPE は、裸の単語、use constant で宣言された定数、 __PACKAGE__ のいずれかです。 現在のところ、TYPE は fields プラグマの使用と結び付けられていて、 属性は attributes プラグマか、Perl 5.8.0 からは Attribute::Handlers モジュールと結び付けられています。 詳しくは "Private Variables via my()" in perlsub を参照してください。

Note that with a parenthesised list, undef can be used as a dummy placeholder, for example to skip assignment of initial values:

かっこで囲まれたリストでは、undef は、例えば初期値の代入を 飛ばすために、ダミーのプレースホルダとして使えることに注意してください:

    my ( undef, $min, $hour ) = localtime;
next LABEL
next EXPR
next

The next command is like the continue statement in C; it starts the next iteration of the loop:

next コマンドは、C での continue 文のようなもので、 ループの次の繰り返しを開始します:

    LINE: while (<STDIN>) {
        next LINE if /^#/;  # discard comments
        #...
    }

Note that if there were a continue block on the above, it would get executed even on discarded lines. If LABEL is omitted, the command refers to the innermost enclosing loop. The next EXPR form, available as of Perl 5.18.0, allows a label name to be computed at run time, being otherwise identical to next LABEL.

continue ブロックが存在すれば、たとえ捨てられる行に あっても、それが実行されます。 LABEL が省略されると、コマンドは一番内側のループを参照します。 Perl 5.18.0 から利用可能な next EXPR 形式では、実行時に計算される ラベル名が使えます; それ以外は next LABEL と同一です。

next cannot return a value from a block that typically returns a value, such as eval {}, sub {}, or do {}. It will perform its flow control behavior, which precludes any return value. It should not be used to exit a grep or map operation.

nexteval {}, sub {}, do {} といった 典型的には値を返すブロックから値を返せません。 これは、返り値を不可能にするフロー制御の振る舞いを実行します。 grepmap 操作を終了するのに 使うべきではありません。

Note that a block by itself is semantically identical to a loop that executes once. Thus next will exit such a block early.

ブロック自身は一回だけ実行されるループと文法的に同一であることに 注意してください。 従って、next はそのようなブロックから早く抜けるのに使えます。

See also continue for an illustration of how last, next, and redo work.

last, next, redo が どのように働くかについては continue も参照してください。

Unlike most named operators, this has the same precedence as assignment. It is also exempt from the looks-like-a-function rule, so next ("foo")."bar" will cause "bar" to be part of the argument to next.

ほとんどの名前付き演算子と異なり、これは代入と同じ優先順位を持ちます。 また、関数のように見えるものの規則からも免れるので、next ("foo")."bar" と すると "bar" は next への引数の一部となります。

no MODULE VERSION LIST
no MODULE VERSION
no MODULE LIST
no MODULE
no VERSION

See the use function, of which no is the opposite.

use 関数を参照してください; no は、その逆を行なうものです。

oct EXPR
oct

Interprets EXPR as an octal string and returns the corresponding value. (If EXPR happens to start off with 0x, interprets it as a hex string. If EXPR starts off with 0b, it is interpreted as a binary string. Leading whitespace is ignored in all three cases.) The following will handle decimal, binary, octal, and hex in standard Perl notation:

EXPR を 8 進数文字列と解釈して、対応する値を返します。 (EXPR が 0x で始まるときには、16 進数文字列と解釈します。 EXPR が 0bで始まるときは、2 進数文字列と解釈します。 どの場合でも、先頭の空白は無視されます。) 以下の例は、標準的な Perl の記法での 10 進数、2 進数、8 進数、16 進数を扱います:

    $val = oct($val) if $val =~ /^0/;

If EXPR is omitted, uses $_. To go the other way (produce a number in octal), use sprintf or printf:

EXPR が省略されると、$_ を使います。 (8 進数を扱う)その他の方法をとしては sprintfprintf があります:

    my $dec_perms = (stat("filename"))[2] & 07777;
    my $oct_perm_str = sprintf "%o", $perms;

The oct function is commonly used when a string such as 644 needs to be converted into a file mode, for example. Although Perl automatically converts strings into numbers as needed, this automatic conversion assumes base 10.

oct 関数は例えば、 644 といった文字列をファイルモードに 変換する時によく使います。 Perl は必要に応じて自動的に文字列を数値に変換しますが、 この自動変換は十進数を仮定します。

Leading white space is ignored without warning, as too are any trailing non-digits, such as a decimal point (oct only handles non-negative integers, not negative integers or floating point).

先頭の空白や、末尾の(小数点のような)非数字は警告なしに無視されます (oct は非負整数のみを扱えます; 負の整数や小数は扱えません)。

open FILEHANDLE,EXPR
open FILEHANDLE,MODE,EXPR
open FILEHANDLE,MODE,EXPR,LIST
open FILEHANDLE,MODE,REFERENCE
open FILEHANDLE

Opens the file whose filename is given by EXPR, and associates it with FILEHANDLE.

EXPR で与えられたファイル名のファイルを開き、FILEHANDLE と結び付けます。

Simple examples to open a file for reading:

読み込みのためにファイルを開くための簡単な例は以下のもので:

    open(my $fh, "<", "input.txt")
        or die "Can't open < input.txt: $!";

and for writing:

書き込み用は以下のものです:

    open(my $fh, ">", "output.txt")
        or die "Can't open > output.txt: $!";

(The following is a comprehensive reference to open: for a gentler introduction you may consider perlopentut.)

(以下は総合的な open のリファレンスです: より親切な説明については perlopentut を参照してください。)

If FILEHANDLE is an undefined scalar variable (or array or hash element), a new filehandle is autovivified, meaning that the variable is assigned a reference to a newly allocated anonymous filehandle. Otherwise if FILEHANDLE is an expression, its value is the real filehandle. (This is considered a symbolic reference, so use strict "refs" should not be in effect.)

FILEHANDLE が未定義のスカラ変数(または配列かハッシュの要素)の場合、 新しいファイルハンドルが自動有効化され、その変数は新しく割り当てられた 無名ファイルハンドルへのリファレンスが代入されます。 さもなければ、もし FILEHANDLE が式なら、その値を求めている実際の ファイルハンドルの名前として使います。 (これはシンボリックリファレンスとして扱われるので、 use strict "refs" の影響を 受けません。)

If three (or more) arguments are specified, the open mode (including optional encoding) in the second argument are distinct from the filename in the third. If MODE is < or nothing, the file is opened for input. If MODE is >, the file is opened for output, with existing files first being truncated ("clobbered") and nonexisting files newly created. If MODE is >>, the file is opened for appending, again being created if necessary.

3 (またはそれ以上)の引数が指定された場合、2 番目の引数の(オプションの エンコーディングを含む)開く時のモードは、3 番目のファイル名と分離されます。 MODE が < か空の場合、ファイルは入力用に開かれます。 MODE が > の場合、ファイルは出力用に開かれ、既にファイルが ある場合は切り詰められ(上書きされ)、ない場合は新しく作られます。 MODE が >> の場合、ファイルは追加用に開かれ、やはり必要なら 作成されます。

You can put a + in front of the > or < to indicate that you want both read and write access to the file; thus +< is almost always preferred for read/write updates--the +> mode would clobber the file first. You can't usually use either read-write mode for updating textfiles, since they have variable-length records. See the -i switch in perlrun for a better approach. The file is created with permissions of 0666 modified by the process's umask value.

ファイルに読み込みアクセスと書き込みアクセスの両方をしたいことを示すために、 >< の前に + を付けることができます: 従って、ほとんど常に +< が読み書き更新のために使われます -- +> モードはまずファイルを上書きします。 普通はこれらの読み書きモードをテキストファイルの更新のためには使えません; なぜなら可変長のレコードで構成されているからです。 よりよい手法については perlrun-i オプションを参照してください。 ファイルは 0666 をプロセスの umask 値で修正した パーミッションで作成されます。

These various prefixes correspond to the fopen(3) modes of r, r+, w, w+, a, and a+.

これらの様々な前置詞は fopen(3)r, r+, w, w+, a, a+ のモードに対応します。

In the one- and two-argument forms of the call, the mode and filename should be concatenated (in that order), preferably separated by white space. You can--but shouldn't--omit the mode in these forms when that mode is <. It is safe to use the two-argument form of open if the filename argument is a known literal.

1 引数 と 2 引数の形式ではモードとファイル名は(この順番で) 結合されます(空白によって分割されているかもしれません)。 この形式で、モードが '<' の場合はモードを省略できます (が、 するべきではありません)。 ファイル引数が既知のリテラルの場合、2 引数形式の open は安全です。

For three or more arguments if MODE is |-, the filename is interpreted as a command to which output is to be piped, and if MODE is -|, the filename is interpreted as a command that pipes output to us. In the two-argument (and one-argument) form, one should replace dash (-) with the command. See "Using open() for IPC" in perlipc for more examples of this. (You are not allowed to open to a command that pipes both in and out, but see IPC::Open2, IPC::Open3, and "Bidirectional Communication with Another Process" in perlipc for alternatives.)

3 引数以上の形式で MODE が |- の場合、ファイル名は出力がパイプされるコマンドとして 解釈され、MODE が -| の場合、ファイル名は出力がこちらに パイプされるコマンドとして解釈されます。 2 引数(と 1 引数) の形式ではハイフン(-)をコマンドの代わりに使えます。 これに関するさらなる例については "Using open() for IPC" in perlipc を 参照してください。 (open を入出力 両用 にパイプすることは 出来ませんが、代替案としては IPC::Open2, IPC::Open3, "Bidirectional Communication with Another Process" in perlipc を 参照してください。)

In the form of pipe opens taking three or more arguments, if LIST is specified (extra arguments after the command name) then LIST becomes arguments to the command invoked if the platform supports it. The meaning of open with more than three arguments for non-pipe modes is not yet defined, but experimental "layers" may give extra LIST arguments meaning.

パイプでの三つ以上の引数の形式では、LIST (コマンド名の後の追加の引数) が 指定されると、プラットフォームが対応していれば、LIST は起動される コマンドへの引数となります。 パイプモードではない open での三つ以上の引数の 意味はまだ未定義ですが、実験的な「層」は追加の LIST 引数の意味を与えます。

In the two-argument (and one-argument) form, opening <- or - opens STDIN and opening >- opens STDOUT.

2 引数(と 1 引数)で <-- を open すると STDIN が オープンされ、>- を open すると STDOUT がオープンされます。

You may (and usually should) use the three-argument form of open to specify I/O layers (sometimes referred to as "disciplines") to apply to the handle that affect how the input and output are processed (see open and PerlIO for more details). For example:

open の 3 引数形式では、どのように入出力が処理されるかに影響を与える I/O 層(「ディシプリン」とも呼ばれます)を指定できます (そして普通はそうするべきです) (詳細については openPerlIO を参照してください)。 例えば:

  open(my $fh, "<:encoding(UTF-8)", $filename)
    || die "Can't open UTF-8 encoded $filename: $!";

opens the UTF8-encoded file containing Unicode characters; see perluniintro. Note that if layers are specified in the three-argument form, then default layers stored in ${^OPEN} (see perlvar; usually set by the open pragma or the switch -CioD) are ignored. Those layers will also be ignored if you specify a colon with no name following it. In that case the default layer for the operating system (:raw on Unix, :crlf on Windows) is used.

は、Unicode 文字を含む UTF8 エンコードされたファイルを開きます; perluniintro を参照してください。 3 引数形式で層を指定すると、${^OPEN} (perlvar を参照してください; 通常は open プラグマか -CioD オプションでセットされます) に保存された デフォルト層は無視されることに注意してください。 これらの層は、名前なしでコロンを指定した場合にも無視されます。 この場合 OS のデフォルトの層 (Unix では :raw、Windows では :crlf) が 使われます。

Open returns nonzero on success, the undefined value otherwise. If the open involved a pipe, the return value happens to be the pid of the subprocess.

open は、成功時にはゼロ以外を返し、失敗時には未定義値を返します。 パイプに関る open のときには、返り値は サブプロセスの pid となります。

On some systems (in general, DOS- and Windows-based systems) binmode is necessary when you're not working with a text file. For the sake of portability it is a good idea always to use it when appropriate, and never to use it when it isn't appropriate. Also, people can set their I/O to be by default UTF8-encoded Unicode, not bytes.

テキストファイルでないものを扱う場合に binmode が必要な システムもあります(一般的には DOS と Windows ベースのシステムです)。 移植性のために、適切なときには常にこれを使い、適切でないときには 決して使わないというのは良い考えです。 また、デフォルトとして I/O を bytes ではなく UTF-8 エンコードされた Unicode にセットすることも出来ます。

When opening a file, it's seldom a good idea to continue if the request failed, so open is frequently used with die. Even if die won't do what you want (say, in a CGI script, where you want to format a suitable error message (but there are modules that can help with that problem)) always check the return value from opening a file.

ファイルを開く時、開くのに失敗した時に通常の処理を続けるのは普通は悪い 考えなので、open はしばしば die と結び付けられて使われます。 望むものが die でない場合(例えば、CGI スクリプトのように きれいにフォーマットされたエラーメッセージを作りたい場合 (但しこの問題を助けるモジュールがあります))でも、 ファイルを開いた時の返り値を常にチェックするべきです。

The filehandle will be closed when its reference count reaches zero. If it is a lexically scoped variable declared with my, that usually means the end of the enclosing scope. However, this automatic close does not check for errors, so it is better to explicitly close filehandles, especially those used for writing:

ファイルハンドルは、参照カウントが 0 になったときに閉じられます。 これが my で宣言されたレキシカルスコープを持つ変数の場合、 普通は囲まれたスコープの終わりを意味します。 しかし、この自動閉じはエラーをチェックしないので、特に書き込み用の場合は、 明示的にファイルハンドルを閉じる方がよいです。

    close($handle)
       || warn "close failed: $!";

An older style is to use a bareword as the filehandle, as

より古いスタイルは、次のように、ファイルハンドルとして裸の単語を使います

    open(FH, "<", "input.txt")
       or die "Can't open < input.txt: $!";

Then you can use FH as the filehandle, in close FH and <FH> and so on. Note that it's a global variable, so this form is not recommended in new code.

それから FH を、close FH<FH> などのように、 ファイルハンドルとして使えます。 これはグローバル変数なので、新しいコードでは非推奨であることに 注意してください。

As a shortcut a one-argument call takes the filename from the global scalar variable of the same name as the filehandle:

短縮版として、1 引数呼び出しでは、ファイル名を、ファイルハンドルと同じ名前の グローバルなスカラ変数から取ります:

    $ARTICLE = 100;
    open(ARTICLE) or die "Can't find article $ARTICLE: $!\n";

Here $ARTICLE must be a global (package) scalar variable - not one declared with my or state.

ここで $ARTICLE はグローバル(パッケージ)スカラ変数でなければなりません - mystate で宣言された 変数ではありません。

As a special case the three-argument form with a read/write mode and the third argument being undef:

特別な場合として、3 引数の形で読み書きモードで 3 番目の引数が undef の場合:

    open(my $tmp, "+>", undef) or die ...

opens a filehandle to a newly created empty anonymous temporary file. (This happens under any mode, which makes +> the only useful and sensible mode to use.) You will need to seek to do the reading.

新しく作成した空の無名一時ファイルとしてファイルハンドルを開きます。 (これはどのモードでも起こりますが、+> のみが有用で意味があります) 読み込みを行うためには seek が 必要です。

Perl is built using PerlIO by default. Unless you've changed this (such as building Perl with Configure -Uuseperlio), you can open filehandles directly to Perl scalars via:

Perl はデフォルトで PerlIO を使ってビルドされています。 (Configure -Uuseperlio して Perl をビルドするなどして)これを 変更していない限り、以下のようにして、Perl スカラを直接ファイルハンドルで 開くことができます:

    open(my $fh, ">", \$variable) || ..

To (re)open STDOUT or STDERR as an in-memory file, close it first:

STDOUTSTDERR を「オンメモリの」ファイルとして 再び開きたい場合は、先にそれを閉じます:

    close STDOUT;
    open(STDOUT, ">", \$variable)
        or die "Can't open STDOUT: $!";

The scalars for in-memory files are treated as octet strings: unless the file is being opened with truncation the scalar may not contain any code points over 0xFF.

オンメモリファイルのためのスカラはオクテット文字列として扱われます: ファイルが切り詰められて開かれない限り、 スカラは 0xFF を超える符号位置を含みません。

Opening in-memory files can fail for a variety of reasons. As with any other open, check the return value for success.

オンメモリファイルを開くのは様々な理由で失敗する ことがあります。 その他の open と同様、成功したかを返り値でチェックしてください。

See perliol for detailed info on PerlIO.

PerlIO に関する詳しい情報については perliol を参照してください。

General examples:

一般的な例:

 open(my $log, ">>", "/usr/spool/news/twitlog");
 # if the open fails, output is discarded

 open(my $dbase, "+<", "dbase.mine")      # open for update
     or die "Can't open 'dbase.mine' for update: $!";

 open(my $dbase, "+<dbase.mine")          # ditto
     or die "Can't open 'dbase.mine' for update: $!";

 open(my $article_fh, "-|", "caesar <$article")  # decrypt
                                                 # article
     or die "Can't start caesar: $!";

 open(my $article_fh, "caesar <$article |")      # ditto
     or die "Can't start caesar: $!";

 open(my $out_fh, "|-", "sort >Tmp$$")    # $$ is our process id
     or die "Can't start sort: $!";

 # in-memory files
 open(my $memory, ">", \$var)
     or die "Can't open memory file: $!";
 print $memory "foo!\n";              # output will appear in $var

You may also, in the Bourne shell tradition, specify an EXPR beginning with >&, in which case the rest of the string is interpreted as the name of a filehandle (or file descriptor, if numeric) to be duped (as in dup(2)) and opened. You may use & after >, >>, <, +>, +>>, and +<. The mode you specify should match the mode of the original filehandle. (Duping a filehandle does not take into account any existing contents of IO buffers.) If you use the three-argument form, then you can pass either a number, the name of a filehandle, or the normal "reference to a glob".

Bourne シェルの慣例にしたがって、EXPR の先頭に >& を付けると、EXPR の残りの文字列をファイルハンドル名 (数字であれば、ファイル記述子) と解釈して、それを (dup(2) によって) 複製してオープンします。 & は、>, >>, <, +>, +>>, +<というモード指定に付けることができます。 指定するモード指定は、もとのファイルハンドルのモードと 合っていないといけません。 (ファイルハンドルの複製は既に存在する IO バッファの内容に含めません。) 3 引数形式を使う場合は、数値を渡すか、ファイルハンドルの名前を渡すか、 通常の「グロブへのリファレンス」を渡します。

Here is a script that saves, redirects, and restores STDOUT and STDERR using various methods:

STDOUTSTDERR 保存し、リダイレクトし、元に戻すスクリプトを示します:

    #!/usr/bin/perl
    open(my $oldout, ">&STDOUT")     or die "Can't dup STDOUT: $!";
    open(OLDERR,     ">&", \*STDERR) or die "Can't dup STDERR: $!";

    open(STDOUT, '>', "foo.out") or die "Can't redirect STDOUT: $!";
    open(STDERR, ">&STDOUT")     or die "Can't dup STDOUT: $!";

    select STDERR; $| = 1;  # make unbuffered
    select STDOUT; $| = 1;  # make unbuffered

    print STDOUT "stdout 1\n";  # this works for
    print STDERR "stderr 1\n";  # subprocesses too

    open(STDOUT, ">&", $oldout) or die "Can't dup \$oldout: $!";
    open(STDERR, ">&OLDERR")    or die "Can't dup OLDERR: $!";

    print STDOUT "stdout 2\n";
    print STDERR "stderr 2\n";

If you specify '<&=X', where X is a file descriptor number or a filehandle, then Perl will do an equivalent of C's fdopen(3) of that file descriptor (and not call dup(2)); this is more parsimonious of file descriptors. For example:

X をファイル記述子の番号かファイルハンドルとして、 '<&=X' と指定すると、Perl はそのファイル記述子に対する C の fdopen(3) と同じことを行ないます(そして dup(2) は呼び出しません); これはファイル記述子をより節約します。 例えば:

    # open for input, reusing the fileno of $fd
    open(my $fh, "<&=", $fd)

or

または

    open(my $fh, "<&=$fd")

or

または

    # open for append, using the fileno of $oldfh
    open(my $fh, ">>&=", $oldfh)

Being parsimonious on filehandles is also useful (besides being parsimonious) for example when something is dependent on file descriptors, like for example locking using flock. If you do just open(my $A, ">>&", $B), the filehandle $A will not have the same file descriptor as $B, and therefore flock($A) will not flock($B) nor vice versa. But with open(my $A, ">>&=", $B), the filehandles will share the same underlying system file descriptor.

ファイルハンドルを倹約することは、(倹約できること以外に)何かが ファイル記述子に依存している場合、例えば flock を使った ファイルロックといった場合に有用です。 open(my $A, ">>&", $B) とすると、ファイルハンドル $A$B と同じ ファイル記述子にはならないので、flock($A)flock($B) は別々になります。 しかし open(my $A, ">>&=", $B) ではファイルハンドルは基礎となるシステムの 同じファイル記述子を共有します。

Note that under Perls older than 5.8.0, Perl uses the standard C library's' fdopen(3) to implement the = functionality. On many Unix systems, fdopen(3) fails when file descriptors exceed a certain value, typically 255. For Perls 5.8.0 and later, PerlIO is (most often) the default.

5.8.0 より前の Perl の場合、= 機能の実装は 標準 C ライブラリの fdopen(3) を使っています。 多くの Unix システムでは、fdopen(3) はファイル記述子がある値 (典型的には 255)を超えた場合に失敗することが知られています。 5.8.0 以降の Perl では、(ほとんどの場合) PerlIO がデフォルトです。

You can see whether your Perl was built with PerlIO by running perl -V:useperlio. If it says 'define', you have PerlIO; otherwise you don't.

Perl が PerlIO つきでビルドされているかどうかを確認するには、 perl -V:useperlio を見ます。 これが 'define' なら PerlIO を使っています; そうでなければ使っていません。

If you open a pipe on the command - (that is, specify either |- or -| with the one- or two-argument forms of open), an implicit fork is done, so open returns twice: in the parent process it returns the pid of the child process, and in the child process it returns (a defined) 0. Use defined($pid) or // to determine whether the open was successful.

1 引数 または 2 引数の形の open) で (-||- というふうに) - というコマンドにパイプを開くと、 暗黙の fork が行なわれるので、 open は 2 回返ります; 親プロセスには子プロセスの pid が返され、子プロセスには (定義された) 0 が 返されます。 open が成功したかどうかを調べるには、defined($pid) または // を 使います。

For example, use either

例えば、以下の二つ

   my $child_pid = open(my $from_kid, "-|") // die "Can't fork: $!";

or

または

   my $child_pid = open(my $to_kid,   "|-") // die "Can't fork: $!";

followed by

を使って、後で以下のようにします。

    if ($child_pid) {
        # am the parent:
        # either write $to_kid or else read $from_kid
        ...
       waitpid $child_pid, 0;
    } else {
        # am the child; use STDIN/STDOUT normally
        ...
        exit;
    }

The filehandle behaves normally for the parent, but I/O to that filehandle is piped from/to the STDOUT/STDIN of the child process. In the child process, the filehandle isn't opened--I/O happens from/to the new STDOUT/STDIN. Typically this is used like the normal piped open when you want to exercise more control over just how the pipe command gets executed, such as when running setuid and you don't want to have to scan shell commands for metacharacters.

親プロセスでは、このファイルハンドルは通常通りに動作しますが、行なわれる 入出力は、子プロセスの STDIN/STDOUT にパイプされます。 子プロセス側では、そのファイルハンドルは開かれず、入出力は新しい STDOUT か STDIN に対して行なわれます。 これは、setuid で実行して、シェルコマンドのメタ文字を 検索させたくないような場合に、パイプコマンドの起動の仕方を 制御したいとき、普通のパイプの open と同じように使います。

The following blocks are more or less equivalent:

以下の組み合わせは、だいたい同じものです:

    open(my $fh, "|tr '[a-z]' '[A-Z]'");
    open(my $fh, "|-", "tr '[a-z]' '[A-Z]'");
    open(my $fh, "|-") || exec 'tr', '[a-z]', '[A-Z]';
    open(my $fh, "|-", "tr", '[a-z]', '[A-Z]');

    open(my $fh, "cat -n '$file'|");
    open(my $fh, "-|", "cat -n '$file'");
    open(my $fh, "-|") || exec "cat", "-n", $file;
    open(my $fh, "-|", "cat", "-n", $file);

The last two examples in each block show the pipe as "list form", which is not yet supported on all platforms. A good rule of thumb is that if your platform has a real fork (in other words, if your platform is Unix, including Linux and MacOS X), you can use the list form. You would want to use the list form of the pipe so you can pass literal arguments to the command without risk of the shell interpreting any shell metacharacters in them. However, this also bars you from opening pipes to commands that intentionally contain shell metacharacters, such as:

それぞれのブロックの末尾二つの例ではパイプを「リスト形式」にしていますが、 これはまだ全てのプラットフォームで対応しているわけではなりません。 よい経験則としては、もし実行しているプラットフォームで本当の fork があれば(言い換えると、プラットフォームが Linux や MacOS X を含む Unix なら)リスト形式が使えます。 パイプのリスト形式を使うことで、コマンドへのリテラルな引数を、 シェルのメタ文字をシェルが解釈するリスクなしに渡すことができます。 しかし、これは以下のように意図的にシェルメタ文字を含むコマンドをパイプとして 開くことを妨げます:

    open(my $fh, "|cat -n | expand -4 | lpr")
        || die "Can't open pipeline to lpr: $!";

See "Safe Pipe Opens" in perlipc for more examples of this.

これに関する更なる例については "Safe Pipe Opens" in perlipc を 参照してください。

Perl will attempt to flush all files opened for output before any operation that may do a fork, but this may not be supported on some platforms (see perlport). To be safe, you may need to set $| ($AUTOFLUSH in English) or call the autoflush method of IO::Handle on any open handles.

v5.6.0 から、Perl は書き込み用に開いている全てのファイルに対して fork を行う前にフラッシュしようとしますが、これに対応していない プラットフォームもあります(perlport を参照してください)。 安全のために、$| (English モジュールでは $AUTOFLUSH) をセットするか、全ての開いているハンドルに対して IO::Handleautoflush メソッドを 呼び出す必要があるかもしれません。

On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor as determined by the value of $^F. See "$^F" in perlvar.

ファイルに対する close-on-exec フラグをサポートしているシステムでは、 フラグは $^F の値で決定される、新しくオープンされた ファイル記述子に対してセットされます。 "$^F" in perlvar を参照してください。

Closing any piped filehandle causes the parent process to wait for the child to finish, then returns the status value in $? and ${^CHILD_ERROR_NATIVE}.

パイプのファイルハンドルを close することで、親プロセスは、子プロセスの終了を 待ち、それから $?${^CHILD_ERROR_NATIVE} にステータス値を 返します。

The filename passed to the one- and two-argument forms of open will have leading and trailing whitespace deleted and normal redirection characters honored. This property, known as "magic open", can often be used to good effect. A user could specify a filename of "rsh cat file |", or you could change certain filenames as needed:

1 引数 と 2 引数の形の open に渡された ファイル名は、はじめと終わりの空白が取り除かれ、通常のリダイレクト文字列を 受け付けます。 この機能は "magic open" として知られていますが、普通いい効果をもたらします。 ユーザーは "rsh cat file |" といったファイル名を指定できますし、 特定のファイル名を必要に応じて変更できます。

    $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/;
    open(my $fh, $filename) or die "Can't open $filename: $!";

Use the three-argument form to open a file with arbitrary weird characters in it,

妙な文字が含まれているようなファイル名をオープンするには、 3 引数の形を使います。

    open(my $fh, "<", $file)
        || die "Can't open $file: $!";

otherwise it's necessary to protect any leading and trailing whitespace:

あるいは、次のようにして、最初と最後の空白を保護します:

    $file =~ s#^(\s)#./$1#;
    open(my $fh, "< $file\0")
        || die "Can't open $file: $!";

(this may not work on some bizarre filesystems). One should conscientiously choose between the magic and three-argument form of open:

(これは奇妙なファイルシステムでは動作しないかもしれません)。 openmagic3 引数 形式を誠実に 選択するべきです。

    open(my $in, $ARGV[0]) || die "Can't open $ARGV[0]: $!";

will allow the user to specify an argument of the form "rsh cat file |", but will not work on a filename that happens to have a trailing space, while

とするとユーザーは "rsh cat file |" という形の引数を指定できますが、 末尾にスペースがついてしまったファイル名では動作しません; 一方:

    open(my $in, "<", $ARGV[0])
        || die "Can't open $ARGV[0]: $!";

will have exactly the opposite restrictions. (However, some shells support the syntax perl your_program.pl <( rsh cat file ), which produces a filename that can be opened normally.)

はまったく逆の制限があります。 (しかし、一部のシェルは perl your_program.pl <( rsh cat file ) という 文法に対応していて、普通に開くことが出来るファイル名を出力します。)

If you want a "real" C open(2), then you should use the sysopen function, which involves no such magic (but uses different filemodes than Perl open, which corresponds to C fopen(3)). This is another way to protect your filenames from interpretation. For example:

もし「本当の」C 言語の open(2) が必要なら、このような副作用のない sysopen 関数を使うべきです (ただし、C の fopen(3) に対応する Perl の open とは違うファイルモードを持ちます)。 これはファイル名を解釈から守るもう一つの方法です。 例えば:

    use IO::Handle;
    sysopen(my $fh, $path, O_RDWR|O_CREAT|O_EXCL)
        or die "Can't open $path: $!";
    $fh->autoflush(1);
    print $fh "stuff $$\n";
    seek($fh, 0, 0);
    print "File contains: ", readline($fh);

See seek for some details about mixing reading and writing.

読み書きを混ぜる場合の詳細については seek を参照してください。

Portability issues: "open" in perlport.

移植性の問題: "open" in perlport

opendir DIRHANDLE,EXPR

Opens a directory named EXPR for processing by readdir, telldir, seekdir, rewinddir, and closedir. Returns true if successful. DIRHANDLE may be an expression whose value can be used as an indirect dirhandle, usually the real dirhandle name. If DIRHANDLE is an undefined scalar variable (or array or hash element), the variable is assigned a reference to a new anonymous dirhandle; that is, it's autovivified. Dirhandles are the same objects as filehandles; an I/O object can only be open as one of these handle types at once.

readdirtelldirseekdirrewinddirclosedir で処理するために、EXPR で指定された名前の ディレクトリをオープンします。 成功時には真を返します。 DIRHANDLE は間接ディレクトリハンドルとして使える値(普通は実際のディレクトリ ハンドルの名前)となる式でも構いません。 DIRHANDLE が未定義のスカラ値(または配列かハッシュの要素)の場合、その変数は 新しい無名ディレクトリハンドルへのリファレンスが代入されます; つまり、 自動有効化されます。 ディレクトリハンドルはファイルハンドルと同じオブジェクトです; 一つの I/O オブジェクトは同時にこれらのハンドル型のどちらかとしてのみ 開くことができます。

See the example at readdir.

readdir の例を参照してください。

ord EXPR
ord

Returns the numeric value of the first character of EXPR. If EXPR is an empty string, returns 0. If EXPR is omitted, uses $_. (Note character, not byte.)

EXPR の最初の文字の数値としての値を返します。 EXPR が空文字列の場合は、0 を返します。 EXPR が省略されると、$_ を使います。 (バイトではなく 文字 であることに注意してください。)

For the reverse, see chr. See perlunicode for more about Unicode.

逆のことをするには chr を参照してください。 Unicode については perlunicode を参照してください。

our VARLIST
our TYPE VARLIST
our VARLIST : ATTRS
our TYPE VARLIST : ATTRS

our makes a lexical alias to a package (i.e. global) variable of the same name in the current package for use within the current lexical scope.

our は単純名を、現在のレキシカルスコープ内で使うために、 現在のパッケージの同じ名前のパッケージ(つまりグローバルな)変数への レキシカルな別名を作ります。

our has the same scoping rules as my or state, meaning that it is only valid within a lexical scope. Unlike my and state, which both declare new (lexical) variables, our only creates an alias to an existing variable: a package variable of the same name.

ourmystate と同じスコープルールを持ちます; つまり レキシカルスコープの中でだけ有効です。 新しい(レキシカル)変数を宣言する mystate と異なり、our は既に 存在する変数への別名を作るだけです: 同じ名前のパッケージ変数です。

This means that when use strict 'vars' is in effect, our lets you use a package variable without qualifying it with the package name, but only within the lexical scope of the our declaration. This applies immediately--even within the same statement.

つまり、use strict 'vars' が有効の場合は、our を 使うことで、 パッケージ変数をパッケージ名で修飾することなく使うことができますが、 our 宣言のレキシカルスコープ内だけということです。 これは(たとえ同じ文の中でも)直ちに適用されます。

    package Foo;
    use strict;

    $Foo::foo = 23;

    {
        our $foo;   # alias to $Foo::foo
        print $foo; # prints 23
    }

    print $Foo::foo; # prints 23

    print $foo; # ERROR: requires explicit package name

This works even if the package variable has not been used before, as package variables spring into existence when first used.

これはパッケージ変数がまだ使われていなくても動作します; パッケージ変数は、 最初に使われた時にひょっこり現れるからです。

    package Foo;
    use strict;

    our $foo = 23;   # just like $Foo::foo = 23

    print $Foo::foo; # prints 23

Because the variable becomes legal immediately under use strict 'vars', so long as there is no variable with that name is already in scope, you can then reference the package variable again even within the same statement.

変数は use strict 'vars' の基で直ちに正当になるので、 スコープ内に同じ名前の変数がない限り、 たとえ同じ文の中でもパッケージ変数を再び参照できます。

    package Foo;
    use strict;

    my  $foo = $foo; # error, undeclared $foo on right-hand side
    our $foo = $foo; # no errors

If more than one variable is listed, the list must be placed in parentheses.

複数の変数を指定する場合は、リストはかっこでくくらなければなりません。

    our($bar, $baz);

An our declaration declares an alias for a package variable that will be visible across its entire lexical scope, even across package boundaries. The package in which the variable is entered is determined at the point of the declaration, not at the point of use. This means the following behavior holds:

our 宣言はレキシカルスコープ全体に対して (たとえ パッケージ境界を越えていても)見える、パッケージ変数への別名を宣言します。 この変数が入るパッケージは宣言した時点で定義され、 使用した時点ではありません。 これにより、以下のような振る舞いになります:

    package Foo;
    our $bar;      # declares $Foo::bar for rest of lexical scope
    $bar = 20;

    package Bar;
    print $bar;    # prints 20, as it refers to $Foo::bar

Multiple our declarations with the same name in the same lexical scope are allowed if they are in different packages. If they happen to be in the same package, Perl will emit warnings if you have asked for them, just like multiple my declarations. Unlike a second my declaration, which will bind the name to a fresh variable, a second our declaration in the same package, in the same scope, is merely redundant.

同じレキシカルスコープでも、パッケージが異なっていれば、同じ名前で複数の our 宣言ができます。 同じパッケージになっていると、警告が出力されるようになっていれば 複数の my 宣言がある場合と同じように警告が出力されます。 新しい変数を名前に割り当てることになる 2 回目の my 宣言と 違って、同じパッケージの同じスコープで 2 回 our 宣言するのは単に冗長です。

    use warnings;
    package Foo;
    our $bar;      # declares $Foo::bar for rest of lexical scope
    $bar = 20;

    package Bar;
    our $bar = 30; # declares $Bar::bar for rest of lexical scope
    print $bar;    # prints 30

    our $bar;      # emits warning but has no other effect
    print $bar;    # still prints 30

An our declaration may also have a list of attributes associated with it.

our 宣言には、それと結び付けられる属性のリストを 持つこともあります。

The exact semantics and interface of TYPE and ATTRS are still evolving. TYPE is currently bound to the use of the fields pragma, and attributes are handled using the attributes pragma, or, starting from Perl 5.8.0, also via the Attribute::Handlers module. See "Private Variables via my()" in perlsub for details.

TYPE と ATTRS の正確な文法とインターフェースは今でも進化しています。 現在のところ、TYPE は fields プラグマの使用と結び付けられていて、 属性は attributes プラグマか、Perl 5.8.0 からは Attribute::Handlers モジュールと結び付けられています。 詳しくは "Private Variables via my()" in perlsub を参照してください。

Note that with a parenthesised list, undef can be used as a dummy placeholder, for example to skip assignment of initial values:

かっこで囲まれたリストでは、undef は、例えば初期値の代入を 飛ばすために、ダミーのプレースホルダとして使えることに注意してください:

    our ( undef, $min, $hour ) = localtime;

our differs from use vars, which allows use of an unqualified name only within the affected package, but across scopes.

ouruse vars と異なります; スコープを またぐのではなく、影響するパッケージの内側 のみ で完全修飾されていない 名前を使えるようにします。

pack TEMPLATE,LIST

Takes a LIST of values and converts it into a string using the rules given by the TEMPLATE. The resulting string is the concatenation of the converted values. Typically, each converted value looks like its machine-level representation. For example, on 32-bit machines an integer may be represented by a sequence of 4 bytes, which will in Perl be presented as a string that's 4 characters long.

LIST の値を TEMPLATE で与えられたルールを用いて文字列に変換します。 結果の文字列は変換した値を連結したものです。 典型的には、それぞれの変換された値はマシンレベルの表現のように見えます。 例えば、32-bit マシンでは、整数は 4 バイトで表現されるので、 Perl では 4 文字の文字列で表現されます。

See perlpacktut for an introduction to this function.

この関数の説明については perlpacktut を参照してください。

The TEMPLATE is a sequence of characters that give the order and type of values, as follows:

TEMPLATE は、以下のような値の型と順番を指定する文字を並べたものです:

    a  A string with arbitrary binary data, will be null padded.
    A  A text (ASCII) string, will be space padded.
    Z  A null-terminated (ASCIZ) string, will be null padded.
    a  任意のバイナリデータを含む文字列、ヌル文字で埋める。
    A  テキスト (ASCII) 文字列、スペース文字で埋める。
    Z  ヌル文字終端 (ASCIZ) 文字列、ヌル文字で埋める。
    b  A bit string (ascending bit order inside each byte,
       like vec()).
    B  A bit string (descending bit order inside each byte).
    h  A hex string (low nybble first).
    H  A hex string (high nybble first).
    b  ビット列 (バイトごとに昇ビット順、vec() と同じ)。
    B  ビット列 (バイトごとに降ビット順)。
    h  16 進数文字列 (低位ニブルが先)。
    H  16 進数文字列 (高位ニブルが先)。
    c  A signed char (8-bit) value.
    C  An unsigned char (octet) value.
    W  An unsigned char value (can be greater than 255).
    c  signed char (8 ビット) 値。
    C  unsigned char (オクテット) 値。
    W  unsigned char 値 (255 より大きいかもしれません)。
    s  A signed short (16-bit) value.
    S  An unsigned short value.
    s  signed short (16 ビット) 値。
    S  unsigned short 値。
    l  A signed long (32-bit) value.
    L  An unsigned long value.
    l  signed long (32 ビット) 値。
    L  unsigned long 値。
    q  A signed quad (64-bit) value.
    Q  An unsigned quad value.
         (Quads are available only if your system supports 64-bit
          integer values _and_ if Perl has been compiled to support
          those.  Raises an exception otherwise.)
    q  符号付き 64 ビット整数。
    Q  符号なし 64 ビット整数。
      (64 ビット整数は、システムが 64 ビット整数に対応していて、かつ Perl が
       64 ビット整数対応としてコンパイルされている場合にのみ使用可能です。
           それ以外の場合は例外が発生します。)
    i  A signed integer value.
    I  An unsigned integer value.
         (This 'integer' is _at_least_ 32 bits wide.  Its exact
          size depends on what a local C compiler calls 'int'.)
    i  signed int 値。
    I  unsigned int 値。
       (ここでの 'integer' は 「最低」 32 ビット幅です。正確なサイズは
        ローカルの C コンパイラの 'int' のサイズに依存します。)
    n  An unsigned short (16-bit) in "network" (big-endian) order.
    N  An unsigned long (32-bit) in "network" (big-endian) order.
    v  An unsigned short (16-bit) in "VAX" (little-endian) order.
    V  An unsigned long (32-bit) in "VAX" (little-endian) order.
    n  "network" 順序 (ビッグエンディアン) の unsigned short (16 ビット)。
    N  "network" 順序 (ビッグエンディアン) の unsigned long (32 ビット)。
    v  "VAX" 順序 (リトルエンディアン) の unsigned short (16 ビット)。
    V  "VAX" 順序 (リトルエンディアン) の unsigned long (32 ビット)。
    j  A Perl internal signed integer value (IV).
    J  A Perl internal unsigned integer value (UV).
    j  Perl 内部符号付き整数 (IV)。
    J  Perl 内部符号なし整数 (UV)。
    f  A single-precision float in native format.
    d  A double-precision float in native format.
    f  機種依存の単精度浮動小数点数。
    d  機種依存の倍精度浮動小数点数。
    F  A Perl internal floating-point value (NV) in native format
    D  A float of long-double precision in native format.
         (Long doubles are available only if your system supports
          long double values _and_ if Perl has been compiled to
          support those.  Raises an exception otherwise.
          Note that there are different long double formats.)
    F  ネイティブフォーマットの Perl 内部浮動小数点数 (NV)
    D  ネイティブフォーマットの長い倍精度浮動小数点数(long double)。
      (long double は、システムが long double に対応していて、かつ Perl が
       long double 対応としてコンパイルされている場合にのみ使用可能です。
          それ以外の場合は例外が発生します。
          long double 型式の場合は異なることに注意してください)
    p  A pointer to a null-terminated string.
    P  A pointer to a structure (fixed-length string).
    p  ヌル文字で終端する文字列へのポインタ。
    P  構造体 (固定長文字列) へのポインタ。
    u  A uuencoded string.
    U  A Unicode character number.  Encodes to a character in char-
       acter mode and UTF-8 (or UTF-EBCDIC in EBCDIC platforms) in
       byte mode.
    u  uuencode 文字列。
    U  Unicode 文字番号。文字モードでは文字に、バイトモードなら UTF-8 に
       (EBCDIC システムでは UTF-EBCDIC に)エンコードされます。
    w  A BER compressed integer (not an ASN.1 BER, see perlpacktut
       for details).  Its bytes represent an unsigned integer in
       base 128, most significant digit first, with as few digits
       as possible.  Bit eight (the high bit) is set on each byte
       except the last.
    w  A BER 圧縮変数(ASN.1 BER ではありません; 詳細については perlpacktut を
       参照してください)。このバイト列はできるだけ少ない桁数で表現された
       128 を基とした符号なし整数で、最上位ビットから順に並びます。
       最後のバイト以外の各バイトのビット 8 (上位ビット) がセットされます。
    x  A null byte (a.k.a ASCII NUL, "\000", chr(0))
    X  Back up a byte.
    @  Null-fill or truncate to absolute position, counted from the
       start of the innermost ()-group.
    .  Null-fill or truncate to absolute position specified by
       the value.
    (  Start of a ()-group.
    x  ヌル文字 (つまり ASCII NUL, "\000", chr(0))
    X  1 文字後退。
    @  一番内側の () の組の開始位置から数えて、絶対位置までヌル文字で
       埋めるか切り詰める。
    .  値で指定した絶対位置までヌル文字で埋めるか切り詰める。
    (  () の組の開始。

One or more modifiers below may optionally follow certain letters in the TEMPLATE (the second column lists letters for which the modifier is valid):

以下に示す一つまたは複数の修飾子を、TEMPLATE の文字のいくつかにオプションで 付けることができます(表の 2 列目は、その修飾子が有効な文字です):

    !   sSlLiI     Forces native (short, long, int) sizes instead
                   of fixed (16-/32-bit) sizes.
    !   sSlLiI     固定の(16/32 ビット)サイズではなく、ネイティブな
                   (short, long, int)サイズを強制する。
    !   xX         Make x and X act as alignment commands.
    !   xX         x と X をアライメントコマンドとして振舞わせる。
    !   nNvV       Treat integers as signed instead of unsigned.
    !   nNvV       整数を符号なしではなく符号付きとして扱わせる。
    !   @.         Specify position as byte offset in the internal
                   representation of the packed string.  Efficient
                   but dangerous.
    !   @.         pack された内部表現のバイトオフセットとして位置を指定する。
                   効率的ですが危険です。
    >   sSiIlLqQ   Force big-endian byte-order on the type.
        jJfFdDpP   (The "big end" touches the construct.)
    >   sSiIlLqQ   これらの型のバイト順をビッグエンディアンに強制します。
        jJfFdDpP   (「大きい端」が構造に触れています。)
    <   sSiIlLqQ   Force little-endian byte-order on the type.
        jJfFdDpP   (The "little end" touches the construct.)
    <   sSiIlLqQ   これらの型のバイト順をリトルエンディアンに強制します。
        jJfFdDpP   (「小さい端」が構造に触れています。)

The > and < modifiers can also be used on () groups to force a particular byte-order on all components in that group, including all its subgroups.

>< の修飾子は ()-グループでも使えます; この場合はそのグループと全ての副グループ内の全ての要素を特定のバイト順に 強制します。

The following rules apply:

以下の条件が適用されます:

  • Each letter may optionally be followed by a number indicating the repeat count. A numeric repeat count may optionally be enclosed in brackets, as in pack("C[80]", @arr). The repeat count gobbles that many values from the LIST when used with all format types other than a, A, Z, b, B, h, H, @, ., x, X, and P, where it means something else, described below. Supplying a * for the repeat count instead of a number means to use however many items are left, except for:

    これらの文字の後には、繰り返し数を示す数字を付けることができます。 数値の繰り返し数は pack "C[80]", @arr のように大かっこで 囲むこともできます。 a, A, Z, b, B, h, H, @, ., x, X, P 以外の全ての型では、LIST から繰り返し数の値を取り出して使います。 繰り返し数に * を指定すると、以下の例外を除いて、 その時点で残っているすべての要素を意味します。

    • @, x, and X, where it is equivalent to 0.

      @, x, X では 0 と等価です。

    • <.>, where it means relative to the start of the string.

      <.> では文字列の先頭からの相対位置を意味します。

    • u, where it is equivalent to 1 (or 45, which here is equivalent).

      u では 1 (あるいはここでは 45 でも等価です) と等価です。

    One can replace a numeric repeat count with a template letter enclosed in brackets to use the packed byte length of the bracketed template for the repeat count.

    このテンプレートでパックされたバイト長を繰り返し数として使うために、 大かっこで囲まれたテンプレートで数値の繰り返し数を置き換えることが できます。

    For example, the template x[L] skips as many bytes as in a packed long, and the template "$t X[$t] $t" unpacks twice whatever $t (when variable-expanded) unpacks. If the template in brackets contains alignment commands (such as x![d]), its packed length is calculated as if the start of the template had the maximal possible alignment.

    例えば、テンプレート x[L] は long でパックされたバイト数分だけスキップし、 テンプレート "$t X[$t] $t" は $t (変数展開された場合)を unpack したものの 2 倍を unpack します。 (x![d] のように) 大かっこにアライメントコマンドが含まれている場合、 パックされた長さは、テンプレートの先頭で最大限可能なアライメントを 持っているものとして計算されます。

    When used with Z, a * as the repeat count is guaranteed to add a trailing null byte, so the resulting string is always one byte longer than the byte length of the item itself.

    Z で、繰り返し数として * が使われた場合、末尾にヌルバイトが 保証されるので、結果の文字列は常にアイテム自身のバイト長よりも 1 バイト 長くなります。

    When used with @, the repeat count represents an offset from the start of the innermost () group.

    @ で使うと、繰り返し数は一番内側の () グループの先頭からのオフセットを 表現します。

    When used with ., the repeat count determines the starting position to calculate the value offset as follows:

    . で使われると、繰り返し数は以下のようにして、 値のオフセットを計算するための開始位置を決定するために使われます。

    • If the repeat count is 0, it's relative to the current position.

      繰り返し数が 0 なら、現在位置からの相対位置となります。

    • If the repeat count is *, the offset is relative to the start of the packed string.

      繰り返し数が * なら、オフセットは pack された文字列の先頭からの 相対位置です。

    • And if it's an integer n, the offset is relative to the start of the nth innermost ( ) group, or to the start of the string if n is bigger then the group level.

      そして整数 n なら、オフセットは一番内側から n 番目の ( ) グループの 先頭、あるいは n がグループレベルより大きい場合は文字列の先頭からの 相対位置です。

    The repeat count for u is interpreted as the maximal number of bytes to encode per line of output, with 0, 1 and 2 replaced by 45. The repeat count should not be more than 65.

    u での繰り返し回数は、出力行毎に最大何バイトまでをエンコードするかを 示します; 0, 1, 2 は 45 として扱われます。 繰り返し数は 65 を超えてはなりません。

  • The a, A, and Z types gobble just one value, but pack it as a string of length count, padding with nulls or spaces as needed. When unpacking, A strips trailing whitespace and nulls, Z strips everything after the first null, and a returns data with no stripping at all.

    a, A, Z という型を使うと、値を一つだけ取り出して使いますが、 繰り返し数で示す長さの文字列となるように、必要に応じてヌル文字か スペース文字を付け足します。 unpack するとき、A は後続の空白やヌル文字を取り除きます; Z は最初の ヌル文字以降の全てを取り除きます; a はデータを取り除くことなく そのまま返します。

    If the value to pack is too long, the result is truncated. If it's too long and an explicit count is provided, Z packs only $count-1 bytes, followed by a null byte. Thus Z always packs a trailing null, except when the count is 0.

    pack する値が長すぎる場合、結果は切り詰められます。 長すぎてかつ明示的に個数が指定されている場合、 Z$count-1 バイトまで pack し、その後にヌルバイトがつきます。 従って、Z は、繰り返し数が 0 の場合を除いて、常に末尾にヌルバイトが つきます。

  • Likewise, the b and B formats pack a string that's that many bits long. Each such format generates 1 bit of the result. These are typically followed by a repeat count like B8 or B64.

    同様に、bB は、繰り返し数で示すビット長のビット列に pack します。 これらの各文字は結果の 1 ビットを生成します。 これらは典型的には B8B64 のような繰り返しカウントが引き続きます。

    Each result bit is based on the least-significant bit of the corresponding input character, i.e., on ord($char)%2. In particular, characters "0" and "1" generate bits 0 and 1, as do characters "\000" and "\001".

    結果ビットのそれぞれは対応する入力文字の最下位ビットを基にします (つまり ord($char)%2)。 特に、文字 "0""1" は文字 "\000""\001" と同様に、 ビット 0 と 1 を生成します。

    Starting from the beginning of the input string, each 8-tuple of characters is converted to 1 character of output. With format b, the first character of the 8-tuple determines the least-significant bit of a character; with format B, it determines the most-significant bit of a character.

    pack() の入力文字列の先頭から始めて、8 タプル毎に 1 文字の出力に変換されます。 b フォーマットでは 8 タプルの最初の文字が出力の最下位ビットとなります; B フォーマットでは出力の最上位ビットとなります。

    If the length of the input string is not evenly divisible by 8, the remainder is packed as if the input string were padded by null characters at the end. Similarly during unpacking, "extra" bits are ignored.

    もし入力文字列の長さが 8 で割り切れない場合、余りの部分は入力文字列の 最後にヌル文字がパッディングされているものとしてパックされます。 同様に、unpack 中は「余分な」ビットは無視されます。

    If the input string is longer than needed, remaining characters are ignored.

    入力文字列が必要な分よりも長い場合、余分な文字は無視されます。

    A * for the repeat count uses all characters of the input field. On unpacking, bits are converted to a string of 0s and 1s.

    繰り返し数として * が指定されると、入力フィールドの全ての文字が使われます。 unpack 時にはビット列は 01 の文字列に変換されます。

  • The h and H formats pack a string that many nybbles (4-bit groups, representable as hexadecimal digits, "0".."9" "a".."f") long.

    hH は、多ニブル長(16 進文字である "0".."9" "a".."f" で 表現可能な 4 ビットグループ)のニブル列に pack します。

    For each such format, pack generates 4 bits of result. With non-alphabetical characters, the result is based on the 4 least-significant bits of the input character, i.e., on ord($char)%16. In particular, characters "0" and "1" generate nybbles 0 and 1, as do bytes "\000" and "\001". For characters "a".."f" and "A".."F", the result is compatible with the usual hexadecimal digits, so that "a" and "A" both generate the nybble 0xA==10. Use only these specific hex characters with this format.

    このようなフォーマット文字のそれぞれについて、pack は 結果の 4 ビットを生成します。 英字でない文字の場合、結果は入力文字の下位 4 ビットを 基にします(つまり ord($char)%16)。 特に、文字 "0""1" はバイト "\000""\001" と同様に ニブル 0 と 1 を生成します。 文字 "a".."f""A".."F" の場合は結果は通常の 16 進数と同じ結果に なるので、"a""A" はどちらも ニブル 0xa==10 を生成します。 これらの 16 進文字はこの特定のフォーマットでだけ使ってください。

    Starting from the beginning of the template to pack, each pair of characters is converted to 1 character of output. With format h, the first character of the pair determines the least-significant nybble of the output character; with format H, it determines the most-significant nybble.

    pack のテンプレートの先頭から始めて、2 文字毎に 1 文字の出力に変換されます。 h フォーマットでは 1 文字目が出力の最下位ニブルとなり、 H フォーマットでは出力の最上位ニブルとなります。

    If the length of the input string is not even, it behaves as if padded by a null character at the end. Similarly, "extra" nybbles are ignored during unpacking.

    入力文字列の長さが偶数でない場合、最後にヌル文字でパッディングされて いるかのように振る舞います。 同様に、unpack 中は「余分な」ニブルは無視されます。

    If the input string is longer than needed, extra characters are ignored.

    入力文字列が必要な分より長い場合、余分な部分は無視されます。

    A * for the repeat count uses all characters of the input field. For unpack, nybbles are converted to a string of hexadecimal digits.

    繰り返し数として * が指定されると、入力フィールドの全ての文字が使われます。 unpack 時にはニブルは 16 進数の文字列に 変換されます。

  • The p format packs a pointer to a null-terminated string. You are responsible for ensuring that the string is not a temporary value, as that could potentially get deallocated before you got around to using the packed result. The P format packs a pointer to a structure of the size indicated by the length. A null pointer is created if the corresponding value for p or P is undef; similarly with unpack, where a null pointer unpacks into undef.

    p は、ヌル文字終端文字列へのポインタを pack します。 文字列が一時的な値でない(つまり pack された結果を使う前に文字列が 解放されない) ことに責任を持つ必要があります。 P は、指定した長さの構造体へのポインタを pack します。 p または P に対応する値が undef だった場合、 ヌルポインタが作成されます; ヌルポインタが undef に unpack される unpack と同様です。

    If your system has a strange pointer size--meaning a pointer is neither as big as an int nor as big as a long--it may not be possible to pack or unpack pointers in big- or little-endian byte order. Attempting to do so raises an exception.

    システムのポインタが変わったサイズの場合--つまり、int の大きさでも long の大きさでもない場合--ポインタをビッグエンディアンやリトルエンディアンの バイト順で pack や unpack することはできません。 そうしようとすると例外が発生します。

  • The / template character allows packing and unpacking of a sequence of items where the packed structure contains a packed item count followed by the packed items themselves. This is useful when the structure you're unpacking has encoded the sizes or repeat counts for some of its fields within the structure itself as separate fields.

    / テンプレート文字は、アイテムの数の後にアイテムそのものが入っている形の アイテム列を pack 及び unpack します。 これは、unpack したい構造体が、サイズや繰り返し数が構造体自身の中に 独立したフィールドとしてエンコードされている場合に有効です。

    For pack, you write length-item/sequence-item, and the length-item describes how the length value is packed. Formats likely to be of most use are integer-packing ones like n for Java strings, w for ASN.1 or SNMP, and N for Sun XDR.

    pack では length-item/string-item の 形になり、 length-item は長さの値がどのように pack されているかを指定します。 もっともよく使われるのは Java 文字列 のための n、ASN.1 や SNMP のための w、Sun XDR のための N といった整数型です。

    For pack, sequence-item may have a repeat count, in which case the minimum of that and the number of available items is used as the argument for length-item. If it has no repeat count or uses a '*', the number of available items is used.

    pack では、sequence-item は繰り返し数を 持つことがあり、その場合はその最小値と利用可能なアイテムの数は length-item のための引数として使われます。 繰り返し数がなかったり、'*' を使うと、利用可能なアイテムの数が使われます。

    For unpack, an internal stack of integer arguments unpacked so far is used. You write /sequence-item and the repeat count is obtained by popping off the last element from the stack. The sequence-item must not have a repeat count.

    unpack では、今まで unpack した数値引数の 内部スタックが使われます。 /sequence-item と書いて、繰り返し数はスタックから最後の要素を 取り出すことで得ます。 sequence-item は繰り返し数を持っていてはいけません。

    If sequence-item refers to a string type ("A", "a", or "Z"), the length-item is the string length, not the number of strings. With an explicit repeat count for pack, the packed string is adjusted to that length. For example:

    sequence-item が文字列型 ("A", "a", "Z") を参照している場合、 length-item は文字列の数ではなく、文字列の長さです。 pack で明示的な繰り返し数があると、pack された文字列は与えられた 長さに調整されます。 例えば:

     This code:                             gives this result:
    
     unpack("W/a", "\004Gurusamy")          ("Guru")
     unpack("a3/A A*", "007 Bond  J ")      (" Bond", "J")
     unpack("a3 x2 /A A*", "007: Bond, J.") ("Bond, J", ".")
    
     pack("n/a* w/a","hello,","world")     "\000\006hello,\005world"
     pack("a/W2", ord("a") .. ord("z"))    "2ab"

    The length-item is not returned explicitly from unpack.

    length-itemunpack から明示的には 返されません。

    Supplying a count to the length-item format letter is only useful with A, a, or Z. Packing with a length-item of a or Z may introduce "\000" characters, which Perl does not regard as legal in numeric strings.

    length-item 文字に繰り返し数をつけるのは、 文字が A, a, Z でない限りは有用ではありません。 aZlength-item として pack すると "\000" 文字が 出力されることがあり、Perl はこれを有効な数値文字列として認識しません。

  • The integer types s, S, l, and L may be followed by a ! modifier to specify native shorts or longs. As shown in the example above, a bare l means exactly 32 bits, although the native long as seen by the local C compiler may be larger. This is mainly an issue on 64-bit platforms. You can see whether using ! makes any difference this way:

    s, S, l, L の整数タイプに引き続いて ! 修飾子を つけることで、ネイティブの short や long を指定できます。 上述のように、l は正確に 32 ビットですが、ネイティブな (ローカルな C コンパイラによる)long はもっと大きいかもしれません。 これは主に 64 ビットプラットフォームで意味があります。 ! を使うことによって違いがあるかどうかは以下のようにして調べられます:

        printf "format s is %d, s! is %d\n",
            length pack("s"), length pack("s!");
    
        printf "format l is %d, l! is %d\n",
            length pack("l"), length pack("l!");

    i! and I! are also allowed, but only for completeness' sake: they are identical to i and I.

    i!I! も動作しますが、単に完全性のためだけです; これは i 及び I と同じです。

    The actual sizes (in bytes) of native shorts, ints, longs, and long longs on the platform where Perl was built are also available from the command line:

    Perl がビルドされたプラットフォームでの short, int, long, long long の 実際の(バイト数での)サイズはコマンドラインから:

        $ perl -V:{short,int,long{,long}}size
        shortsize='2';
        intsize='4';
        longsize='4';
        longlongsize='8';

    or programmatically via the Config module:

    あるいは Config モジュールからプログラムで:

           use Config;
           print $Config{shortsize},    "\n";
           print $Config{intsize},      "\n";
           print $Config{longsize},     "\n";
           print $Config{longlongsize}, "\n";

    $Config{longlongsize} is undefined on systems without long long support.

    システムが long long に対応していない場合は $Config{longlongsize} は 未定義値になります。

  • The integer formats s, S, i, I, l, L, j, and J are inherently non-portable between processors and operating systems because they obey native byteorder and endianness. For example, a 4-byte integer 0x12345678 (305419896 decimal) would be ordered natively (arranged in and handled by the CPU registers) into bytes as

    整数フォーマット s, S, i, I, l, L, j, J は ネイティブなバイト順序とエンディアンに従っているため、 本質的にプロセッサ間や OS 間で移植性がありません。 例えば 4 バイトの整数 0x12345678 (10 進数では 305419896) は 内部では(CPU レジスタによって変換され扱われる形では) 以下のようなバイト列に並べられます:

        0x12 0x34 0x56 0x78  # big-endian
        0x78 0x56 0x34 0x12  # little-endian

    Basically, Intel and VAX CPUs are little-endian, while everybody else, including Motorola m68k/88k, PPC, Sparc, HP PA, Power, and Cray, are big-endian. Alpha and MIPS can be either: Digital/Compaq uses (well, used) them in little-endian mode, but SGI/Cray uses them in big-endian mode.

    基本的に、Intel と VAX の CPU はリトルエンディアンです; 一方、 Motorola m68k/88k, PPC, Sparc, HP PA, Power, Cray などを含むその他の全ては ビッグエンディアンです。 Alpha と MIPS は両方ともあります: Digital/Compaq はリトルエンディアンモードで 使っています (えーと、いました) が、SGI/Cray はビッグエンディアンモードで 使っています。

    The names big-endian and little-endian are comic references to the egg-eating habits of the little-endian Lilliputians and the big-endian Blefuscudians from the classic Jonathan Swift satire, Gulliver's Travels. This entered computer lingo via the paper "On Holy Wars and a Plea for Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980.

    ビッグエンディアンリトルエンディアン の名前は、 ジョナサン=スウィフトによる風刺小説の古典 ガリバー旅行記 での、卵を 小さい方からむくリリパット国と大きい方からむくブレフスキュ国から 取られています。 "On Holy Wars and a Plea for Peace" by Danny Cohen, USC/ISI IEN 137, April 1, 1980 の文書からコンピュータ用語として取り入れられました。

    Some systems may have even weirder byte orders such as

    以下のような、さらに変わったバイト順序を持つシステムもあるかもしれません:

       0x56 0x78 0x12 0x34
       0x34 0x12 0x78 0x56

    These are called mid-endian, middle-endian, mixed-endian, or just weird.

    これらは mid-endian, middle-endian, mixed-endian あるいは単におかしなものと 呼ばれます。

    You can determine your system endianness with this incantation:

    システムの設定は以下のようにして調べられます:

       printf("%#02x ", $_) for unpack("W*", pack L=>0x12345678);

    The byteorder on the platform where Perl was built is also available via Config:

    Perl がビルドされたプラットフォームでのバイト順序は Config 経由か:

        use Config;
        print "$Config{byteorder}\n";

    or from the command line:

    あるいはコマンドラインで:

        $ perl -V:byteorder

    Byteorders "1234" and "12345678" are little-endian; "4321" and "87654321" are big-endian. Systems with multiarchitecture binaries will have "ffff", signifying that static information doesn't work, one must use runtime probing.

    "1234""12345678" はリトルエンディアンです; "4321""87654321" はビッグエンディアンです。 マルチアーキテクチャバイナリを持つシステムは "ffff" となります; これは静的な情報は動作せず、実行時調査を使う必要が あることを示します。

    For portably packed integers, either use the formats n, N, v, and V or else use the > and < modifiers described immediately below. See also perlport.

    移植性のあるパック化された整数がほしい場合は、 n, N, v, V フォーマットを使うか、 直後で説明する >< の修飾子が使えます。 perlport も参照してください。

  • Also floating point numbers have endianness. Usually (but not always) this agrees with the integer endianness. Even though most platforms these days use the IEEE 754 binary format, there are differences, especially if the long doubles are involved. You can see the Config variables doublekind and longdblkind (also doublesize, longdblsize): the "kind" values are enums, unlike byteorder.

    また、浮動小数点数にもエンディアンがあります。 通常は(但し常にではありません)これは整数のエンディアンと同じです。 最近のほとんどのプラットフォームが IEEE 754 バイナリ形式を使っているにも 関わらず、(特に long double 関連で) 相違点があります。 Config 変数 doublekindlongdblkind (および doublesize, longdblsize) を参照できます: "kind" 値は byteorder と異なり、 順序値です。

    Portability-wise the best option is probably to keep to the IEEE 754 64-bit doubles, and of agreed-upon endianness. Another possibility is the "%a") format of printf.

    移植性を考慮した最良の選択肢はおそらく、IEEE 754 64-bit double と同意した エンディアンを維持することです。 もう一つの可能性は printf"%a" 型式です。

  • Starting with Perl 5.10.0, integer and floating-point formats, along with the p and P formats and () groups, may all be followed by the > or < endianness modifiers to respectively enforce big- or little-endian byte-order. These modifiers are especially useful given how n, N, v, and V don't cover signed integers, 64-bit integers, or floating-point values.

    Perl 5.10.0 から、pP フォーマットや () グループと同様、 全ての整数と浮動小数点数のフォーマットは、>< の エンディアン修飾子をつけることで、それぞれ ビッグエンディアンとリトルエンディアンに強制させることができます。 n, N, v, V は符号付き整数、64 ビット整数、浮動小数点数に 対応していないので、これは特に有用です。

    Here are some concerns to keep in mind when using an endianness modifier:

    エンディアン修飾子を使うときに心に留めておくべきことを記します:

    • Exchanging signed integers between different platforms works only when all platforms store them in the same format. Most platforms store signed integers in two's-complement notation, so usually this is not an issue.

      異なったプラットフォームで符号付き整数を交換することは、全ての プラットフォームで同じフォーマットで保存されている場合にのみうまくいきます。 ほとんどのプラットフォームでは符号付き整数は 2 の補数記法で保存するので、 普通はこれは問題になりません。

    • The > or < modifiers can only be used on floating-point formats on big- or little-endian machines. Otherwise, attempting to use them raises an exception.

      >< の修飾子はビッグエンディアンやリトルエンディアンの マシンでの浮動小数点フォーマットでのみ使えます。 それ以外では、そのようなことをすると例外が発生します。

    • Forcing big- or little-endian byte-order on floating-point values for data exchange can work only if all platforms use the same binary representation such as IEEE floating-point. Even if all platforms are using IEEE, there may still be subtle differences. Being able to use > or < on floating-point values can be useful, but also dangerous if you don't know exactly what you're doing. It is not a general way to portably store floating-point values.

      データ交換のために浮動小数点数のバイト順をビッグエンディアンかリトル エンディアンに強制することは、全てのプラットフォームが IEEE 浮動小数点フォーマットのような同じバイナリ表現の場合にのみ うまくいきます。 たとえ全てのプラットフォームが IEEE を使っていても、そこには微妙な違いが あるかもしれません。 浮動小数点数に >< が使えることは便利な場合がありますが、 もし自分が何をしているかを正確に理解していなければ、危険です。 移植性のある浮動小数点数の保存のための一般的な方法はありません。

    • When using > or < on a () group, this affects all types inside the group that accept byte-order modifiers, including all subgroups. It is silently ignored for all other types. You are not allowed to override the byte-order within a group that already has a byte-order modifier suffix.

      () グループで >< を使うと、これは、副グループを 含む全ての型のうち、バイト順修飾子を受け入れる全てのものに影響与えます。 その他の型については沈黙のうちに無視されます。 既にバイト順接尾辞を持っているグループ内のバイト順を上書きすることは できません。

  • Real numbers (floats and doubles) are in native machine format only. Due to the multiplicity of floating-point formats and the lack of a standard "network" representation for them, no facility for interchange has been made. This means that packed floating-point data written on one machine may not be readable on another, even if both use IEEE floating-point arithmetic (because the endianness of the memory representation is not part of the IEEE spec). See also perlport.

    実数 (float と double) は、機種依存のフォーマットしかありません。 いろんな浮動小数点数のフォーマットが在り、標準的な "network" 表現といったものが ないため、データ交換のための機能は用意してありません。 つまり、あるマシンで pack した浮動小数点数は、別のマシンでは 読めないかもしれないということです; たとえ双方で IEEE フォーマットの 浮動小数点数演算を行なっていてもです (IEEE の仕様では、メモリ表現上の バイト順序までは、規定されていないからです)。 perlport も参照してください。

    If you know exactly what you're doing, you can use the > or < modifiers to force big- or little-endian byte-order on floating-point values.

    もし何をしようとしているのかを 正確に 理解しているなら、浮動小数点数の バイト順をビッグエンディアンやリトルエンディアンに強制するために、 >< の修飾子が使えます。

    Because Perl uses doubles (or long doubles, if configured) internally for all numeric calculation, converting from double into float and thence to double again loses precision, so unpack("f", pack("f", $foo)) will not in general equal $foo.

    Perl では、すべての数値演算のために、内部的に double (または設定によっては long double) を使用しているので、double から float へ変換し、それから再び double に戻すと精度が落ちることになり、unpack("f", pack("f", $foo)) は、 一般には $foo と同じではありません。

  • Pack and unpack can operate in two modes: character mode (C0 mode) where the packed string is processed per character, and UTF-8 byte mode (U0 mode) where the packed string is processed in its UTF-8-encoded Unicode form on a byte-by-byte basis. Character mode is the default unless the format string starts with U. You can always switch mode mid-format with an explicit C0 or U0 in the format. This mode remains in effect until the next mode change, or until the end of the () group it (directly) applies to.

    pack と unpack は二つのモードで操作します: pack された文字列を文字単位で 処理する文字モード (C0 モード) と、pack された文字列を、バイト毎に、 その UTF-8 エンコードされた形式で処理するUTF-8 モード (U0 モード) です。 文字モードはフォーマット文字列が U で始まっていない限りはデフォルトです。 モードはフォーマット中に明示的に C0 または U0 と書くことでいつでも 切り替えられます。 モードは次のモードに切り替えられるか、(直接)適用された () グループが 終了するまで有効です。

    Using C0 to get Unicode characters while using U0 to get non-Unicode bytes is not necessarily obvious. Probably only the first of these is what you want:

    Unicode 文字を取得するのに C0 を使い、 Unicode バイトを取得するのに U0 を使うというのは必ずしも明白ではありません。 おそらく、これらのうち最初のものだけが望みのものでしょう:

        $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
          perl -CS -ne 'printf "%v04X\n", $_ for unpack("C0A*", $_)'
        03B1.03C9
        $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
          perl -CS -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)'
        CE.B1.CF.89
        $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
          perl -C0 -ne 'printf "%v02X\n", $_ for unpack("C0A*", $_)'
        CE.B1.CF.89
        $ perl -CS -E 'say "\x{3B1}\x{3C9}"' |
          perl -C0 -ne 'printf "%v02X\n", $_ for unpack("U0A*", $_)'
        C3.8E.C2.B1.C3.8F.C2.89

    Those examples also illustrate that you should not try to use pack/unpack as a substitute for the Encode module.

    これらの例は、pack/ unpackEncode モジュールの代わりとして 使おうとするべきではないということも示しています。

  • You must yourself do any alignment or padding by inserting, for example, enough "x"es while packing. There is no way for pack and unpack to know where characters are going to or coming from, so they handle their output and input as flat sequences of characters.

    pack するときに、例えば十分な数の "x" を挿入することによって アライメントやパッディングを行うのは全て自分でしなければなりません。 packunpack は、 文字列がどこへ行くかやどこから来たかを 知る方法はないので、出力と入力をフラットな文字列として扱います。

  • A () group is a sub-TEMPLATE enclosed in parentheses. A group may take a repeat count either as postfix, or for unpack, also via the / template character. Within each repetition of a group, positioning with @ starts over at 0. Therefore, the result of

    () のグループはかっこで囲われた副テンプレートです。 グループは繰り返し数を取ることができます; 接尾辞によるか、 unpack の場合は / テンプレート文字によります。 グループの繰り返し毎に、@ の位置は 0 になります。 従って、以下の結果は:

        pack("@1A((@2A)@3A)", qw[X Y Z])

    is the string "\0X\0\0YZ".

    文字列 "\0X\0\0YZ" です。

  • x and X accept the ! modifier to act as alignment commands: they jump forward or back to the closest position aligned at a multiple of count characters. For example, to pack or unpack a C structure like

    xX にはアライメントコマンドとして ! 修飾子を付けることができます: これは count 文字の倍数のアライメントとなる、もっとも近い位置に移動します。 例えば、以下のような C 構造体を pack または unpack するには

        struct {
            char   c;    /* one signed, 8-bit character */
            double d;
            char   cc[2];
        }

    one may need to use the template c x![d] d c[2]. This assumes that doubles must be aligned to the size of double.

    W x![d] d W[2] というテンプレートを使う必要があるかもしれません。 これは double が double のサイズでアライメントされていることを 仮定しています。

    For alignment commands, a count of 0 is equivalent to a count of 1; both are no-ops.

    アライメントコマンドに対しては、count に 0 を指定するのは count に 1 を指定するのと等価です; どちらも何もしません。

  • n, N, v and V accept the ! modifier to represent signed 16-/32-bit integers in big-/little-endian order. This is portable only when all platforms sharing packed data use the same binary representation for signed integers; for example, when all platforms use two's-complement representation.

    n, N, v, V はビッグ/リトルエンディアンの順序で符号付き 16 または 32 ビット整数で表現するための ! 修飾子を受け入れます。 これは pack されたデータを共有する全てのプラットフォームが 符号付き整数について同じバイナリ表現を使う場合にのみ移植性があります; 例えば、全てのプラットフォームで 2 の補数表現を使う場合です。

  • Comments can be embedded in a TEMPLATE using # through the end of line. White space can separate pack codes from each other, but modifiers and repeat counts must follow immediately. Breaking complex templates into individual line-by-line components, suitably annotated, can do as much to improve legibility and maintainability of pack/unpack formats as /x can for complicated pattern matches.

    TEMPLATE の中の # から行末まではコメントです。 空白は pack コードをそれぞれ分けるために使えますが、修飾子と 繰り返し数は直後に置かなければなりません。 複雑なテンプレートを個々の行単位の要素に分解して適切に注釈をつけると、 複雑なパターンマッチングに対する /x と同じぐらい、pack/unpack フォーマットの読みやすさと保守性が向上します。

  • If TEMPLATE requires more arguments than pack is given, pack assumes additional "" arguments. If TEMPLATE requires fewer arguments than given, extra arguments are ignored.

    TEMPLATE が要求する引数の数が pack が実際に 与えている数より多い場合、 pack は追加の "" 引数があるものと仮定します。 TEMPLATE が要求する引数の数の方が少ない場合、余分の引数は無視されます。

  • Attempting to pack the special floating point values Inf and NaN (infinity, also in negative, and not-a-number) into packed integer values (like "L") is a fatal error. The reason for this is that there simply isn't any sensible mapping for these special values into integers.

    特殊浮動小数点値 InfNaN ((負を含む)無限と非数) を ("L" のような) 整数値に pack しようとすると 致命的エラーとなります。 この理由は、単に特殊値を整数に割り当てられないからです。

Examples:

例:

    $foo = pack("WWWW",65,66,67,68);
    # foo eq "ABCD"
    $foo = pack("W4",65,66,67,68);
    # same thing
    $foo = pack("W4",0x24b6,0x24b7,0x24b8,0x24b9);
    # same thing with Unicode circled letters.
    $foo = pack("U4",0x24b6,0x24b7,0x24b8,0x24b9);
    # same thing with Unicode circled letters.  You don't get the
    # UTF-8 bytes because the U at the start of the format caused
    # a switch to U0-mode, so the UTF-8 bytes get joined into
    # characters
    $foo = pack("C0U4",0x24b6,0x24b7,0x24b8,0x24b9);
    # foo eq "\xe2\x92\xb6\xe2\x92\xb7\xe2\x92\xb8\xe2\x92\xb9"
    # This is the UTF-8 encoding of the string in the
    # previous example

    $foo = pack("ccxxcc",65,66,67,68);
    # foo eq "AB\0\0CD"

    # NOTE: The examples above featuring "W" and "c" are true
    # only on ASCII and ASCII-derived systems such as ISO Latin 1
    # and UTF-8.  On EBCDIC systems, the first example would be
    #      $foo = pack("WWWW",193,194,195,196);

    $foo = pack("s2",1,2);
    # "\001\000\002\000" on little-endian
    # "\000\001\000\002" on big-endian

    $foo = pack("a4","abcd","x","y","z");
    # "abcd"

    $foo = pack("aaaa","abcd","x","y","z");
    # "axyz"

    $foo = pack("a14","abcdefg");
    # "abcdefg\0\0\0\0\0\0\0"

    $foo = pack("i9pl", gmtime);
    # a real struct tm (on my system anyway)

    $utmp_template = "Z8 Z8 Z16 L";
    $utmp = pack($utmp_template, @utmp1);
    # a struct utmp (BSDish)

    @utmp2 = unpack($utmp_template, $utmp);
    # "@utmp1" eq "@utmp2"

    sub bintodec {
        unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
    }

    $foo = pack('sx2l', 12, 34);
    # short 12, two zero bytes padding, long 34
    $bar = pack('s@4l', 12, 34);
    # short 12, zero fill to position 4, long 34
    # $foo eq $bar
    $baz = pack('s.l', 12, 4, 34);
    # short 12, zero fill to position 4, long 34

    $foo = pack('nN', 42, 4711);
    # pack big-endian 16- and 32-bit unsigned integers
    $foo = pack('S>L>', 42, 4711);
    # exactly the same
    $foo = pack('s<l<', -42, 4711);
    # pack little-endian 16- and 32-bit signed integers
    $foo = pack('(sl)<', -42, 4711);
    # exactly the same

The same template may generally also be used in unpack.

一般的には、同じテンプレートが unpack でも 使用できます。

package NAMESPACE
package NAMESPACE VERSION
package NAMESPACE BLOCK
package NAMESPACE VERSION BLOCK

Declares the BLOCK or the rest of the compilation unit as being in the given namespace. The scope of the package declaration is either the supplied code BLOCK or, in the absence of a BLOCK, from the declaration itself through the end of current scope (the enclosing block, file, or eval). That is, the forms without a BLOCK are operative through the end of the current scope, just like the my, state, and our operators. All unqualified dynamic identifiers in this scope will be in the given namespace, except where overridden by another package declaration or when they're one of the special identifiers that qualify into main::, like STDOUT, ARGV, ENV, and the punctuation variables.

BLOCK や残りのコンパイル単位を与えられた名前空間として宣言します。 パッケージ宣言のスコープは BLOCK か、BLOCK がないばあいは宣言自身から 現在のスコープの末尾 (閉じたブロック、ファイル、eval) です。 つまり、BLOCK なしの形式は、my, state, our 演算子と同様に現在のスコープの末尾にまで作用します。 このスコープ内の、全ての完全修飾されていない動的識別子は、他の package 宣言によって上書きされるか、 STDOUT, ARGV, ENV や句読点変数のように main:: に 割り当てられる特殊変数でない限り、指定された 名前空間になります。

A package statement affects dynamic variables only, including those you've used local on, but not lexically-scoped variables, which are created with my, state, or our. Typically it would be the first declaration in a file included by require or use. You can switch into a package in more than one place, since this only determines which default symbol table the compiler uses for the rest of that block. You can refer to identifiers in other packages than the current one by prefixing the identifier with the package name and a double colon, as in $SomePack::var or ThatPack::INPUT_HANDLE. If package name is omitted, the main package as assumed. That is, $::sail is equivalent to $main::sail (as well as to $main'sail, still seen in ancient code, mostly from Perl 4).

package 文は動的変数にのみ影響します(local で使ったものも 含みます)が、my, state, our のいずれかで作成された レキシカルなスコープの変数には 影響しません。 典型的にはこれは requireuse 演算子でインクルードされるファイルの 最初に宣言されます。 パッケージを複数の場所で切り替えることができます; なぜならこれは単にコンパイラがこのブロックの残りに対してどの シンボルテーブルを使うかにのみ影響するからです。 他のパッケージの識別子は、$SomePack::varThatPack::INPUT_HANDLE のように、識別子にパッケージ名と コロン二つをつけることで参照できます。 パッケージ名が省略された場合、main パッケージが仮定されます。 つまり、$::sail$main::sail と等価です(ほとんどは Perl 4 からの、 古いコードでは $main'sail もまだ見られます)。

If VERSION is provided, package sets the $VERSION variable in the given namespace to a version object with the VERSION provided. VERSION must be a "strict" style version number as defined by the version module: a positive decimal number (integer or decimal-fraction) without exponentiation or else a dotted-decimal v-string with a leading 'v' character and at least three components. You should set $VERSION only once per package.

VERSION が指定されると、package は与えられた 名前空間の $VERSION 変数に、 指定された VERSION の version オブジェクトをセットします。 VERSION は version で定義されている「厳密な」形式のバージョン番号で なければなりません: 指数のない正の 10 進数 (整数か 10 進小数) か、 さもなければ先頭に 'v' の文字が付いて、少なくとも三つの部分から 構成されるドット付き 10 進v-文字列です。 $VERSION はパッケージ毎に 1 回だけセットするべきです。

See "Packages" in perlmod for more information about packages, modules, and classes. See perlsub for other scoping issues.

パッケージ、モジュール、クラスに関するさらなる情報については "Packages" in perlmod を参照してください。 その他のスコープに関する話題については perlsub を参照してください。

__PACKAGE__

A special token that returns the name of the package in which it occurs.

これが書いてあるパッケージの名前を返す特殊トークン。

pipe READHANDLE,WRITEHANDLE

Opens a pair of connected pipes like the corresponding system call. Note that if you set up a loop of piped processes, deadlock can occur unless you are very careful. In addition, note that Perl's pipes use IO buffering, so you may need to set $| to flush your WRITEHANDLE after each command, depending on the application.

対応するシステムコールと同じように、接続されたパイプのペアを開きます。 パイプでプロセスをループにするときには、よほど気を付けないと、 デッドロックが起こり得ます。 さらに、Perl のパイプでは、IO のバッファリングを使ので、 アプリケーションによっては、コマンドごとに WRITEHANDLE を フラッシュするように、$| を設定することが 必要になるかもしれません。

Returns true on success.

成功時には真を返します。

これらに関する例については、IPC::Open2, IPC::Open3, "Bidirectional Communication with Another Process" in perlipc を 参照してください。

On systems that support a close-on-exec flag on files, that flag is set on all newly opened file descriptors whose filenos are higher than the current value of $^F (by default 2 for STDERR). See "$^F" in perlvar.

ファイルに対する close-on-exec フラグをサポートしているシステムでは、 新しくオープンされたファイル記述子のうち、 fileno が現在の $^F の値 (デフォルトでは STDERR の 2) よりも大きい ものに対してフラグがセットされます。 "$^F" in perlvar を参照してください。

pop ARRAY
pop

Pops and returns the last value of the array, shortening the array by one element.

配列の最後の値をポップして返し、配列の大きさを 1 だけ小さくします。

Returns the undefined value if the array is empty, although this may also happen at other times. If ARRAY is omitted, pops the @ARGV array in the main program, but the @_ array in subroutines, just like shift.

指定された配列に要素がなければ未定義値が返されますが、 しかしこれは他の場合にも起こり得ます。 ARRAY が省略されると、shift と同様に、メインプログラムでは @ARGV が使われますが、 サブルーチンでは @_ が使われます。

Starting with Perl 5.14, an experimental feature allowed pop to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.

Perl 5.14 から、pop がスカラ式を取ることが出来るという 実験的機能がありました。 この実験は失敗と見なされ、Perl 5.24 で削除されました。

pos SCALAR
pos

Returns the offset of where the last m//g search left off for the variable in question ($_ is used when the variable is not specified). This offset is in characters unless the (no-longer-recommended) use bytes pragma is in effect, in which case the offset is in bytes. Note that 0 is a valid match offset. undef indicates that the search position is reset (usually due to match failure, but can also be because no match has yet been run on the scalar).

対象の変数に対して、前回の m//g が終了した場所の オフセットを返します(変数が指定されなかった場合は $_ が 使われます)。 オフセットは、(もはや勧められない) use bytes プラグマが有効の 場合(この場合はバイト単位です)を除いて、文字単位です。 0 は有効なマッチオフセットであることに注意してください。 undef は検索位置がリセットされることを意味します (通常は マッチ失敗が原因ですが、このスカラ値にまだマッチングが 行われていないためかもしれません)。

pos directly accesses the location used by the regexp engine to store the offset, so assigning to pos will change that offset, and so will also influence the \G zero-width assertion in regular expressions. Both of these effects take place for the next match, so you can't affect the position with pos during the current match, such as in (?{pos() = 5}) or s//pos() = 5/e.

pos は正規表現エンジンがオフセットを保存するために使う場所を 直接アクセスするので、pos への代入はオフセットを変更し、 そのような変更は正規表現における \G ゼロ幅アサートにも影響を与えます。 これらの効果の両方は次のマッチングのために行われるので、 (?{pos() = 5})s//pos() = 5/e のように現在のマッチング中の pos の位置には影響を与えません。

Setting pos also resets the matched with zero-length flag, described under "Repeated Patterns Matching a Zero-length Substring" in perlre.

pos を設定すると、 "Repeated Patterns Matching a Zero-length Substring" in perlre に 記述されている、長さ 0 でマッチング フラグもリセットされます。

Because a failed m//gc match doesn't reset the offset, the return from pos won't change either in this case. See perlre and perlop.

m//gc マッチに失敗してもオフセットはリセットしないので、 pos からの返り値はどちらの場合も変更されません。 perlreperlop を参照してください。

print FILEHANDLE LIST
print FILEHANDLE
print LIST
print

Prints a string or a list of strings. Returns true if successful. FILEHANDLE may be a scalar variable containing the name of or a reference to the filehandle, thus introducing one level of indirection. (NOTE: If FILEHANDLE is a variable and the next token is a term, it may be misinterpreted as an operator unless you interpose a + or put parentheses around the arguments.) If FILEHANDLE is omitted, prints to the last selected (see select) output handle. If LIST is omitted, prints $_ to the currently selected output handle. To use FILEHANDLE alone to print the content of $_ to it, you must use a bareword filehandle like FH, not an indirect one like $fh. To set the default output handle to something other than STDOUT, use the select operation.

文字列か文字列のリストを出力します。 成功時には真を返します。 FILEHANDLE は、ファイルハンドル名またはそのリファレンスが 入っているスカラ変数名でもよいので、一段階の間接指定が行なえます。 (注: FILEHANDLE に変数を使い、次のトークンが「項」のときには、 間に + を置くか、引数の前後を括弧で括らなければ、 誤って解釈されることがあります。) FILEHANDLE を省略した場合には、最後に選択された (select 参照) 出力チャネルに出力します。 LIST を省略すると、$_ が現在選択されている出力ハンドルに 出力されます。 $_ の内容を表示するために FILEHANDLE のみを使用するには、 $fh のような間接ファイルハンドルではなく、FH のような裸の単語の ファイルハンドルを使わなければなりません。 デフォルトの出力チャネルを STDOUT 以外にするには、select 演算子を 使ってください。

The current value of $, (if any) is printed between each LIST item. The current value of $\ (if any) is printed after the entire LIST has been printed. Because print takes a LIST, anything in the LIST is evaluated in list context, including any subroutines whose return lists you pass to print. Be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print; put parentheses around all arguments (or interpose a +, but that doesn't look as good).

$, の値が(もしあれば)各 LIST 要素の間に出力されます。 LIST 全体が出力された後、(もしあれば) $\ の現在の値が 出力されます。 print の引数は LIST なので、LIST の中のものは、すべてリストコンテキストで 評価されます; print に渡した、リストを返す サブルーチンも含みます。 また、すべての引数を括弧で括るのでなければ、print というキーワードの 次に開き括弧を書いてはいけません; すべての引数を括弧で括ってください (あるいは "print" と引数の間に + を書きますが、これはあまり よくありません)。

If you're storing handles in an array or hash, or in general whenever you're using any expression more complex than a bareword handle or a plain, unsubscripted scalar variable to retrieve it, you will have to use a block returning the filehandle value instead, in which case the LIST may not be omitted:

もし FILESHANDLE を配列、ハッシュあるいは一般的には裸の単語のハンドルや 普通のスカラ変数よりも複雑な表現を使っている場合、代わりにその値を返す ブロックを使う必要があります; この場合 LIST は省略できません:

    print { $files[$i] } "stuff\n";
    print { $OK ? *STDOUT : *STDERR } "stuff\n";

Printing to a closed pipe or socket will generate a SIGPIPE signal. See perlipc for more on signal handling.

閉じたパイプやソケットに print すると SIGPIPE シグナルが生成されます。 さらなるシグナル操作については perlipc を参照してください。

printf FILEHANDLE FORMAT, LIST
printf FILEHANDLE
printf FORMAT, LIST
printf

Equivalent to print FILEHANDLE sprintf(FORMAT, LIST), except that $\ (the output record separator) is not appended. The FORMAT and the LIST are actually parsed as a single list. The first argument of the list will be interpreted as the printf format. This means that printf(@_) will use $_[0] as the format. See sprintf for an explanation of the format argument. If use locale (including use locale ':not_characters') is in effect and POSIX::setlocale has been called, the character used for the decimal separator in formatted floating-point numbers is affected by the LC_NUMERIC locale setting. See perllocale and POSIX.

$\(出力レコードセパレータ)を追加しないことを除けば、 print FILEHANDLE sprintf(FORMAT, LIST) と等価です。 FORMAT と LIST は実際には単一のリストとしてパースされます。 リストの最初の要素は、printf フォーマットと解釈されます。 これは、printf(@_) はフォーマットとして $_[0] を使うということです。 フォーマット引数の説明については sprintf を 参照してください。 (use locale ':not_characters' を含む) use locale が有効で、 POSIX::setlocale が呼び出されていれば、 小数点に使われる文字は LC_NUMERIC ロケール設定の影響を受けます。 perllocalePOSIX を参照してください。

For historical reasons, if you omit the list, $_ is used as the format; to use FILEHANDLE without a list, you must use a bareword filehandle like FH, not an indirect one like $fh. However, this will rarely do what you want; if $_ contains formatting codes, they will be replaced with the empty string and a warning will be emitted if warnings are enabled. Just use print if you want to print the contents of $_.

歴史的な理由により、リストを省略すると、フォーマットとして $_ が使われます; リストなしで FILEHANDLE を使用するには、$fh のような 間接ファイルハンドルではなく、FH のような裸の単語の ファイルハンドルを使わなければなりません。 しかし、これがあなたが求めていることをすることはまれです; $_ がフォーマッティングコードの場合、空文字列に置き換えられ、 warnings が有効なら警告が出力されます。 $_ の内容を表示したい場合は、単に print を使ってください。

Don't fall into the trap of using a printf when a simple print would do. The print is more efficient and less error prone.

単純な print を使うべきところで printf を使ってしまう 罠にかからないようにしてください。 print はより効率的で、間違いが起こりにくいです。

prototype FUNCTION
prototype

Returns the prototype of a function as a string (or undef if the function has no prototype). FUNCTION is a reference to, or the name of, the function whose prototype you want to retrieve. If FUNCTION is omitted, $_ is used.

関数のプロトタイプを文字列として返します(関数にプロトタイプがない場合は undef を返します)。 FUNCTION はプロトタイプを得たい関数の名前、またはリファレンスです。 FUNCTION が省略された場合、$_ が使われます。

If FUNCTION is a string starting with CORE::, the rest is taken as a name for a Perl builtin. If the builtin's arguments cannot be adequately expressed by a prototype (such as system), prototype returns undef, because the builtin does not really behave like a Perl function. Otherwise, the string describing the equivalent prototype is returned.

FUNCTION が CORE:: で始まっている場合、残りは Perl ビルドインの名前として 扱われます。 このビルドインの引数が(system のように)プロトタイプとして 適切に記述できない場合、prototypeundef を返します; なぜならビルドインは実際に Perl 関数のように振舞わないからです。 それ以外では、等価なプロトタイプを表現した文字列が返されます。

push ARRAY,LIST

Treats ARRAY as a stack by appending the values of LIST to the end of ARRAY. The length of ARRAY increases by the length of LIST. Has the same effect as

ARRAY をスタックとして扱い、LIST 内の値を ARRAY の終わりに追加します。 ARRAY の大きさは、LIST の長さ分だけ大きくなります。 これは、

    for my $value (LIST) {
        $ARRAY[++$#ARRAY] = $value;
    }

but is more efficient. Returns the number of elements in the array following the completed push.

とするのと同じ効果がありますが、より効率的です。 push の処理終了後の配列の要素数を返します。

Starting with Perl 5.14, an experimental feature allowed push to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.

Perl 5.14 から、push がスカラ式を取ることが出来るという 実験的機能がありました。 この実験は失敗と見なされ、Perl 5.24 で削除されました。

q/STRING/
qq/STRING/
qw/STRING/
qx/STRING/

Generalized quotes. See "Quote-Like Operators" in perlop.

汎用のクォートです。 "Quote-Like Operators" in perlop を参照してください。

qr/STRING/

Regexp-like quote. See "Regexp Quote-Like Operators" in perlop.

正規表現風のクォートです。 "Regexp Quote-Like Operators" in perlop を参照してください。

quotemeta EXPR
quotemeta

Returns the value of EXPR with all the ASCII non-"word" characters backslashed. (That is, all ASCII characters not matching /[A-Za-z_0-9]/ will be preceded by a backslash in the returned string, regardless of any locale settings.) This is the internal function implementing the \Q escape in double-quoted strings. (See below for the behavior on non-ASCII code points.)

EXPR の中のすべての ASCII 非英数字キャラクタをバックスラッシュで エスケープしたものを返します。 (つまり、/[A-Za-z_0-9]/ にマッチしない全ての ASCII 文字の前には ロケールに関わらずバックスラッシュが前置されます。) これは、ダブルクォート文字列での \Q エスケープを実装するための 内部関数です。 (非 ASCII 符号位置での振る舞いについては以下を参照してください。)

If EXPR is omitted, uses $_.

EXPR が省略されると、$_ を使います。

quotemeta (and \Q ... \E) are useful when interpolating strings into regular expressions, because by default an interpolated variable will be considered a mini-regular expression. For example:

クォートメタ (と \Q ... \E) は、文字列を正規表現に展開するのに 便利です; なぜなら、デフォルトでは展開された変数は小さな正規表現として 扱われるからです。 例えば:

    my $sentence = 'The quick brown fox jumped over the lazy dog';
    my $substring = 'quick.*?fox';
    $sentence =~ s{$substring}{big bad wolf};

Will cause $sentence to become 'The big bad wolf jumped over...'.

とすると、$sentence'The big bad wolf jumped over...' になります。

On the other hand:

一方:

    my $sentence = 'The quick brown fox jumped over the lazy dog';
    my $substring = 'quick.*?fox';
    $sentence =~ s{\Q$substring\E}{big bad wolf};

Or:

あるいは:

    my $sentence = 'The quick brown fox jumped over the lazy dog';
    my $substring = 'quick.*?fox';
    my $quoted_substring = quotemeta($substring);
    $sentence =~ s{$quoted_substring}{big bad wolf};

Will both leave the sentence as is. Normally, when accepting literal string input from the user, quotemeta or \Q must be used.

とすると、両方ともそのままです。 普通は、ユーザーからのリテラルな文字列入力を受け付ける場合は、 必ず quotemeta\Q を使わなければなりません。

In Perl v5.14, all non-ASCII characters are quoted in non-UTF-8-encoded strings, but not quoted in UTF-8 strings.

Perl v5.14 では、全ての非 ASCII 文字は非 UTF-8 エンコードされた 文字列ではクォートされませんが、UTF-8 文字列ではクォートされます。

Starting in Perl v5.16, Perl adopted a Unicode-defined strategy for quoting non-ASCII characters; the quoting of ASCII characters is unchanged.

Perl v5.16 から、Perl は非 ASCII 文字をクォートするのに Unicode で 定義された戦略を採用しました; ASCII 文字のクォートは変わりません。

Also unchanged is the quoting of non-UTF-8 strings when outside the scope of a use feature 'unicode_strings', which is to quote all characters in the upper Latin1 range. This provides complete backwards compatibility for old programs which do not use Unicode. (Note that unicode_strings is automatically enabled within the scope of a use v5.12 or greater.)

また、 use feature 'unicode_strings' の 範囲外で非 UTF-8 文字列をクォートするのも変わりません; 上位の Latin1 の範囲の 全ての文字をクォートします。 これは Unicode を使わない古いプログラムに対して完全な後方互換性を提供します。 (unicode_stringsuse v5.12 またはそれ以上のスコープでは 自動的に有効になることに注意してください。)

Within the scope of use locale, all non-ASCII Latin1 code points are quoted whether the string is encoded as UTF-8 or not. As mentioned above, locale does not affect the quoting of ASCII-range characters. This protects against those locales where characters such as "|" are considered to be word characters.

use locale スコープの内側では、全ての非 ASCII Latin1 符号位置は 文字列が UTF-8 でエンコードされているかどうかに関わらずクォートされます。 上述のように、ロケールは ASCII の範囲の文字のクォートに影響を与えません。 これは "|" のような文字が単語文字として考えられるロケールから守ります。

Otherwise, Perl quotes non-ASCII characters using an adaptation from Unicode (see http://www.unicode.org/reports/tr31/). The only code points that are quoted are those that have any of the Unicode properties: Pattern_Syntax, Pattern_White_Space, White_Space, Default_Ignorable_Code_Point, or General_Category=Control.

さもなければ、Perl は Unicode からの本版を使って非 ASCII 文字をクォートします (http://www.unicode.org/reports/tr31/ 参照)。 クォートされる符号位置は以下のどれかの Unicode を特性を持つものだけです: Pattern_Syntax, Pattern_White_Space, White_Space, Default_Ignorable_Code_Point, or General_Category=Control。

Of these properties, the two important ones are Pattern_Syntax and Pattern_White_Space. They have been set up by Unicode for exactly this purpose of deciding which characters in a regular expression pattern should be quoted. No character that can be in an identifier has these properties.

これらの特性の中で、重要な二つは Pattern_Syntax と Pattern_White_Space です。 これらはまさに正規表現中パターン中のどの文字をクォートするべきかを 決定するという目的のために Unicode によって設定されています。 識別子になる文字はこれらの特性はありません。

Perl promises, that if we ever add regular expression pattern metacharacters to the dozen already defined (\ | ( ) [ { ^ $ * + ? .), that we will only use ones that have the Pattern_Syntax property. Perl also promises, that if we ever add characters that are considered to be white space in regular expressions (currently mostly affected by /x), they will all have the Pattern_White_Space property.

Perl は、正規表現メタ文字として既に定義されている (\ | ( ) [ { ^ $ * + ? .) ものに追加するときは、 Pattern_Syntax 特性を持つものだけを使うことを約束します。 Perl はまた、(現在の所ほとんどは /x よって影響される)正規表現中で空白と 考えられる文字に追加するときは、Pattern_White_Space 特性を 持つものであることを約束します。

Unicode promises that the set of code points that have these two properties will never change, so something that is not quoted in v5.16 will never need to be quoted in any future Perl release. (Not all the code points that match Pattern_Syntax have actually had characters assigned to them; so there is room to grow, but they are quoted whether assigned or not. Perl, of course, would never use an unassigned code point as an actual metacharacter.)

Unicode はこれら二つの特性を持つ符号位置の集合が決して変わらないことを 約束しているので、v5.16 でクォートされないものは将来の Perl リリースでも クォートする必要はありません。 (Pattern_Syntax にマッチングする全ての符号位置が実際に割り当てられている 文字を持っているわけではありません; したがって拡張する余地がありますが、 割り当てられているかどうかに関わらずクォートされます。 Perl はもちろん割り当てられていない符号位置を実際のメタ文字として使うことは ありません。)

Quoting characters that have the other 3 properties is done to enhance the readability of the regular expression and not because they actually need to be quoted for regular expression purposes (characters with the White_Space property are likely to be indistinguishable on the page or screen from those with the Pattern_White_Space property; and the other two properties contain non-printing characters).

その他の 3 特性を持つ文字のクォートは正規表現の可読性を向上させるために 行われ、実際には正規表現の目的でクォートする必要があるからではありません (White_Space 特性を持つ文字は表示上は Pattern_White_Space 特性を持つ文字と おそらく区別が付かないでしょう; そして残りの 二つの特性は非表示文字を含んでいます).

rand EXPR
rand

Returns a random fractional number greater than or equal to 0 and less than the value of EXPR. (EXPR should be positive.) If EXPR is omitted, the value 1 is used. Currently EXPR with the value 0 is also special-cased as 1 (this was undocumented before Perl 5.8.0 and is subject to change in future versions of Perl). Automatically calls srand unless srand has already been called. See also srand.

0 以上 EXPR の値未満の小数の乱数値を返します。 (EXPR は正の数である必要があります。) EXPR が省略されると、1 が使われます。 現在のところ、EXPR に値 0 をセットすると 1 として特別扱いされます (これは Perl 5.8.0 以前には文書化されておらず、将来のバージョンの perl では 変更される可能性があります)。 srand が既に呼ばれている場合以外は、自動的に srand 関数を呼び出します。 srand も参照してください。

Apply int to the value returned by rand if you want random integers instead of random fractional numbers. For example,

ランダムな小数ではなく、ランダムな整数がほしい場合は、 rand から返された値に int を 適用してください。 例えば:

    int(rand(10))

returns a random integer between 0 and 9, inclusive.

これは 0 から 9 の値をランダムに返します。

(Note: If your rand function consistently returns numbers that are too large or too small, then your version of Perl was probably compiled with the wrong number of RANDBITS.)

(注: もし、rand 関数が、常に大きい値ばかりや、小さい数ばかりを 返すようなら、お使いになっている Perl が、 良くない RANDBITS を使ってコンパイルされている可能性があります。)

rand is not cryptographically secure. You should not rely on it in security-sensitive situations. As of this writing, a number of third-party CPAN modules offer random number generators intended by their authors to be cryptographically secure, including: Data::Entropy, Crypt::Random, Math::Random::Secure, and Math::TrulyRandom.

rand は暗号学的に安全ではありません。 セキュリティ的に重要な状況でこれに頼るべきではありません。 これを書いている時点で、いくつかのサードパーティ CPAN モジュールが 作者によって暗号学的に安全であることを目的とした乱数生成器を 提供しています: Data::Entropy, Crypt::Random, Math::Random::Secure, Math::TrulyRandom などです。

read FILEHANDLE,SCALAR,LENGTH,OFFSET
read FILEHANDLE,SCALAR,LENGTH

Attempts to read LENGTH characters of data into variable SCALAR from the specified FILEHANDLE. Returns the number of characters actually read, 0 at end of file, or undef if there was an error (in the latter case $! is also set). SCALAR will be grown or shrunk so that the last character actually read is the last character of the scalar after the read.

指定した FILEHANDLE から、変数 SCALAR に LENGTH 文字 のデータを 読み込みます。 実際に読み込まれた文字数、ファイル終端の場合は 0、エラーの場合は undef の いずれかを返します (後者の場合、$! もセットされます)。 SCALAR は伸び縮みするので、読み込み後は、実際に読み込んだ最後の文字がスカラの 最後の文字になります。

An OFFSET may be specified to place the read data at some place in the string other than the beginning. A negative OFFSET specifies placement at that many characters counting backwards from the end of the string. A positive OFFSET greater than the length of SCALAR results in the string being padded to the required size with "\0" bytes before the result of the read is appended.

OFFSET を指定すると、文字列の先頭以外の場所から読み込みを行なえます。 OFFSET に負の値を指定すると、文字列の最後から逆向きに何文字目かで 位置を指定します。 OFFSET が正の値で、SCALAR の長さよりも大きかった場合、文字列は読み込みの結果が 追加される前に、必要なサイズまで "\0" のバイトでパッディングされます。

The call is implemented in terms of either Perl's or your system's native fread(3) library function. To get a true read(2) system call, see sysread.

この関数は、Perl か システムの fread(3) ライブラリ関数を使って 実装しています。 本当の read(2) システムコールを利用するには、 sysread を参照してください。

Note the characters: depending on the status of the filehandle, either (8-bit) bytes or characters are read. By default, all filehandles operate on bytes, but for example if the filehandle has been opened with the :utf8 I/O layer (see open, and the open pragma), the I/O will operate on UTF8-encoded Unicode characters, not bytes. Similarly for the :encoding layer: in that case pretty much any characters can be read.

文字 に関する注意: ファイルハンドルの状態によって、(8 ビットの) バイトか 文字が読み込まれます。 デフォルトでは全てのファイルハンドルはバイトを処理しますが、 例えばファイルハンドルが :utf8 I/O 層(open, open プラグマを参照してください) で開かれた場合、I/O はバイトではなく、 UTF8 エンコードされた Unicode 文字を操作します。 :encoding 層も同様です: この場合、ほとんど大体全ての文字が読み込めます。

readdir DIRHANDLE

Returns the next directory entry for a directory opened by opendir. If used in list context, returns all the rest of the entries in the directory. If there are no more entries, returns the undefined value in scalar context and the empty list in list context.

opendir でオープンしたディレクトリで、次の ディレクトリエントリを返します。 リストコンテキストで用いると、そのディレクトリの残りのエントリを、すべて 返します。 エントリが残っていない場合には、スカラコンテキストでは未定義値を、 リストコンテキストでは空リストを返します。

If you're planning to filetest the return values out of a readdir, you'd better prepend the directory in question. Otherwise, because we didn't chdir there, it would have been testing the wrong file.

readdir の返り値をファイルテストに使おうと 計画しているなら、頭にディレクトリをつける必要があります。 さもなければ、ここでは chdir はしないので、 間違ったファイルをテストしてしまうことになるでしょう。

    opendir(my $dh, $some_dir) || die "Can't opendir $some_dir: $!";
    my @dots = grep { /^\./ && -f "$some_dir/$_" } readdir($dh);
    closedir $dh;

As of Perl 5.12 you can use a bare readdir in a while loop, which will set $_ on every iteration. If either a readdir expression or an explicit assignment of a readdir expression to a scalar is used as a while/for condition, then the condition actually tests for definedness of the expression's value, not for its regular truth value.

Perl 5.12 から裸の readdirwhile で 使うことができ、この場合繰り返し毎に $_ にセットされます。 readdir 式または readdir 式からスカラへの明示的な代入が while/for の条件部として使われた場合、 条件は通常の真の値かどうかではなく、式の値が定義されているかどうかを テストします。

    opendir(my $dh, $some_dir) || die "Can't open $some_dir: $!";
    while (readdir $dh) {
        print "$some_dir/$_\n";
    }
    closedir $dh;

To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious failures, put this sort of thing at the top of your file to signal that your code will work only on Perls of a recent vintage:

あなたのコードを以前のバージョンの Perl で実行したユーザーが不思議な 失敗で混乱することを避けるために、コードが最近のバージョンの Perl で のみ 動作することを示すためにファイルの先頭に以下のようなことを 書いてください:

    use 5.012; # so readdir assigns to $_ in a lone while test
readline EXPR
readline

Reads from the filehandle whose typeglob is contained in EXPR (or from *ARGV if EXPR is not provided). In scalar context, each call reads and returns the next line until end-of-file is reached, whereupon the subsequent call returns undef. In list context, reads until end-of-file is reached and returns a list of lines. Note that the notion of "line" used here is whatever you may have defined with $/ (or $INPUT_RECORD_SEPARATOR in English). See "$/" in perlvar.

型グロブが EXPR (EXPR がない場合は *ARGV) に含まれている ファイルハンドルから読み込みます。 スカラコンテキストでは、呼び出し毎に一行読み込んで返します; ファイルの 最後まで読み込んだら、以後の呼び出しでは undef を返します。 リストコンテキストでは、ファイルの最後まで読み込んで、行のリストを返します。 ここでの「行」とは、$/ (または English モジュールでは $INPUT_RECORD_SEPARATOR) で 定義されることに注意してください。 "$/" in perlvar を参照してください。

When $/ is set to undef, when readline is in scalar context (i.e., file slurp mode), and when an empty file is read, it returns '' the first time, followed by undef subsequently.

$/undef を設定した場合は、 readline はスカラコンテキスト (つまりファイル吸い込み モード)となり、空のファイルを読み込んだ場合は、最初は '' を返し、 それ以降は undef を返します。

This is the internal function implementing the <EXPR> operator, but you can use it directly. The <EXPR> operator is discussed in more detail in "I/O Operators" in perlop.

これは <EXPR> 演算子を実装している内部関数ですが、 直接使うこともできます。 <EXPR> 演算子についてのさらなる詳細については "I/O Operators" in perlop で議論されています。

    my $line = <STDIN>;
    my $line = readline(STDIN);    # same thing

If readline encounters an operating system error, $! will be set with the corresponding error message. It can be helpful to check $! when you are reading from filehandles you don't trust, such as a tty or a socket. The following example uses the operator form of readline and dies if the result is not defined.

readline が OS のシステムエラーになると、 $! に対応するエラーメッセージがセットされます。 tty やソケットといった、信頼できないファイルハンドルから読み込む時には $! をチェックするのが助けになります。 以下の例は演算子の形の readline を使っており、結果が 未定義の場合は die します。

    while ( ! eof($fh) ) {
        defined( $_ = readline $fh ) or die "readline failed: $!";
        ...
    }

Note that you have can't handle readline errors that way with the ARGV filehandle. In that case, you have to open each element of @ARGV yourself since eof handles ARGV differently.

readline のエラーは ARGV ファイルハンドルの方法では 扱えないことに注意してください。 この場合、eofARGV を異なった方法で扱うので、 @ARGV のそれぞれの要素を自分でオープンする必要があります。

    foreach my $arg (@ARGV) {
        open(my $fh, $arg) or warn "Can't open $arg: $!";

        while ( ! eof($fh) ) {
            defined( $_ = readline $fh )
                or die "readline failed for $arg: $!";
            ...
        }
    }

Like the <EXPR> operator, if a readline expression is used as the condition of a while or for loop, then it will be implicitly assigned to $_. If either a readline expression or an explicit assignment of a readline expression to a scalar is used as a while/for condition, then the condition actually tests for definedness of the expression's value, not for its regular truth value.

<EXPR> 演算子と同様、 readline 式が whilefor ループの条件として使われた場合、 これは暗黙に $_ に代入されます。 readline 式または readline 式からスカラへの明示的な代入が while/for の条件部として使われた場合、 条件は通常の真の値かどうかではなく、式の値が定義されているかどうかを テストします。

readlink EXPR
readlink

Returns the value of a symbolic link, if symbolic links are implemented. If not, raises an exception. If there is a system error, returns the undefined value and sets $! (errno). If EXPR is omitted, uses $_.

シンボリックリンクが実装されていれば、シンボリックリンクの値を返します。 実装されていないときには、例外が発生します。 何らかのシステムエラーが検出されると、未定義値を返し、 $! (errno) を設定します。 EXPR が省略されると、$_ を使います。

Portability issues: "readlink" in perlport.

移植性の問題: "readlink" in perlport

readpipe EXPR
readpipe

EXPR is executed as a system command. The collected standard output of the command is returned. In scalar context, it comes back as a single (potentially multi-line) string. In list context, returns a list of lines (however you've defined lines with $/ (or $INPUT_RECORD_SEPARATOR in English)). This is the internal function implementing the qx/EXPR/ operator, but you can use it directly. The qx/EXPR/ operator is discussed in more detail in "I/O Operators" in perlop. If EXPR is omitted, uses $_.

EXPR がシステムコマンドとして実行されます。 コマンドの標準出力の内容が返されます。 スカラコンテキストでは、単一の(内部的に複数行の)文字列を返します。 リストコンテキストでは、行のリストを返します (但し、行は $/ (または English モジュールでは $INPUT_RECORD_SEPARATOR で定義されます)。 これは qx/EXPR/ 演算子を実装する内部関数ですが、直接使うことも出来ます。 qx/EXPR/ 演算子は "I/O Operators" in perlop でより詳細に述べられています。 EXPR が省略されると、$_ を使います。

recv SOCKET,SCALAR,LENGTH,FLAGS

Receives a message on a socket. Attempts to receive LENGTH characters of data into variable SCALAR from the specified SOCKET filehandle. SCALAR will be grown or shrunk to the length actually read. Takes the same flags as the system call of the same name. Returns the address of the sender if SOCKET's protocol supports this; returns an empty string otherwise. If there's an error, returns the undefined value. This call is actually implemented in terms of the recvfrom(2) system call. See "UDP: Message Passing" in perlipc for examples.

ソケット上のメッセージを受信します。 指定されたファイルハンドル SOCKET から、変数 SCALAR に LENGTH 文字のデータを読み込もうとします。 SCALAR は、実際に読まれた長さによって、大きくなったり、小さくなったりします。 同名のシステムコールと同じフラグが指定できます。 SOCKET のプロトコルが対応していれば、送信側のアドレスを返します。 エラー発生時には、未定義値を返します。 実際には、C の recvfrom(2) を呼びます。 例については "UDP: Message Passing" in perlipc を参照してください。

Note that if the socket has been marked as :utf8, recv will throw an exception. The :encoding(...) layer implicitly introduces the :utf8 layer. See binmode.

ソケットが :utf8 としてマークされている場合、 recv は例外を投げることに注意してください。 :encoding(...) 層は暗黙に :utf8 層を導入します。 binmode を参照してください。

redo LABEL
redo EXPR
redo

The redo command restarts the loop block without evaluating the conditional again. The continue block, if any, is not executed. If the LABEL is omitted, the command refers to the innermost enclosing loop. The redo EXPR form, available starting in Perl 5.18.0, allows a label name to be computed at run time, and is otherwise identical to redo LABEL. Programs that want to lie to themselves about what was just input normally use this command:

redo コマンドは、条件を再評価しないで、ループブロックの 始めからもう一度実行を開始します。 continue ブロックがあっても、実行されません。 LABEL が省略されると、コマンドは一番内側のループを参照します。 Perl 5.18.0 から利用可能な redo EXPR 形式では、実行時に計算されるラベル名が 使えます; それ以外は redo LABEL と同一です。 このコマンドは通常、自分への入力を欺くために使用します:

    # a simpleminded Pascal comment stripper
    # (warning: assumes no { or } in strings)
    LINE: while (<STDIN>) {
        while (s|({.*}.*){.*}|$1 |) {}
        s|{.*}| |;
        if (s|{.*| |) {
            my $front = $_;
            while (<STDIN>) {
                if (/}/) {  # end of comment?
                    s|^|$front\{|;
                    redo LINE;
                }
            }
        }
        print;
    }

redo cannot return a value from a block that typically returns a value, such as eval {}, sub {}, or do {}. It will perform its flow control behavior, which precludes any return value. It should not be used to exit a grep or map operation.

redoeval {}, sub {}, do {} といった 典型的には値を返すブロックから値を返せません。 これは、返り値を不可能にするフロー制御の振る舞いを実行します。 grepmap 操作を終了するのに 使うべきではありません。

Note that a block by itself is semantically identical to a loop that executes once. Thus redo inside such a block will effectively turn it into a looping construct.

ブロック自身は一回だけ実行されるループと文法的に同一であることに 注意してください。 従って、ブロックの中で redo を使うことで効果的に ループ構造に変換します。

See also continue for an illustration of how last, next, and redo work.

last, next, redo が どのように働くかについては continue も参照してください。

Unlike most named operators, this has the same precedence as assignment. It is also exempt from the looks-like-a-function rule, so redo ("foo")."bar" will cause "bar" to be part of the argument to redo.

ほとんどの名前付き演算子と異なり、これは代入と同じ優先順位を持ちます。 また、関数のように見えるものの規則からも免れるので、redo ("foo")."bar" と すると "bar" は redo への引数の一部となります。

ref EXPR
ref

Examines the value of EXPR, expecting it to be a reference, and returns a string giving information about the reference and the type of referent. If EXPR is not specified, $_ will be used.

Examines the value of リファレンスと想定される EXPR の値を調べて、 そのリファレンスとリファレンス先の型に関する情報を表す 文字列を返します。 EXPR が指定されていない場合、$_ が使われます。

If the operand is not a reference, then the empty string will be returned. An empty string will only be returned in this situation. ref is often useful to just test whether a value is a reference, which can be done by comparing the result to the empty string. It is a common mistake to use the result of ref directly as a truth value: this goes wrong because 0 (which is false) can be returned for a reference.

オペランドがリファレンスでない場合、空文字列が返されます。 空文字列はこの場合にのみ返されます。 結果を空文字列を比較することでできるので、 ref は単にある値がリファレンスかどうかを調べるのにしばしば有用です。 ref の結果を直接真の値として使うのは良くある誤りです: リファレンスの場合に (偽である) 0 が返されることがあるので、 これは誤りです。

If the operand is a reference to a blessed object, then the name of the class into which the referent is blessed will be returned. ref doesn't care what the physical type of the referent is; blessing takes precedence over such concerns. Beware that exact comparison of ref results against a class name doesn't perform a class membership test: a class's members also include objects blessed into subclasses, for which ref will return the name of the subclass. Also beware that class names can clash with the built-in type names (described below).

オペランドが bless されたオブジェクトへのリファレンスの場合、 リファレンス先が bless されているクラス名が返されます。 ref はリファレンス先の物理的な種類については気にしません; bless されているかがそのような関心より優先されます。 ref の結果とクラス名の正確な比較は、クラスの所属のテストを 実行しないことに注意してください: ref がサブクラスの名前を返す場合、 あるクラスのメンバはサブクラスに bless されているオブジェクトを 含んでいます。 クラス名は(後述する)組み込みの型名と衝突することにも注意してください。

If the operand is a reference to an unblessed object, then the return value indicates the type of object. If the unblessed referent is not a scalar, then the return value will be one of the strings ARRAY, HASH, CODE, FORMAT, or IO, indicating only which kind of object it is. If the unblessed referent is a scalar, then the return value will be one of the strings SCALAR, VSTRING, REF, GLOB, LVALUE, or REGEXP, depending on the kind of value the scalar currently has. But note that qr// scalars are created already blessed, so ref qr/.../ will likely return Regexp. Beware that these built-in type names can also be used as class names, so ref returning one of these names doesn't unambiguously indicate that the referent is of the kind to which the name refers.

オペランドが bless されていないオブジェクトへのリファレンスの場合、 返り値はオブジェクトの型を示します。 bless されていないリファレンス先がスカラではない場合、 返り値はオブジェクトの種類を示す、 ARRAY, HASH, CODE, FORMAT, IO のいずれかの文字列です。 bless されていないリファレンス先がスカラの場合、 返り値はそのスカラが現在保持している種類に依存して、 SCALAR, VSTRING, REF, GLOB, LVALUE, REGEXP の いずれかの文字列です。 しかし、qr// は既に bless されて作成されるので、 ref qr/.../ はおそらく Regexp を返すことに注意してください。 これらの組み込み型名はまたクラス名として使われることができるので、 ref がこれらの名前の一つを返すことは、 明らかにリファレンス先がその名前が示している種類のものであることを 示しているわけではないことに注意してください。

The ambiguity between built-in type names and class names significantly limits the utility of ref. For unambiguous information, use Scalar::Util::blessed() for information about blessing, and Scalar::Util::reftype() for information about physical types. Use the isa method for class membership tests, though one must be sure of blessedness before attempting a method call.

組み込み型とクラス名の間の曖昧さは ref の有用性を大きく制限しています。 曖昧でない情報のためには、bless に関する情報については Scalar::Util::blessed() を、 物理的な型の情報については Scalar::Util::reftype() を使ってください。 クラスの所属メンバテストには the isa method を使ってください; 但し、メソッド呼び出しを試みる前に bless されていることを 確認しなければなりません。

See also perlref and perlobj.

perlrefperlobj も参照してください。

rename OLDNAME,NEWNAME

Changes the name of a file; an existing file NEWNAME will be clobbered. Returns true for success, false otherwise.

ファイルの名前を変更します; NEWNAME というファイルが既に存在した場合、 上書きされるかもしれません。 成功時には真を、さもなければ偽を返します。

Behavior of this function varies wildly depending on your system implementation. For example, it will usually not work across file system boundaries, even though the system mv command sometimes compensates for this. Other restrictions include whether it works on directories, open files, or pre-existing files. Check perlport and either the rename(2) manpage or equivalent system documentation for details.

この関数の振る舞いはシステムの実装に大きく依存して異なります。 例えば、普通はファイルシステムにまたがってパス名を付け替えることはできません; システムの mv がこれを補完している場合でもそうです。 その他の制限には、ディレクトリ、オープンしているファイル、既に存在している ファイルに対して使えるか、といったことを含みます。 詳しくは、perlport および rename(2) man ページあるいは同様の システムドキュメントを参照してください。

For a platform independent move function look at the File::Copy module.

プラットフォームに依存しない move 関数については File::Copy モジュールを参照してください。

Portability issues: "rename" in perlport.

移植性の問題: "rename" in perlport

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";
        }

        foreach $prefix (@INC) {
            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 回読み込まれることはないことに注意してください。

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.

初期化コードの実行がうまくいったことを示すために、ファイルは真を 返さなければならないので、真を返すようになっている自信がある場合を除いては、 ファイルの最後に 1; と書くのが習慣です。 しかし、実行文を追加するような場合に備えて、1; と書いておいた方が良いです。

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 code directly into the @INC array. There are three forms of hooks: subroutine references, array references, and blessed objects.

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

Subroutine references are the simplest case. When the inclusion system walks through @INC and encounters a subroutine, this subroutine gets 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 を走査してサブルーチンに 出会った場合、このサブルーチンは二つの引数と共に呼び出されます; 一つ目は自身へのリファレンス、二つ目はインクルードされるファイル名 (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] として渡されます。

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 array reference, its first element must be a subroutine reference. This subroutine is called as above, but the first parameter is the array reference. This lets you indirectly pass arguments to the subroutine.

フックが配列のリファレンスの場合、その最初の要素はサブルーチンへの リファレンスでなければなりません。 このサブルーチンは上述のように呼び出されますが、その最初の引数は 配列のリファレンスです。 これによって、間接的にサブルーチンに引数を渡すことが出来ます。

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;
        ...
    }

If the hook is an object, it must provide an INC method that will be called as above, the first parameter being the object itself. (Note that you must fully qualify the sub's name, as unqualified INC is always forced into package main.) Here is a typical code layout:

フックがオブジェクトの場合、INC メソッドを提供している必要があります; それが、最初の引数をオブジェクト自身として上述のように呼び出されます。 (修飾されていない INC は常にパッケージ main に強制されるため、 サブルーチン名は完全修飾する必要があることに注意してください。) 以下は典型的なコードレイアウトです:

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

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

These hooks are also permitted to set the %INC entry corresponding to the files they have loaded. See "%INC" in perlvar.

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

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

より強力な import 機能については、このドキュメントの use の項と、perlmod を参照してください。

reset EXPR
reset

Generally used in a continue block at the end of a loop to clear variables and reset m?pattern? searches so that they work again. The expression is interpreted as a list of single characters (hyphens allowed for ranges). All variables (scalars, arrays, and hashes) in the current package beginning with one of those letters are reset to their pristine state. If the expression is omitted, one-match searches (m?pattern?) are reset to match again. Only resets variables or searches in the current package. Always returns 1. Examples:

通常、ループの最後に、変数をクリアし、m?pattern? 検索を再び動作するように リセットするため、continue ブロックで使われます。 EXPR は、文字を並べたもの (範囲を指定するのに、ハイフンが使えます) と 解釈されます。 名前がその文字のいずれかで始まる、現在のパッケージの全ての変数 (スカラ、配列、ハッシュ)は、 最初の状態にリセットされます。 EXPR を省略すると、1 回検索 (m?pattern?) を再びマッチするように リセットできます。 カレントパッケージの変数もしくは検索だけがリセットされます。 常に 1 を返します。 例:

    reset 'X';      # reset all X variables
    reset 'a-z';    # reset lower case variables
    reset;          # just reset m?one-time? searches

Resetting "A-Z" is not recommended because you'll wipe out your @ARGV and @INC arrays and your %ENV hash.

reset "A-Z" とすると、@ARGV, @INC 配列や %ENV ハッシュも なくなってしまうので、止めた方が良いでしょう。

Resets only package variables; lexical variables are unaffected, but they clean themselves up on scope exit anyway, so you'll probably want to use them instead. See my.

パッケージ変数だけがリセットされます; レキシカル変数は影響を受けませんが、 スコープから外れれば自動的に綺麗になるので、これからはこちらを 使うようにした方がよいでしょう。 my を参照してください。

return EXPR
return

Returns from a subroutine, eval, do FILE, sort block or regex eval block (but not a grep or map block) with the value given in EXPR. Evaluation of EXPR may be in list, scalar, or void context, depending on how the return value will be used, and the context may vary from one execution to the next (see wantarray). If no EXPR is given, returns an empty list in list context, the undefined value in scalar context, and (of course) nothing at all in void context.

サブルーチン, eval, do FILE, sort ブロックまたは正規表現 eval ブロック (但し grepmap ブロックではない) から EXPR で与えられた値をもって、リターンします。 EXPR の評価は、返り値がどのように使われるかによってリスト、スカラ、 無効コンテキストになります; またコンテキストは実行毎に変わります (wantarray を参照してください)。 EXPR が指定されなかった場合は、リストコンテキストでは空リストを、 スカラコンテキストでは未定義値を返します; そして(もちろん) 無効コンテキストでは何も返しません。

(In the absence of an explicit return, a subroutine, eval, or do FILE automatically returns the value of the last expression evaluated.)

(サブルーチン, eval, do FILE に明示的に return がなければ、最後に評価された値で、 自動的にリターンします。)

Unlike most named operators, this is also exempt from the looks-like-a-function rule, so return ("foo")."bar" will cause "bar" to be part of the argument to return.

ほとんどの名前付き演算子と異なり、関数のように見えるものの規則からも 免れるので、return ("foo")."bar" とすると "bar"return への引数の一部となります。

reverse LIST

In list context, returns a list value consisting of the elements of LIST in the opposite order. In scalar context, concatenates the elements of LIST and returns a string value with all characters in the opposite order.

リストコンテキストでは、LIST を構成する要素を逆順に並べた リスト値を返します。 スカラコンテキストでは、LIST の要素を連結して、 全ての文字を逆順にした文字列を返します。

    print join(", ", reverse "world", "Hello"); # Hello, world

    print scalar reverse "dlrow ,", "olleH";    # Hello, world

Used without arguments in scalar context, reverse reverses $_.

スカラコンテキストで引数なしで使うと、reverse$_ を逆順にします。

    $_ = "dlrow ,olleH";
    print reverse;                         # No output, list context
    print scalar reverse;                  # Hello, world

Note that reversing an array to itself (as in @a = reverse @a) will preserve non-existent elements whenever possible; i.e., for non-magical arrays or for tied arrays with EXISTS and DELETE methods.

(@a = reverse @a のように) 反転した配列を自分自身に代入すると、 存在しない要素は可能なら(つまりマジカルでない配列や EXISTSDELETE メソッドがある tie された配列) いつでも保存されることに注意してください。

This operator is also handy for inverting a hash, although there are some caveats. If a value is duplicated in the original hash, only one of those can be represented as a key in the inverted hash. Also, this has to unwind one hash and build a whole new one, which may take some time on a large hash, such as from a DBM file.

この演算子はハッシュの逆順にするのにも便利ですが、いくつかの弱点があります。 元のハッシュで値が重複していると、それらのうち一つだけが 逆順になったハッシュのキーとして表現されます。 また、これは一つのハッシュをほどいて完全に新しいハッシュを作るので、 DBM ファイルからのような大きなハッシュでは少し時間がかかります。

    my %by_name = reverse %by_address;  # Invert the hash
rewinddir DIRHANDLE

Sets the current position to the beginning of the directory for the readdir routine on DIRHANDLE.

DIRHANDLE に対する readdir ルーチンの現在位置を ディレクトリの最初に設定します。

Portability issues: "rewinddir" in perlport.

移植性の問題: "rewinddir" in perlport

rindex STR,SUBSTR,POSITION
rindex STR,SUBSTR

Works just like index except that it returns the position of the last occurrence of SUBSTR in STR. If POSITION is specified, returns the last occurrence beginning at or before that position.

STR 中で 最後に 見つかった SUBSTR の位置を返すことを除いて、 index と同じように動作します。 POSITION を指定すると、その位置から始まるか、その位置より前の、 最後の位置を返します。

rmdir FILENAME
rmdir

Deletes the directory specified by FILENAME if that directory is empty. If it succeeds it returns true; otherwise it returns false and sets $! (errno). If FILENAME is omitted, uses $_.

FILENAME で指定したディレクトリが空であれば、 そのディレクトリを削除します。 成功時には真を返します; さもなければ偽を返して $! (errno) を 設定します。 FILENAME を省略した場合には、$_ を使用します。

To remove a directory tree recursively (rm -rf on Unix) look at the rmtree function of the File::Path module.

ディレクトリツリーを再帰的に削除したい (Unix での rm -rf) 場合、 File::Path モジュールの rmtree 関数を 参照してください。

s///

The substitution operator. See "Regexp Quote-Like Operators" in perlop.

置換演算子。 "Regexp Quote-Like Operators" in perlop を参照してください。

say FILEHANDLE LIST
say FILEHANDLE
say LIST
say

Just like print, but implicitly appends a newline. say LIST is simply an abbreviation for { local $\ = "\n"; print LIST }. To use FILEHANDLE without a LIST to print the contents of $_ to it, you must use a bareword filehandle like FH, not an indirect one like $fh.

print と同様ですが、暗黙に改行が追加されます。 say LIST は単に { local $\ = "\n"; print LIST } の省略形です。 $_ の内容を表示するために LIST なしで FILEHANDLE を 使用するには、$fh のような間接ファイルハンドルではなく、FH のような 裸の単語のファイルハンドルを使わなければなりません。

say is available only if the "say" feature is enabled or if it is prefixed with CORE::. The "say" feature is enabled automatically with a use v5.10 (or higher) declaration in the current scope.

say"say" 機能 が有効か CORE:: が 前置されたときにのみ利用可能です。 "say" 機能 は現在のスコープで use v5.10 (またはそれ以上) が宣言されると自動的に有効になります。

scalar EXPR

Forces EXPR to be interpreted in scalar context and returns the value of EXPR.

EXPR を強制的にスカラコンテキストで解釈されるようにして、 EXPR の値を返します。

    my @counts = ( scalar @a, scalar @b, scalar @c );

There is no equivalent operator to force an expression to be interpolated in list context because in practice, this is never needed. If you really wanted to do so, however, you could use the construction @{[ (some expression) ]}, but usually a simple (some expression) suffices.

式を強制的にリストコンテキストで解釈させるようにする演算子はありません; 理論的には不要だからです。 それでも、もしそうしたいのなら、@{[ (some expression) ]} という構造を 使えます; しかし、普通は単に (some expression) とすれば十分です。

Because scalar is a unary operator, if you accidentally use a parenthesized list for the EXPR, this behaves as a scalar comma expression, evaluating all but the last element in void context and returning the final element evaluated in scalar context. This is seldom what you want.

scalar は単項演算子なので、EXPR として括弧でくくった リストを使った場合、これはスカラカンマ表現として振舞い、最後以外の全ては 無効コンテキストとして扱われ、最後の要素をスカラコンテキストとして扱った 結果が返されます。 これがあなたの望むものであることはめったにないでしょう。

The following single statement:

以下の一つの文は:

    print uc(scalar(foo(), $bar)), $baz;

is the moral equivalent of these two:

以下の二つの文と等価です。

    foo();
    print(uc($bar), $baz);

See perlop for more details on unary operators and the comma operator, and perldata for details on evaluating a hash in scalar contex.

単項演算子とカンマ演算子に関する詳細については perlop を、 スカラコンテキストでのハッシュの評価に関する詳細については perldata を 参照してください。

seek FILEHANDLE,POSITION,WHENCE

Sets FILEHANDLE's position, just like the fseek(3) call of C stdio. FILEHANDLE may be an expression whose value gives the name of the filehandle. The values for WHENCE are 0 to set the new position in bytes to POSITION; 1 to set it to the current position plus POSITION; and 2 to set it to EOF plus POSITION, typically negative. For WHENCE you may use the constants SEEK_SET, SEEK_CUR, and SEEK_END (start of the file, current position, end of the file) from the Fcntl module. Returns 1 on success, false otherwise.

C の stdio ライブラリの fseek(3) 関数のように、FILEHANDLE の ファイルポインタを任意の位置に設定します。 FILEHANDLE は、実際のファイルハンドル名を与える式でもかまいません。 WHENCE の値が、0 ならば、新しい位置を バイト単位で POSITION の位置へ 設定します; 1 ならば、現在位置から POSITION 加えた位置へ 設定します; 2 ならば、EOF からPOSITION だけ加えた位置へ、新しい位置を 設定します。 この値には、Fcntl モジュールで使われている SEEK_SETSEEK_CURSEEK_END (ファイルの先頭、現在位置、ファイルの最後)という定数を 使うこともできます。 成功時には、1 を、失敗時にはそれ以外を返します。

Note the emphasis on bytes: even if the filehandle has been set to operate on characters (for example using the :encoding(UTF-8) I/O layer), the seek, tell, and sysseek family of functions use byte offsets, not character offsets, because seeking to a character offset would be very slow in a UTF-8 file.

バイト単位に対する注意: 例え(例えば :encoding(UTF-8) I/O 層を使うなどして) ファイルハンドルが文字単位で処理するように設定されていたとしても、 seek, tell, sysseek シリーズの関数は 文字オフセットではなくバイトオフセットを使います; 文字オフセットでシークするのは UTF-8 ファイルではとても遅いからです。

If you want to position the file for sysread or syswrite, don't use seek, because buffering makes its effect on the file's read-write position unpredictable and non-portable. Use sysseek instead.

sysreadsyswrite のためにファイルの 位置を指定したい場合は、seek は 使えません; なぜならバッファリングのためにファイルの読み込み位置は 動作は予測不能で移植性のないものになってしまいます。 代わりに sysseek を使ってください。

Due to the rules and rigors of ANSI C, on some systems you have to do a seek whenever you switch between reading and writing. Amongst other things, this may have the effect of calling stdio's clearerr(3). A WHENCE of 1 (SEEK_CUR) is useful for not moving the file position:

ANSI C の規則と困難により、システムによっては読み込みと書き込みを 切り替える度にシークしなければならない場合があります。 その他のことの中で、これは stdio の clearerr(3) を呼び出す効果があります。 WHENCE の 1 (SEEK_CUR) が、ファイル位置を変えないので有用です:

    seek($fh, 0, 1);

This is also useful for applications emulating tail -f. Once you hit EOF on your read and then sleep for a while, you (probably) have to stick in a dummy seek to reset things. The seek doesn't change the position, but it does clear the end-of-file condition on the handle, so that the next readline FILE makes Perl try again to read something. (We hope.)

これはアプリケーションで tail -f をエミュレートするのにも有用です。 一度読み込み時に EOF に到達すると、しばらくスリープし、 (おそらく) ダミーの seek をすることで リセットする必要があります。 seek は現在の位置を変更しませんが、 ハンドルの EOF 状態をクリアします ので、次の readline FILE で Perl は 再び何かを読み込もうとします。(そのはずです。)

If that doesn't work (some I/O implementations are particularly cantankerous), you might need something like this:

これが動かない場合(特に意地の悪い I/O 実装もあります)、 以下のようなことをする必要があります:

    for (;;) {
        for ($curpos = tell($fh); $_ = readline($fh);
             $curpos = tell($fh)) {
            # search for some stuff and put it into files
        }
        sleep($for_a_while);
        seek($fh, $curpos, 0);
    }
seekdir DIRHANDLE,POS

Sets the current position for the readdir routine on DIRHANDLE. POS must be a value returned by telldir. seekdir also has the same caveats about possible directory compaction as the corresponding system library routine.

DIRHANDLE での readdir ルーチンの現在位置を 設定します。 POS は、telldir が返す値でなければなりません。 seekdir は同名のシステムライブラリルーチンと 同じく、ディレクトリ縮小時の問題が考えられます。

select FILEHANDLE
select

Returns the currently selected filehandle. If FILEHANDLE is supplied, sets the new current default filehandle for output. This has two effects: first, a write or a print without a filehandle default to this FILEHANDLE. Second, references to variables related to output will refer to this output channel.

その時点で、選択されていたファイルハンドルを返します。 FILEHANDLE を指定した場合には、その値を出力のデフォルトファイルハンドルに 設定します。 これには、2 つの効果があります: まず、ファイルハンドルを指定しないで writeprint を 行なった場合のデフォルトが、この FILEHANDLE になります。 もう一つは、出力関連の変数への参照は、この出力チャネルを 参照するようになります。

For example, to set the top-of-form format for more than one output channel, you might do the following:

例えば、複数の出力チャネルに対して、ページ先頭フォーマットを 設定するには:

    select(REPORT1);
    $^ = 'report1_top';
    select(REPORT2);
    $^ = 'report2_top';

FILEHANDLE may be an expression whose value gives the name of the actual filehandle. Thus:

FILEHANDLE は、実際のファイルハンドル名を示す式でもかまいません。 つまり、以下のようなものです:

    my $oldfh = select(STDERR); $| = 1; select($oldfh);

Some programmers may prefer to think of filehandles as objects with methods, preferring to write the last example as:

ファイルハンドルはメソッドを持ったオブジェクトであると考えることを好む プログラマもいるかもしれません; そのような場合のための最後の例は 以下のようなものです:

    STDERR->autoflush(1);

(Prior to Perl version 5.14, you have to use IO::Handle; explicitly first.)

(Perl バージョン 5.14 以前では、まず明示的に use IO::Handle; とする 必要があります。)

Portability issues: "select" in perlport.

移植性の問題: "select" in perlport

select RBITS,WBITS,EBITS,TIMEOUT

This calls the select(2) syscall with the bit masks specified, which can be constructed using fileno and vec, along these lines:

これは、select(2) システムコールを、指定したビットマスクで呼び出します; ビットマスクは、filenovec を使って、以下のようにして作成できます:

    my $rin = my $win = my $ein = '';
    vec($rin, fileno(STDIN),  1) = 1;
    vec($win, fileno(STDOUT), 1) = 1;
    $ein = $rin | $win;

If you want to select on many filehandles, you may wish to write a subroutine like this:

複数のファイルハンドルに select を行ないたいのであれば、 以下のようにします:

    sub fhbits {
        my @fhlist = @_;
        my $bits = "";
        for my $fh (@fhlist) {
            vec($bits, fileno($fh), 1) = 1;
        }
        return $bits;
    }
    my $rin = fhbits(\*STDIN, $tty, $mysock);

The usual idiom is:

通常は、

 my ($nfound, $timeleft) =
   select(my $rout = $rin, my $wout = $win, my $eout = $ein,
                                                          $timeout);

or to block until something becomes ready just do this

のように使い、いずれかの準備が整うまでブロックするには、 以下のようにします。

 my $nfound =
   select(my $rout = $rin, my $wout = $win, my $eout = $ein, undef);

Most systems do not bother to return anything useful in $timeleft, so calling select in scalar context just returns $nfound.

ほとんどのシステムではわざわざ意味のある値を $timeleft に返さないので、 select をスカラコンテキストで 呼び出すと、単に $nfound を返します。

Any of the bit masks can also be undef. The timeout, if specified, is in seconds, which may be fractional. Note: not all implementations are capable of returning the $timeleft. If not, they always return $timeleft equal to the supplied $timeout.

どのビットマスクにも undef を設定することができます。 TIMEOUT を指定するときは、秒数で指定し、小数でかまいません。 注: すべての実装で、$timeleft が返せるものではありません。 その場合、$timeleft には、常に指定した $timeout と同じ値が返されます。

You can effect a sleep of 250 milliseconds this way:

250 ミリ秒の sleep と同じ効果が、以下のようにして得られます。

    select(undef, undef, undef, 0.25);

Note that whether select gets restarted after signals (say, SIGALRM) is implementation-dependent. See also perlport for notes on the portability of select.

select がシグナル (例えば、SIGALRM) の 後に再起動するかどうかは実装依存であることに注意してください。 select の移植性に関する 注意については perlport も参照してください。

On error, select behaves just like select(2): it returns -1 and sets $!.

エラー時は、selectselect(2) のように振舞います: -1 を返し、$! をセットします。

On some Unixes, select(2) may report a socket file descriptor as "ready for reading" even when no data is available, and thus any subsequent read would block. This can be avoided if you always use O_NONBLOCK on the socket. See select(2) and fcntl(2) for further details.

Unix の中には、実際に利用可能なデータがないために引き続く read が ブロックされる場合でも、select(2) が、ソケットファイル記述子が 「読み込み準備中」であると報告するものもあります。 これは、ソケットに対して常に O_NONBLOCK フラグを使うことで回避できます。 さらなる詳細については select(2)fcntl(2) を参照してください。

The standard IO::Select module provides a user-friendlier interface to select, mostly because it does all the bit-mask work for you.

標準の IO::Select モジュールは select へのよりユーザーフレンドリーな インターフェースを提供します; 主な理由はビットマスクの仕事を してくれることです。

WARNING: One should not attempt to mix buffered I/O (like read or readline) with select, except as permitted by POSIX, and even then only on POSIX systems. You have to use sysread instead.

警告: バッファ付き I/O (readreadline) と select を 混ぜて使ってはいけません(例外: POSIX で認められている形で使い、 POSIX システムでだけ動かす場合を除きます)。 代わりに sysread を 使わなければなりません。

Portability issues: "select" in perlport.

移植性の問題: "select" in perlport

semctl ID,SEMNUM,CMD,ARG

Calls the System V IPC function semctl(2). You'll probably have to say

System V IPC 関数 semctl(2) を呼び出します。 正しい定数定義を得るために、まず

    use IPC::SysV;

first to get the correct constant definitions. If CMD is IPC_STAT or GETALL, then ARG must be a variable that will hold the returned semid_ds structure or semaphore value array. Returns like ioctl: the undefined value for error, "0 but true" for zero, or the actual return value otherwise. The ARG must consist of a vector of native short integers, which may be created with pack("s!",(0)x$nsem). See also "SysV IPC" in perlipc and the documentation for IPC::SysV and IPC::Semaphore.

と書くことが必要でしょう。 CMD が、IPC_STAT か GETALL のときには、ARG は、返される semid_ds 構造体か、セマフォ値の配列を納める変数でなければなりません。 ioctl と同じように、エラー時には 未定義値、ゼロのときは "0 だが真"、それ以外なら、その値そのものを返します。 ARG はネイティブな short int のベクターから成っていなければなりません; これは pack("s!",(0)x$nsem) で作成できます。 "SysV IPC" in perlipc と、 IPC::SysV, IPC::Semaphore の文書も 参照してください。

Portability issues: "semctl" in perlport.

移植性の問題: "semctl" in perlport

semget KEY,NSEMS,FLAGS

Calls the System V IPC function semget(2). Returns the semaphore id, or the undefined value on error. See also "SysV IPC" in perlipc and the documentation for IPC::SysV and IPC::Semaphore.

System V IPC 関数 semget(2) を呼び出します。 セマフォ ID か、エラー時には未定義値を返します。 "SysV IPC" in perlipc と、IPC::SysV, IPC::Semaphore 文書も参照してください。

Portability issues: "semget" in perlport.

移植性の問題: "semget" in perlport

semop KEY,OPSTRING

Calls the System V IPC function semop(2) for semaphore operations such as signalling and waiting. OPSTRING must be a packed array of semop structures. Each semop structure can be generated with pack("s!3", $semnum, $semop, $semflag). The length of OPSTRING implies the number of semaphore operations. Returns true if successful, false on error. As an example, the following code waits on semaphore $semnum of semaphore id $semid:

シグナルを送信や、待ち合わせなどのセマフォ操作を行なうために、 System V IPC 関数 semop(2) を呼び出します。 OPSTRING は、semop 構造体の pack された配列でなければなりません。 semop 構造体は、それぞれ、pack("s!3", $semnum, $semop, $semflag) のように 作ることができます。 セマフォ操作の数は、OPSTRING の長さからわかります。 成功時には真を、エラー時には偽を返します。 以下の例は、セマフォ ID $semid のセマフォ $semnum で 待ち合わせを行ないます。

    my $semop = pack("s!3", $semnum, -1, 0);
    die "Semaphore trouble: $!\n" unless semop($semid, $semop);

To signal the semaphore, replace -1 with 1. See also "SysV IPC" in perlipc and the documentation for IPC::SysV and IPC::Semaphore.

セマフォにシグナルを送るには、-11 に変更してください。 "SysV IPC" in perlipcIPC::SysV, IPC::Semaphore の文書も参照してください。

Portability issues: "semop" in perlport.

移植性の問題: "semop" in perlport

send SOCKET,MSG,FLAGS,TO
send SOCKET,MSG,FLAGS

Sends a message on a socket. Attempts to send the scalar MSG to the SOCKET filehandle. Takes the same flags as the system call of the same name. On unconnected sockets, you must specify a destination to send to, in which case it does a sendto(2) syscall. Returns the number of characters sent, or the undefined value on error. The sendmsg(2) syscall is currently unimplemented. See "UDP: Message Passing" in perlipc for examples.

ソケットにメッセージを送ります。 スカラ MSG を ファイルハンドル SOCKET に送ろうとします。 同名のシステムコールと同じフラグが指定できます。 接続していないソケットには、send to に接続先を指定しなければならず、 この場合、sendto(2) を実行します。 送信した文字数か、エラー時には、未定義値を返します。 システムコール sendmsg(2) は現在実装されていません。 例については "UDP: Message Passing" in perlipc を参照してください。

Note that if the socket has been marked as :utf8, send will throw an exception. The :encoding(...) layer implicitly introduces the :utf8 layer. See binmode.

ソケットが :utf8 とマークされている場合、 send は例外を投げることに注意してください。 :encoding(...) 層は暗黙に :utf8 層を導入します。 binmode を参照してください。

setpgrp PID,PGRP

Sets the current process group for the specified PID, 0 for the current process. Raises an exception when used on a machine that doesn't implement POSIX setpgid(2) or BSD setpgrp(2). If the arguments are omitted, it defaults to 0,0. Note that the BSD 4.2 version of setpgrp does not accept any arguments, so only setpgrp(0,0) is portable. See also POSIX::setsid().

指定した PID (0 を指定するとカレントプロセス) に 対するプロセスグループを設定します。 POSIX setpgrp(2) または BSD setpgrp(2) が実装されていないマシンでは、 例外が発生します。 引数が省略された場合は、0,0が使われます。 BSD 4.2 版の setpgrp は引数を取ることができないので、 setpgrp(0,0) のみが移植性があることに注意してください。 POSIX::setsid() も参照してください。

Portability issues: "setpgrp" in perlport.

移植性の問題: "setpgrp" in perlport

setpriority WHICH,WHO,PRIORITY

Sets the current priority for a process, a process group, or a user. (See setpriority(2).) Raises an exception when used on a machine that doesn't implement setpriority(2).

プロセス、プロセスグループ、ユーザに対する優先順位を設定します。 (setpriority(2) を参照してください。) setpriority(2) が実装されていないマシンでは、例外が発生します。

WHICH can be any of PRIO_PROCESS, PRIO_PGRP or PRIO_USER imported from "RESOURCE CONSTANTS" in POSIX.

WHICH は、"RESOURCE CONSTANTS" in POSIX からインポートされた PRIO_PROCESS, PRIO_PGRP, PRIO_USER のいずれかです。

Portability issues: "setpriority" in perlport.

移植性の問題: "setpriority" in perlport

setsockopt SOCKET,LEVEL,OPTNAME,OPTVAL

Sets the socket option requested. Returns undef on error. Use integer constants provided by the Socket module for LEVEL and OPNAME. Values for LEVEL can also be obtained from getprotobyname. OPTVAL might either be a packed string or an integer. An integer OPTVAL is shorthand for pack("i", OPTVAL).

要求したソケットオプションを設定します。 エラー時には、undef を返します。 LEVEL と OPNAME には Socket モジュールが提供する 整数定数を使います。 LEVEL の値は getprotobyname から得ることもできます。 OPTVAL は pack された文字列か整数です。 整数の OPTVAL は pack("i", OPTVAL) の省略表現です。

An example disabling Nagle's algorithm on a socket:

ソケットに対する Nagle のアルゴリズムを無効にする例です:

    use Socket qw(IPPROTO_TCP TCP_NODELAY);
    setsockopt($socket, IPPROTO_TCP, TCP_NODELAY, 1);

Portability issues: "setsockopt" in perlport.

移植性の問題: "setsockopt" in perlport

shift ARRAY
shift

Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array, returns the undefined value. If ARRAY is omitted, shifts the @_ array within the lexical scope of subroutines and formats, and the @ARGV array outside a subroutine and also within the lexical scopes established by the eval STRING, BEGIN {}, INIT {}, CHECK {}, UNITCHECK {}, and END {} constructs.

配列の最初の値を取り出して、その値を返し、配列を一つ短くして、すべての要素を 前へずらします。 配列に要素がなければ、未定義値を返します。 ARRAY を省略すると、サブルーチンやフォーマットのレキシカルスコープでは @_ を、サブルーチンの外側で、eval STRING, BEGIN {}, INIT {}, CHECK {}, UNITCHECK {}, END {} で作成された レキシカルスコープでは @ARGV が用いられます。

Starting with Perl 5.14, an experimental feature allowed shift to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.

Perl 5.14 から、shift がスカラ式を取ることが出来るという 実験的機能がありました。 この実験は失敗と見なされ、Perl 5.24 で削除されました。

See also unshift, push, and pop. shift and unshift do the same thing to the left end of an array that pop and push do to the right end.

unshiftpushpop も参照してください。 shiftunshift は、 poppush が配列の右端で 行なうことを、左端で行ないます。

shmctl ID,CMD,ARG

Calls the System V IPC function shmctl. You'll probably have to say

System V IPC 関数 shmctl を呼び出します。 正しい定数定義を得るために、まず

    use IPC::SysV;

first to get the correct constant definitions. If CMD is IPC_STAT, then ARG must be a variable that will hold the returned shmid_ds structure. Returns like ioctl: undef for error; "0 but true" for zero; and the actual return value otherwise. See also "SysV IPC" in perlipc and the documentation for IPC::SysV.

と書くことが必要でしょう。 CMD が、IPC_STAT ならば、ARG は、返される shmid_ds 構造体を 納める変数でなければなりません。 ioctl と同様です: エラー時には undef; ゼロのときは "0 だが真"; それ以外なら、その値そのものを返します。 "SysV IPC" in perlipcIPC::SysV の文書も参照してください。

Portability issues: "shmctl" in perlport.

移植性の問題: "shmctl" in perlport

shmget KEY,SIZE,FLAGS

Calls the System V IPC function shmget. Returns the shared memory segment id, or undef on error. See also "SysV IPC" in perlipc and the documentation for IPC::SysV.

System V IPC 関数 shmget を呼び出します。 共有メモリのセグメント ID か、エラー時には undef を返します。 "SysV IPC" in perlipcIPC::SysV の文書も参照してください。

Portability issues: "shmget" in perlport.

移植性の問題: "shmget" in perlport

shmread ID,VAR,POS,SIZE
shmwrite ID,STRING,POS,SIZE

Reads or writes the System V shared memory segment ID starting at position POS for size SIZE by attaching to it, copying in/out, and detaching from it. When reading, VAR must be a variable that will hold the data read. When writing, if STRING is too long, only SIZE bytes are used; if STRING is too short, nulls are written to fill out SIZE bytes. Return true if successful, false on error. shmread taints the variable. See also "SysV IPC" in perlipc and the documentation for IPC::SysV and the IPC::Shareable module from CPAN.

System V 共有メモリセグメント ID に対し、アタッチして、コピーを行ない、 デタッチするという形で、位置 POS から、サイズ SIZE だけ、読み込みか書き込みを 行ないます。 読み込み時には、VAR は読み込んだデータを納める変数でなければなりません。 書き込み時には、STRING が長すぎても、SIZE バイトだけが使われます; STRING が 短すぎる場合には、SIZE バイトを埋めるために、ヌル文字が書き込まれます。 成功時には真を、エラー時には偽を返します。 shmread は変数を汚染します。 "SysV IPC" in perlipc および、IPC::SysV と CPAN の IPC::Shareable の文書も参照してください。

移植性の問題: "shmread" in perlport"shmwrite" in perlport

shutdown SOCKET,HOW

Shuts down a socket connection in the manner indicated by HOW, which has the same interpretation as in the syscall of the same name.

同名のシステムコールと同じように解釈される HOW によって、 指定された方法でソケット接続のシャットダウンを行ないます。

    shutdown($socket, 0);    # I/we have stopped reading data
    shutdown($socket, 1);    # I/we have stopped writing data
    shutdown($socket, 2);    # I/we have stopped using this socket

This is useful with sockets when you want to tell the other side you're done writing but not done reading, or vice versa. It's also a more insistent form of close because it also disables the file descriptor in any forked copies in other processes.

これは、こちらがソケットを書き終わったが読み終わっていない、 またはその逆を相手側に伝えたいときに便利です。 これはその他のプロセスでフォークしたファイル記述子のコピーも 無効にするので、よりしつこい閉じ方です。

Returns 1 for success; on error, returns undef if the first argument is not a valid filehandle, or returns 0 and sets $! for any other failure.

成功時には 1 を返します; エラーの場合、最初の引数が有効なファイルハンドルでない場合は undef を返し、その他のエラーの場合は 0 を返して $! をセットします。

sin EXPR
sin

Returns the sine of EXPR (expressed in radians). If EXPR is omitted, returns sine of $_.

(ラジアンで示した) EXPR の正弦を返します。 EXPR が省略されたときには、$_ の正弦を返します。

For the inverse sine operation, you may use the Math::Trig::asin function, or use this relation:

逆正弦を求めるためには、Math::Trig::asin 関数を使うか、 以下の関係を使ってください:

    sub asin { atan2($_[0], sqrt(1 - $_[0] * $_[0])) }
sleep EXPR
sleep

Causes the script to sleep for (integer) EXPR seconds, or forever if no argument is given. Returns the integer number of seconds actually slept.

スクリプトを(整数の) EXPR で指定した秒数 (省略時には、永久に) スリープさせます。 実際にスリープした秒数を返します。

May be interrupted if the process receives a signal such as SIGALRM.

そのプロセスが SIGALRMのようなシグナルを受信すると、 割り込みがかかります。

    eval {
        local $SIG{ALRM} = sub { die "Alarm!\n" };
        sleep;
    };
    die $@ unless $@ eq "Alarm!\n";

You probably cannot mix alarm and sleep calls, because sleep is often implemented using alarm.

sleep は、alarm を使って 実装されることが多いので、alarmsleep は、混ぜて使用することはおそらくできません。

On some older systems, it may sleep up to a full second less than what you requested, depending on how it counts seconds. Most modern systems always sleep the full amount. They may appear to sleep longer than that, however, because your process might not be scheduled right away in a busy multitasking system.

古いシステムでは、どのように秒を数えるかによって、要求した秒数に完全に 満たないうちに、スリープから抜ける場合があります。 最近のシステムでは、常に完全にスリープします。 しかし、負荷の高いマルチタスクシステムでは 正しくスケジューリングされないがために より長い時間スリープすることがあります。

For delays of finer granularity than one second, the Time::HiRes module (from CPAN, and starting from Perl 5.8 part of the standard distribution) provides usleep. You may also use Perl's four-argument version of select leaving the first three arguments undefined, or you might be able to use the syscall interface to access setitimer(2) if your system supports it. See perlfaq8 for details.

1 秒より精度の高いスリープを行なうには、Time::HiRes モジュール(CPAN から、 また Perl 5.8 からは標準配布されています) が usleep を提供します。 Perl の 4 引数版 select を最初の 3 引数を未定義にして使うか、setitimer(2) をサポートしているシステムでは、 Perl の syscall インタフェースを使って アクセスすることもできます。 詳しくは perlfaq8 を参照してください。

See also the POSIX module's pause function.

POSIX モジュールの pause 関数も参照してください。

socket SOCKET,DOMAIN,TYPE,PROTOCOL

Opens a socket of the specified kind and attaches it to filehandle SOCKET. DOMAIN, TYPE, and PROTOCOL are specified the same as for the syscall of the same name. You should use Socket first to get the proper definitions imported. See the examples in "Sockets: Client/Server Communication" in perlipc.

指定した種類のソケットをオープンし、ファイルハンドル SOCKET にアタッチします。 DOMAIN, TYPE, PROTOCOL は、同名のシステムコールと同じように指定します。 適切な定義を import するために、まず、use Socket とするとよいでしょう。 "Sockets: Client/Server Communication" in perlipc の例を参照してください。

On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptor, as determined by the value of $^F. See "$^F" in perlvar.

ファイルに対する close-on-exec フラグをサポートしているシステムでは、 フラグは $^F の値で決定される、新しくオープンされた ファイル記述子に対してセットされます。 "$^F" in perlvar を参照してください。

socketpair SOCKET1,SOCKET2,DOMAIN,TYPE,PROTOCOL

Creates an unnamed pair of sockets in the specified domain, of the specified type. DOMAIN, TYPE, and PROTOCOL are specified the same as for the syscall of the same name. If unimplemented, raises an exception. Returns true if successful.

指定した DOMAIN に、指定した TYPE で名前の無いソケットのペアを生成します。 DOMAIN, TYPE, PROTOCOL は、同名のシステムコールと同じように指定します。 実装されていない場合には、例外が発生します。 成功時には真を返します。

On systems that support a close-on-exec flag on files, the flag will be set for the newly opened file descriptors, as determined by the value of $^F. See "$^F" in perlvar.

ファイルに対する close-on-exec フラグをサポートしているシステムでは、 フラグは $^F の値で決定される、新しくオープンされた ファイル記述子に対してセットされます。 "$^F" in perlvar を参照してください。

Some systems define pipe in terms of socketpair, in which a call to pipe($rdr, $wtr) is essentially:

pipesocketpair を使って 定義しているシステムもあります; pipe($rdr, $wtr) は本質的には以下のようになります:

    use Socket;
    socketpair(my $rdr, my $wtr, AF_UNIX, SOCK_STREAM, PF_UNSPEC);
    shutdown($rdr, 1);        # no more writing for reader
    shutdown($wtr, 0);        # no more reading for writer

See perlipc for an example of socketpair use. Perl 5.8 and later will emulate socketpair using IP sockets to localhost if your system implements sockets but not socketpair.

socketpair の使用例については perlipc を参照してください。 Perl 5.8 以降では、システムがソケットを実装しているが socketpair を 実装していない場合、localhost に対して IP ソケットを使うことで socketpair をエミュレートします。

Portability issues: "socketpair" in perlport.

移植性の問題: "socketpair" in perlport

sort SUBNAME LIST
sort BLOCK LIST
sort LIST

In list context, this sorts the LIST and returns the sorted list value. In scalar context, the behaviour of sort is undefined.

リストコンテキストでは、LIST をソートし、ソートされたリスト値を返します。 スカラコンテキストでは、sort の振る舞いは未定義です。

If SUBNAME or BLOCK is omitted, sorts in standard string comparison order. If SUBNAME is specified, it gives the name of a subroutine that returns an integer less than, equal to, or greater than 0, depending on how the elements of the list are to be ordered. (The <=> and cmp operators are extremely useful in such routines.) SUBNAME may be a scalar variable name (unsubscripted), in which case the value provides the name of (or a reference to) the actual subroutine to use. In place of a SUBNAME, you can provide a BLOCK as an anonymous, in-line sort subroutine.

SUBNAME や BLOCK を省略すると、sort は標準の 文字列比較の順番で行なわれます。 SUBNAME を指定すると、それは、リストの要素をどのような順番に並べるかに 応じて、負の整数、0、正の整数を返すサブルーチンの名前であると解釈されます。 (このようなルーチンには、<=> 演算子や cmp 演算子が、 たいへん便利です。) SUBNAME は、スカラ変数名(添字なし)でもよく、その場合には、その値が使用する 実際のサブルーチンの名前(またはそのリファレンス)と解釈されます。 SUBNAME の代わりに、無名のインラインソートルーチンとして、BLOCK を 書くことができます。

If the subroutine's prototype is ($$), the elements to be compared are passed by reference in @_, as for a normal subroutine. This is slower than unprototyped subroutines, where the elements to be compared are passed into the subroutine as the package global variables $a and $b (see example below).

サブルーチンのプロトタイプが ($$)の場合、比較する要素は通常のサブルーチンと 同じように @_ の中にリファレンスとして渡されます。 これはプロトタイプなしのサブルーチンより遅いです; この場合は比較のため サブルーチンに渡される二つの要素は、パッケージのグローバル変数 $a$b で渡されます(次の例を参照してください)。

If the subroutine is an XSUB, the elements to be compared are pushed on to the stack, the way arguments are usually passed to XSUBs. $a and $b are not set.

サブルーチンが XSUB の場合、比較される要素は、普通に引数を XSUB に渡す形で、 スタックにプッシュされます。 $a$b は設定されません。

The values to be compared are always passed by reference and should not be modified.

比較される値はリファレンスによって渡されるので、変更するべきではありません。

You also cannot exit out of the sort block or subroutine using any of the loop control operators described in perlsyn or with goto.

また、ソートブロックやサブルーチンから perlsyn で説明されている ループ制御子や goto を使って抜けてはいけません。

When use locale (but not use locale ':not_characters') is in effect, sort LIST sorts LIST according to the current collation locale. See perllocale.

use locale が有効(そして use locale ':not_characters' が 有効でない)の場合、sort LIST は LIST を現在の比較ロケールに従って ソートします。 perllocale を参照してください。

sort returns aliases into the original list, much as a for loop's index variable aliases the list elements. That is, modifying an element of a list returned by sort (for example, in a foreach, map or grep) actually modifies the element in the original list. This is usually something to be avoided when writing clear code.

sort は元のリストへのエイリアスを返します; for ループのインデックス変数がリスト要素へのエイリアスと同様です。 つまり、sort で返されるリストの要素を(例えば、 foreachmapgrep で)変更すると、実際に元のリストの要素が 変更されます。 これはきれいなコードを書くときには普通は回避されます。

Historically Perl has varied in whether sorting is stable by default. If stability matters, it can be controlled explicitly by using the sort pragma.

歴史的には、ソートがデフォルトで安定かどうかは様々です。 安定性が問題になる場合は、sort プラグマを使うことで明示的に制御できます。

Examples:

例:

    # sort lexically
    my @articles = sort @files;

    # same thing, but with explicit sort routine
    my @articles = sort {$a cmp $b} @files;

    # now case-insensitively
    my @articles = sort {fc($a) cmp fc($b)} @files;

    # same thing in reversed order
    my @articles = sort {$b cmp $a} @files;

    # sort numerically ascending
    my @articles = sort {$a <=> $b} @files;

    # sort numerically descending
    my @articles = sort {$b <=> $a} @files;

    # this sorts the %age hash by value instead of key
    # using an in-line function
    my @eldest = sort { $age{$b} <=> $age{$a} } keys %age;

    # sort using explicit subroutine name
    sub byage {
        $age{$a} <=> $age{$b};  # presuming numeric
    }
    my @sortedclass = sort byage @class;

    sub backwards { $b cmp $a }
    my @harry  = qw(dog cat x Cain Abel);
    my @george = qw(gone chased yz Punished Axed);
    print sort @harry;
        # prints AbelCaincatdogx
    print sort backwards @harry;
        # prints xdogcatCainAbel
    print sort @george, 'to', @harry;
        # prints AbelAxedCainPunishedcatchaseddoggonetoxyz

    # inefficiently sort by descending numeric compare using
    # the first integer after the first = sign, or the
    # whole record case-insensitively otherwise

    my @new = sort {
        ($b =~ /=(\d+)/)[0] <=> ($a =~ /=(\d+)/)[0]
                            ||
                    fc($a)  cmp  fc($b)
    } @old;

    # same thing, but much more efficiently;
    # we'll build auxiliary indices instead
    # for speed
    my (@nums, @caps);
    for (@old) {
        push @nums, ( /=(\d+)/ ? $1 : undef );
        push @caps, fc($_);
    }

    my @new = @old[ sort {
                           $nums[$b] <=> $nums[$a]
                                    ||
                           $caps[$a] cmp $caps[$b]
                         } 0..$#old
                  ];

    # same thing, but without any temps
    my @new = map { $_->[0] }
           sort { $b->[1] <=> $a->[1]
                           ||
                  $a->[2] cmp $b->[2]
           } map { [$_, /=(\d+)/, fc($_)] } @old;

    # using a prototype allows you to use any comparison subroutine
    # as a sort subroutine (including other package's subroutines)
    package Other;
    sub backwards ($$) { $_[1] cmp $_[0]; }  # $a and $b are
                                             # not set here
    package main;
    my @new = sort Other::backwards @old;

    # guarantee stability
    use sort 'stable';
    my @new = sort { substr($a, 3, 5) cmp substr($b, 3, 5) } @old;

Warning: syntactical care is required when sorting the list returned from a function. If you want to sort the list returned by the function call find_records(@key), you can use:

警告: 関数から返されたリストをソートするときには文法上の注意が必要です。 関数呼び出し find_records(@key) から返されたリストをソートしたい場合、 以下のように出来ます:

    my @contact = sort { $a cmp $b } find_records @key;
    my @contact = sort +find_records(@key);
    my @contact = sort &find_records(@key);
    my @contact = sort(find_records(@key));

If instead you want to sort the array @key with the comparison routine find_records() then you can use:

一方、配列 @key を比較ルーチン find_records() でソートしたい場合は、 以下のように出来ます:

    my @contact = sort { find_records() } @key;
    my @contact = sort find_records(@key);
    my @contact = sort(find_records @key);
    my @contact = sort(find_records (@key));

$a and $b are set as package globals in the package the sort() is called from. That means $main::a and $main::b (or $::a and $::b) in the main package, $FooPack::a and $FooPack::b in the FooPack package, etc. If the sort block is in scope of a my or state declaration of $a and/or $b, you must spell out the full name of the variables in the sort block :

$a$b は、sort() を呼び出したパッケージのパッケージグローバルとして 設定されます。 つまり、main パッケージの $main::a$main::b (あるいは $::a$::b) 、 FooPack パッケージの $FooPack::a$FooPack::b、などです。 ソートブロックが $a$bmy または state のスコープ内の場合、 ソートブロックの変数の完全名を 指定しなければなりません:

   package main;
   my $a = "C"; # DANGER, Will Robinson, DANGER !!!

   print sort { $a cmp $b }               qw(A C E G B D F H);
                                          # WRONG
   sub badlexi { $a cmp $b }
   print sort badlexi                     qw(A C E G B D F H);
                                          # WRONG
   # the above prints BACFEDGH or some other incorrect ordering

   print sort { $::a cmp $::b }           qw(A C E G B D F H);
                                          # OK
   print sort { our $a cmp our $b }       qw(A C E G B D F H);
                                          # also OK
   print sort { our ($a, $b); $a cmp $b } qw(A C E G B D F H);
                                          # also OK
   sub lexi { our $a cmp our $b }
   print sort lexi                        qw(A C E G B D F H);
                                          # also OK
   # the above print ABCDEFGH

With proper care you may mix package and my (or state) $a and/or $b:

適切に注意すれば、パッケージと my (あるいは state) $a$b を 混ぜることができます:

   my $a = {
      tiny   => -2,
      small  => -1,
      normal => 0,
      big    => 1,
      huge   => 2
   };

   say sort { $a->{our $a} <=> $a->{our $b} }
       qw{ huge normal tiny small big};

   # prints tinysmallnormalbighuge

$a and $b are implicitly local to the sort() execution and regain their former values upon completing the sort.

$a$b は sort() の実行中は暗黙にローカル化され、ソート終了時に 元の値に戻ります。

Sort subroutines written using $a and $b are bound to their calling package. It is possible, but of limited interest, to define them in a different package, since the subroutine must still refer to the calling package's $a and $b :

$a$b を使って書かれたソートサブルーチンはその呼び出しパッケージに しなければなりません。 異なるパッケージに定義することは可能ですが、 これは可能ですが、限られた関心しかありません; サブルーチンは呼び出しパッケージの $a$b を 参照しなければならないからです:

   package Foo;
   sub lexi { $Bar::a cmp $Bar::b }
   package Bar;
   ... sort Foo::lexi ...

Use the prototyped versions (see above) for a more generic alternative.

より一般的な代替案としては(前述の)プロトタイプ版を使ってください。

The comparison function is required to behave. If it returns inconsistent results (sometimes saying $x[1] is less than $x[2] and sometimes saying the opposite, for example) the results are not well-defined.

比較関数は一貫した振る舞いをすることが求められます。 一貫しない結果を返す(例えば、あるときは $x[1]$x[2] より 小さいと返し、またあるときは逆を返す)場合、結果は未定義です。

Because <=> returns undef when either operand is NaN (not-a-number), be careful when sorting with a comparison function like $a <=> $b any lists that might contain a NaN. The following example takes advantage that NaN != NaN to eliminate any NaNs from the input list.

<=> はどちらかのオペランドが NaN (not-a-number) のときに undef を返すので、$a <=> $b といった比較関数で ソートする場合はリストに NaN が含まれないように注意してください。 以下の例は 入力リストから NaN を取り除くために NaN != NaN という性質を 利用しています。

    my @result = sort { $a <=> $b } grep { $_ == $_ } @input;
splice ARRAY,OFFSET,LENGTH,LIST
splice ARRAY,OFFSET,LENGTH
splice ARRAY,OFFSET
splice ARRAY

Removes the elements designated by OFFSET and LENGTH from an array, and replaces them with the elements of LIST, if any. In list context, returns the elements removed from the array. In scalar context, returns the last element removed, or undef if no elements are removed. The array grows or shrinks as necessary. If OFFSET is negative then it starts that far from the end of the array. If LENGTH is omitted, removes everything from OFFSET onward. If LENGTH is negative, removes the elements from OFFSET onward except for -LENGTH elements at the end of the array. If both OFFSET and LENGTH are omitted, removes everything. If OFFSET is past the end of the array and a LENGTH was provided, Perl issues a warning, and splices at the end of the array.

ARRAY から OFFSET、LENGTH で指定される要素を取り除き、 LIST があれば、それを代わりに挿入します。 リストコンテキストでは、配列から取り除かれた要素を返します。 スカラコンテキストでは、取り除かれた最後の要素を返します; 要素が 取り除かれなかった場合は undef を返します。 配列は、必要に応じて、大きくなったり、小さくなったりします。 OFFSET が負の数の場合は、配列の最後からの距離を示します。 LENGTH が省略されると、OFFSET 以降のすべての要素を取り除きます。 LENGTH が負の数の場合は、OFFSET から前方へ、配列の最後から -LENGTH 要素を 除いて取り除きます。 OFFSET と LENGTH の両方が省略されると、全ての要素を取り除きます。 OFFSET が配列の最後より後ろで、 LENGTH が指定されていると、Perl は警告を出し、 配列の最後に対して処理します。

The following equivalences hold (assuming $#a >= $i )

以下は、($#a >= $i と仮定すると) それぞれ、等価です。

    push(@a,$x,$y)      splice(@a,@a,0,$x,$y)
    pop(@a)             splice(@a,-1)
    shift(@a)           splice(@a,0,1)
    unshift(@a,$x,$y)   splice(@a,0,0,$x,$y)
    $a[$i] = $y         splice(@a,$i,1,$y)

splice can be used, for example, to implement n-ary queue processing:

splice は、例えば、n-ary キュー処理の 実装に使えます:

    sub nary_print {
      my $n = shift;
      while (my @next_n = splice @_, 0, $n) {
        say join q{ -- }, @next_n;
      }
    }

    nary_print(3, qw(a b c d e f g h));
    # prints:
    #   a -- b -- c
    #   d -- e -- f
    #   g -- h

Starting with Perl 5.14, an experimental feature allowed splice to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.

Perl 5.14 から、splice がスカラ式を 取ることが出来るという実験的機能がありました。 この実験は失敗と見なされ、Perl 5.24 で削除されました。

split /PATTERN/,EXPR,LIMIT
split /PATTERN/,EXPR
split /PATTERN/
split

Splits the string EXPR into a list of strings and returns the list in list context, or the size of the list in scalar context. (Prior to Perl 5.11, it also overwrote @_ with the list in void and scalar context. If you target old perls, beware.)

文字列 EXPR を文字列のリストに分割して、リストコンテキストではそのリストを 返し、スカラコンテキストではリストの大きさを返します。 (Perl 5.11 以前では、無効コンテキストやスカラコンテキストの場合は @_ をリストで上書きします。 もし古い perl を対象にするなら、注意してください。)

If only PATTERN is given, EXPR defaults to $_.

PATTERN のみが与えられた場合、EXPR のデフォルトは $_ です。

Anything in EXPR that matches PATTERN is taken to be a separator that separates the EXPR into substrings (called "fields") that do not include the separator. Note that a separator may be longer than one character or even have no characters at all (the empty string, which is a zero-width match).

EXPR の中で PATTERN にマッチングするものは何でも EXPR を("fields" と 呼ばれる)セパレータを 含まない 部分文字列に分割するための セパレータとなります。 セパレータは一文字より長くてもよく、全く文字がなくてもよい(空文字列は ゼロ幅マッチングです)ということに注意してください。

The PATTERN need not be constant; an expression may be used to specify a pattern that varies at runtime.

PATTERN は定数である必要はありません; 実行時に変更されるパターンを 指定するために式を使えます。

If PATTERN matches the empty string, the EXPR is split at the match position (between characters). As an example, the following:

PATTERN が空文字列にマッチングする場合、EXPR はマッチング位置 (文字の間)で分割されます。 例えば、以下のものは:

    print join(':', split(/b/, 'abc')), "\n";

uses the b in 'abc' as a separator to produce the output a:c. However, this:

'abc'b をセパレータとして使って出力 a:c を生成します。 しかし、これは:

    print join(':', split(//, 'abc')), "\n";

uses empty string matches as separators to produce the output a:b:c; thus, the empty string may be used to split EXPR into a list of its component characters.

空文字列マッチングをセパレータとして使って出力 a:b:c を生成します; 従って、 空文字列は EXPR を構成する文字のリストに分割するために使われます。

As a special case for split, the empty pattern given in match operator syntax (//) specifically matches the empty string, which is contrary to its usual interpretation as the last successful match.

split の特殊な場合として、 マッチング演算子 文法で与えられた 空パターン (//) は特に空文字列にマッチングし、最後に成功した マッチングという普通の解釈と異なります。

If PATTERN is /^/, then it is treated as if it used the multiline modifier (/^/m), since it isn't much use otherwise.

PATTERN が /^/ の場合、複数行修飾子 (/^/m) が使われたかのように扱われます; そうでなければほとんど 使えないからです。

/m and any of the other pattern modifiers valid for qr (summarized in "qr/STRING/msixpodualn" in perlop) may be specified explicitly.

qr で有効な /m 及びその他のパターン修飾子 ("qr/STRING/msixpodualn" in perlop にまとめられています) は 明示的に定義されます。

As another special case, split emulates the default behavior of the command line tool awk when the PATTERN is either omitted or a string composed of a single space character (such as ' ' or "\x20", but not e.g. / /). In this case, any leading whitespace in EXPR is removed before splitting occurs, and the PATTERN is instead treated as if it were /\s+/; in particular, this means that any contiguous whitespace (not just a single space character) is used as a separator. However, this special treatment can be avoided by specifying the pattern / / instead of the string " ", thereby allowing only a single space character to be a separator. In earlier Perls this special case was restricted to the use of a plain " " as the pattern argument to split; in Perl 5.18.0 and later this special case is triggered by any expression which evaluates to the simple string " ".

もう一つの特別な場合として、 split は PATTERN が省略されるか単一のスペース文字からなる文字列 (つまり例えば / / ではなく ' '"\x20") の場合、コマンドラインツール awk のデフォルトの振る舞いをエミュレートします。 この場合、EXPR の先頭の空白は分割を行う前に削除され、PATTERN は /\s+/ であったかのように扱われます; 特に、これは (単に単一の スペース文字ではなく) あらゆる 連続した空白がセパレータとして 使われるということです。 しかし、この特別の扱いは文字列 " " の代わりにパターン / / を 指定することで回避でき、それによってセパレータとして単一の スペース文字のみが使われます。 以前の Perl ではこの特別な場合は split のパターン引数として単に " " を 使った場合に制限されていました; Perl 5.18.0 以降では、この特別な場合は 単純な文字列 " " と評価される任意の式によって引き起こされます。

As of Perl 5.28, this special-cased whitespace splitting works as expected in the scope of "use feature 'unicode_strings". In previous versions, and outside the scope of that feature, it exhibits "The "Unicode Bug"" in perlunicode: characters that are whitespace according to Unicode rules but not according to ASCII rules can be treated as part of fields rather than as field separators, depending on the string's internal encoding.

Perl 5.28 から、この特別な場合の空白分割は "use feature 'unicode_strings" のスコープの中では想定通りに動作します。 以前のバージョンでは、そしてこの機能のスコープの外側では、 これは "The "Unicode Bug"" in perlunicode を引き起こします: Unicode によれば空白だけれども ASCII の規則ではそうではない文字は、 文字列の内部エンコーディングに依存して、 フィールドの区切りではなくフィールドの一部として扱われることがあります。

If omitted, PATTERN defaults to a single space, " ", triggering the previously described awk emulation.

省略されると、PATTERN のデフォルトは単一のスペース " " になり、 先に記述した awk エミュレーションを起動します。

If LIMIT is specified and positive, it represents the maximum number of fields into which the EXPR may be split; in other words, LIMIT is one greater than the maximum number of times EXPR may be split. Thus, the LIMIT value 1 means that EXPR may be split a maximum of zero times, producing a maximum of one field (namely, the entire value of EXPR). For instance:

LIMIT が指定された正数の場合、EXPR が分割されるフィールドの最大数を 表現します; 言い換えると、 LIMIT は EXPR が分割される数より一つ大きい数です。 従って、LIMIT の値 1 は EXPR が最大 0 回分割されるということで、 最大で一つのフィールドを生成します (言い換えると、EXPR 全体の値です)。 例えば:

    print join(':', split(//, 'abc', 1)), "\n";

produces the output abc, and this:

これは abc を出力し、次のものは:

    print join(':', split(//, 'abc', 2)), "\n";

produces the output a:bc, and each of these:

a:bc を出力し、以下のものそれぞれは:

    print join(':', split(//, 'abc', 3)), "\n";
    print join(':', split(//, 'abc', 4)), "\n";

produces the output a:b:c.

a:b:c を出力します。

If LIMIT is negative, it is treated as if it were instead arbitrarily large; as many fields as possible are produced.

LIMIT が負数なら、非常に大きい数であるかのように扱われます; できるだけ多くの フィールドが生成されます。

If LIMIT is omitted (or, equivalently, zero), then it is usually treated as if it were instead negative but with the exception that trailing empty fields are stripped (empty leading fields are always preserved); if all fields are empty, then all fields are considered to be trailing (and are thus stripped in this case). Thus, the following:

LIMIT が省略されると(あるいは等価な 0 なら)、普通は負数が指定されたかのように 動作しますが、末尾の空フィールドは取り除かれるという例外があります (先頭の空フィールドは常に保存されます); もし全てのフィールドが空なら、 全てのフィールドが末尾として扱われます(そしてこの場合取り除かれます)。 従って、以下のようにすると:

    print join(':', split(/,/, 'a,b,c,,,')), "\n";

produces the output a:b:c, but the following:

出力 a:b:c を生成しますが、以下のようにすると:

    print join(':', split(/,/, 'a,b,c,,,', -1)), "\n";

produces the output a:b:c:::.

出力 a:b:c::: を生成します。

In time-critical applications, it is worthwhile to avoid splitting into more fields than necessary. Thus, when assigning to a list, if LIMIT is omitted (or zero), then LIMIT is treated as though it were one larger than the number of variables in the list; for the following, LIMIT is implicitly 3:

時間に厳しいアプリケーションでは、必要でないフィールドの分割を避けるのは 価値があります。 従って、リストに代入される場合に、LIMIT が省略される(または 0)と、 LIMIT は リストにある変数の数より一つ大きい数のように扱われます; 次の場合、LIMIT は暗黙に 3 になります:

    my ($login, $passwd) = split(/:/);

Note that splitting an EXPR that evaluates to the empty string always produces zero fields, regardless of the LIMIT specified.

LIMIT の指定に関わらず、空文字列に評価される EXPR を分割すると常に 0 個の フィールドを生成することに注意してください。

An empty leading field is produced when there is a positive-width match at the beginning of EXPR. For instance:

EXPR の先頭で正数幅でマッチングしたときには先頭に空のフィールドが 生成されます。 例えば:

    print join(':', split(/ /, ' abc')), "\n";

produces the output :abc. However, a zero-width match at the beginning of EXPR never produces an empty field, so that:

これは出力 :abc を生成します。 しかし、EXPR の先頭でのゼロ幅マッチングは決して空フィールドを生成しないので:

    print join(':', split(//, ' abc'));

produces the output :a:b:c (rather than : :a:b:c).

これは(: :a:b:c ではなく)出力 :a:b:c を生成します。

An empty trailing field, on the other hand, is produced when there is a match at the end of EXPR, regardless of the length of the match (of course, unless a non-zero LIMIT is given explicitly, such fields are removed, as in the last example). Thus:

一方、末尾の空のフィールドは、マッチングの長さに関わらず、EXPR の末尾で マッチングしたときに生成されます(もちろん非 0 の LIMIT が明示的に 指定されていない場合です; このようなフィールドは前の例のように 取り除かれます)。 従って:

    print join(':', split(//, ' abc', -1)), "\n";

produces the output :a:b:c:.

これは出力 :a:b:c: を生成します。

If the PATTERN contains capturing groups, then for each separator, an additional field is produced for each substring captured by a group (in the order in which the groups are specified, as per backreferences); if any group does not match, then it captures the undef value instead of a substring. Also, note that any such additional field is produced whenever there is a separator (that is, whenever a split occurs), and such an additional field does not count towards the LIMIT. Consider the following expressions evaluated in list context (each returned list is provided in the associated comment):

PATTERN が 捕捉グループ を 含んでいる場合、それぞれのセパレータについて、 (後方参照 のようにグループが指定された) グループによって捕捉されたそれぞれの部分文字列について追加のフィールドが 生成されます; どのグループもマッチングしなかった場合、部分文字列の代わりに undef 値を捕捉します。 また、このような追加のフィールドはセパレータがあるとき(つまり、分割が 行われるとき)はいつでも生成され、このような追加のフィールドは LIMIT に関してはカウント されない ことに注意してください。 リストコンテキストで評価される以下のような式を考えます (それぞれの返されるリストは関連づけられたコメントで提供されます):

    split(/-|,/, "1-10,20", 3)
    # ('1', '10', '20')

    split(/(-|,)/, "1-10,20", 3)
    # ('1', '-', '10', ',', '20')

    split(/-|(,)/, "1-10,20", 3)
    # ('1', undef, '10', ',', '20')

    split(/(-)|,/, "1-10,20", 3)
    # ('1', '-', '10', undef, '20')

    split(/(-)|(,)/, "1-10,20", 3)
    # ('1', '-', undef, '10', undef, ',', '20')
sprintf FORMAT, LIST

Returns a string formatted by the usual printf conventions of the C library function sprintf. See below for more details and see sprintf(3) or printf(3) on your system for an explanation of the general principles.

C ライブラリ関数 sprintf の 普通の printf 記法の 整形された文字列を返します。 一般的な原則の説明については以下の説明と、システムの sprintf(3) または printf(3) の説明を参照してください。

For example:

例えば:

        # Format number with up to 8 leading zeroes
        my $result = sprintf("%08d", $number);

        # Round number to 3 digits after decimal point
        my $rounded = sprintf("%.3f", $number);

Perl does its own sprintf formatting: it emulates the C function sprintf(3), but doesn't use it except for floating-point numbers, and even then only standard modifiers are allowed. Non-standard extensions in your local sprintf(3) are therefore unavailable from Perl.

Perl は sprintf フォーマット処理を自力で行います: これは C の sprintf(3) 関数をエミュレートしますが、C の関数は使いません (浮動小数点を除きますが、それでも標準の記述子のみが利用できます)。 従って、ローカルな非標準の sprintf(3) 拡張機能は Perl では使えません。

Unlike printf, sprintf does not do what you probably mean when you pass it an array as your first argument. The array is given scalar context, and instead of using the 0th element of the array as the format, Perl will use the count of elements in the array as the format, which is almost never useful.

printf と違って、 sprintf の最初の引数に配列を渡しても あなたが多分望むとおりには動作しません。 配列はスカラコンテキストで渡されるので、配列の 0 番目の要素ではなく、 配列の要素数をフォーマットとして扱います; これはほとんど役に立ちません。

Perl's sprintf permits the following universally-known conversions:

Perl の sprintf は以下の一般に知られている変換に 対応しています:

   %%    a percent sign
   %c    a character with the given number
   %s    a string
   %d    a signed integer, in decimal
   %u    an unsigned integer, in decimal
   %o    an unsigned integer, in octal
   %x    an unsigned integer, in hexadecimal
   %e    a floating-point number, in scientific notation
   %f    a floating-point number, in fixed decimal notation
   %g    a floating-point number, in %e or %f notation
   %%    パーセントマーク
   %c    与えられた番号の文字
   %s    文字列
   %d    符号付き 10 進数
   %u    符号なし 10 進数
   %o    符号なし 8 進数
   %x    符号なし 16 進数
   %e    科学的表記の浮動小数点数
   %f    固定 10 進数表記の浮動小数点数
   %g    %e か %f の表記の浮動小数点数

In addition, Perl permits the following widely-supported conversions:

さらに、Perl では以下のよく使われている変換に対応しています:

   %X    like %x, but using upper-case letters
   %E    like %e, but using an upper-case "E"
   %G    like %g, but with an upper-case "E" (if applicable)
   %b    an unsigned integer, in binary
   %B    like %b, but using an upper-case "B" with the # flag
   %p    a pointer (outputs the Perl value's address in hexadecimal)
   %n    special: *stores* the number of characters output so far
         into the next argument in the parameter list
   %a    hexadecimal floating point
   %A    like %a, but using upper-case letters
   %X    %x と同様だが大文字を使う
   %E    %e と同様だが大文字の "E" を使う
   %G    %g と同様だが(適切なら)大文字の "E" を使う
   %b    符号なし 2 進数
   %B    %b と同様だが、# フラグで大文字の "B" を使う
   %p    ポインタ (Perl の値のアドレスを 16 進数で出力する)
   %n    特殊: 出力文字数を引数リストの次の変数に「格納」する
   %a    16 進浮動小数点
   %A    %a と同様だが、大文字を使う

Finally, for backward (and we do mean "backward") compatibility, Perl permits these unnecessary but widely-supported conversions:

最後に、過去との互換性(これは「過去」だと考えています)のために、 Perl は以下の不要ではあるけれども広く使われている変換に対応しています。

   %i    a synonym for %d
   %D    a synonym for %ld
   %U    a synonym for %lu
   %O    a synonym for %lo
   %F    a synonym for %f
   %i    %d の同義語
   %D    %ld の同義語
   %U    %lu の同義語
   %O    %lo の同義語
   %F    %f の同義語

Note that the number of exponent digits in the scientific notation produced by %e, %E, %g and %G for numbers with the modulus of the exponent less than 100 is system-dependent: it may be three or less (zero-padded as necessary). In other words, 1.23 times ten to the 99th may be either "1.23e99" or "1.23e099". Similarly for %a and %A: the exponent or the hexadecimal digits may float: especially the "long doubles" Perl configuration option may cause surprises.

%e, %E, %g, %G において、指数部が 100 未満の場合の 指数部の科学的な表記法はシステム依存であることに注意してください: 3 桁かもしれませんし、それ以下かもしれません(必要に応じて 0 で パッディングされます)。 言い換えると、 1.23 掛ける 10 の 99 乗は "1.23e99" かもしれませんし "1.23e099" かもしれません。 同様に %a%A の場合: 指数部と 16 進数が浮動小数点かもしれません: 特に "long doubles" Perl 設定オプションが驚きを引き起こすかもしれません。

Between the % and the format letter, you may specify several additional attributes controlling the interpretation of the format. In order, these are:

% とフォーマット文字の間に、フォーマットの解釈を制御するための、 いくつかの追加の属性を指定できます。 順番に、以下のものがあります:

format parameter index

(フォーマットパラメータインデックス)

An explicit format parameter index, such as 2$. By default sprintf will format the next unused argument in the list, but this allows you to take the arguments out of order:

2$ のような明示的なフォーマットパラメータインデックス。 デフォルトでは sprintf はリストの次の使われていない引数を フォーマットしますが、これによって異なった順番の引数を使えるようにします:

  printf '%2$d %1$d', 12, 34;      # prints "34 12"
  printf '%3$d %d %1$d', 1, 2, 3;  # prints "3 1 1"
flags

(フラグ)

one or more of:

以下のうちの一つまたは複数指定できます:

   space   prefix non-negative number with a space
   +       prefix non-negative number with a plus sign
   -       left-justify within the field
   0       use zeros, not spaces, to right-justify
   #       ensure the leading "0" for any octal,
           prefix non-zero hexadecimal with "0x" or "0X",
           prefix non-zero binary with "0b" or "0B"
   space   非負数の前に空白をつける
   +       非負数の前にプラス記号をつける
   -       フィールド内で左詰めする
   0       右詰めに空白ではなくゼロを使う
   #       8 進数では確実に先頭に "0" をつける;
           非 0 の 16 進数では "0x" か "0X" をつける;
           非 0 の 2 進数では "0b" か "0B" をつける

For example:

例えば:

  printf '<% d>',  12;   # prints "< 12>"
  printf '<% d>',   0;   # prints "< 0>"
  printf '<% d>', -12;   # prints "<-12>"
  printf '<%+d>',  12;   # prints "<+12>"
  printf '<%+d>',   0;   # prints "<+0>"
  printf '<%+d>', -12;   # prints "<-12>"
  printf '<%6s>',  12;   # prints "<    12>"
  printf '<%-6s>', 12;   # prints "<12    >"
  printf '<%06s>', 12;   # prints "<000012>"
  printf '<%#o>',  12;   # prints "<014>"
  printf '<%#x>',  12;   # prints "<0xc>"
  printf '<%#X>',  12;   # prints "<0XC>"
  printf '<%#b>',  12;   # prints "<0b1100>"
  printf '<%#B>',  12;   # prints "<0B1100>"

When a space and a plus sign are given as the flags at once, the space is ignored.

空白とプラス記号がフラグとして同時に与えられると、 空白は無視されます。

  printf '<%+ d>', 12;   # prints "<+12>"
  printf '<% +d>', 12;   # prints "<+12>"

When the # flag and a precision are given in the %o conversion, the precision is incremented if it's necessary for the leading "0".

%o 変換に # フラグと精度が与えられると、先頭の "0" が必要な場合は 精度に 1 が加えられます。

  printf '<%#.5o>', 012;      # prints "<00012>"
  printf '<%#.5o>', 012345;   # prints "<012345>"
  printf '<%#.0o>', 0;        # prints "<0>"
vector flag

(ベクタフラグ)

This flag tells Perl to interpret the supplied string as a vector of integers, one for each character in the string. Perl applies the format to each integer in turn, then joins the resulting strings with a separator (a dot . by default). This can be useful for displaying ordinal values of characters in arbitrary strings:

このフラグは Perl に、与えられた文字列を、文字毎に一つの整数のベクタとして 解釈させます。 Perl は各数値をフォーマットし、それから結果の文字列をセパレータ (デフォルトでは .)で連結します。 これは任意の文字列の文字を順序付きの値として表示するのに便利です:

  printf "%vd", "AB\x{100}";           # prints "65.66.256"
  printf "version is v%vd\n", $^V;     # Perl's version

Put an asterisk * before the v to override the string to use to separate the numbers:

アスタリスク *v の前に置くと、数値を分けるために使われる文字列を 上書きします:

  printf "address is %*vX\n", ":", $addr;   # IPv6 address
  printf "bits are %0*v8b\n", " ", $bits;   # random bitstring

You can also explicitly specify the argument number to use for the join string using something like *2$v; for example:

また、*2$v のように、連結する文字列として使う引数の番号を明示的に 指定できます; 例えば:

  printf '%*4$vX %*4$vX %*4$vX',       # 3 IPv6 addresses
          @addr[1..3], ":";
(minimum) width

((最小)幅)

Arguments are usually formatted to be only as wide as required to display the given value. You can override the width by putting a number here, or get the width from the next argument (with *) or from a specified argument (e.g., with *2$):

引数は、普通は値を表示するのに必要なちょうどの幅でフォーマットされます。 ここに数値を置くか、(* で)次の引数か(*2$ で)明示的に指定した引数で 幅を上書きできます。

 printf "<%s>", "a";       # prints "<a>"
 printf "<%6s>", "a";      # prints "<     a>"
 printf "<%*s>", 6, "a";   # prints "<     a>"
 printf '<%*2$s>', "a", 6; # prints "<     a>"
 printf "<%2s>", "long";   # prints "<long>" (does not truncate)

If a field width obtained through * is negative, it has the same effect as the - flag: left-justification.

* を通して得られたフィールドの値が負数の場合、- フラグと 同様の効果 (左詰め) があります。

precision, or maximum width

(精度あるいは最大幅)

You can specify a precision (for numeric conversions) or a maximum width (for string conversions) by specifying a . followed by a number. For floating-point formats except g and G, this specifies how many places right of the decimal point to show (the default being 6). For example:

. の後に数値を指定することで、(数値変換の場合)精度や(文字列変換の場合) 最大幅を指定できます。 小数点数フォーマットの場合、gG を除いて、表示する小数点以下の 桁数を指定します(デフォルトは 6 です)。 例えば:

  # these examples are subject to system-specific variation
  printf '<%f>', 1;    # prints "<1.000000>"
  printf '<%.1f>', 1;  # prints "<1.0>"
  printf '<%.0f>', 1;  # prints "<1>"
  printf '<%e>', 10;   # prints "<1.000000e+01>"
  printf '<%.1e>', 10; # prints "<1.0e+01>"

For "g" and "G", this specifies the maximum number of significant digits to show; for example:

"g" と "G" の場合、これは最大有効数字を指定します; 例えば:

  # These examples are subject to system-specific variation.
  printf '<%g>', 1;        # prints "<1>"
  printf '<%.10g>', 1;     # prints "<1>"
  printf '<%g>', 100;      # prints "<100>"
  printf '<%.1g>', 100;    # prints "<1e+02>"
  printf '<%.2g>', 100.01; # prints "<1e+02>"
  printf '<%.5g>', 100.01; # prints "<100.01>"
  printf '<%.4g>', 100.01; # prints "<100>"
  printf '<%.1g>', 0.0111; # prints "<0.01>"
  printf '<%.2g>', 0.0111; # prints "<0.011>"
  printf '<%.3g>', 0.0111; # prints "<0.0111>"

For integer conversions, specifying a precision implies that the output of the number itself should be zero-padded to this width, where the 0 flag is ignored:

整数変換の場合、精度を指定すると、数値自体の出力はこの幅に 0 で パッディングするべきであることを暗に示すことになり、0 フラグは 無視されます:

  printf '<%.6d>', 1;      # prints "<000001>"
  printf '<%+.6d>', 1;     # prints "<+000001>"
  printf '<%-10.6d>', 1;   # prints "<000001    >"
  printf '<%10.6d>', 1;    # prints "<    000001>"
  printf '<%010.6d>', 1;   # prints "<    000001>"
  printf '<%+10.6d>', 1;   # prints "<   +000001>"

  printf '<%.6x>', 1;      # prints "<000001>"
  printf '<%#.6x>', 1;     # prints "<0x000001>"
  printf '<%-10.6x>', 1;   # prints "<000001    >"
  printf '<%10.6x>', 1;    # prints "<    000001>"
  printf '<%010.6x>', 1;   # prints "<    000001>"
  printf '<%#10.6x>', 1;   # prints "<  0x000001>"

For string conversions, specifying a precision truncates the string to fit the specified width:

文字列変換の場合、精度を指定すると、指定された幅に収まるように文字列を 切り詰めます:

  printf '<%.5s>', "truncated";   # prints "<trunc>"
  printf '<%10.5s>', "truncated"; # prints "<     trunc>"

You can also get the precision from the next argument using .*, or from a specified argument (e.g., with .*2$):

.* を使って精度を次の引数から取ったり、 (.*2$ のように) 指定した引数から取ったりすることもできます:

  printf '<%.6x>', 1;       # prints "<000001>"
  printf '<%.*x>', 6, 1;    # prints "<000001>"

  printf '<%.*2$x>', 1, 6;  # prints "<000001>"

  printf '<%6.*2$x>', 1, 4; # prints "<  0001>"

If a precision obtained through * is negative, it counts as having no precision at all.

* によって得られた精度が負数の場合、精度が指定されなかった場合と 同じ効果となります。

  printf '<%.*s>',  7, "string";   # prints "<string>"
  printf '<%.*s>',  3, "string";   # prints "<str>"
  printf '<%.*s>',  0, "string";   # prints "<>"
  printf '<%.*s>', -1, "string";   # prints "<string>"

  printf '<%.*d>',  1, 0;   # prints "<0>"
  printf '<%.*d>',  0, 0;   # prints "<>"
  printf '<%.*d>', -1, 0;   # prints "<0>"
size

(サイズ)

For numeric conversions, you can specify the size to interpret the number as using l, h, V, q, L, or ll. For integer conversions (d u o x X b i D U O), numbers are usually assumed to be whatever the default integer size is on your platform (usually 32 or 64 bits), but you can override this to use instead one of the standard C types, as supported by the compiler used to build Perl:

数値変換では、l, h, V, q, L, ll を使って解釈する数値の 大きさを指定できます。 整数変換 (d u o x X b i D U O) では、数値は通常プラットフォームの デフォルトの整数のサイズ (通常は 32 ビットか 64 ビット) を仮定しますが、 これを Perl がビルドされたコンパイラが対応している標準 C の型の一つで 上書きできます:

   hh          interpret integer as C type "char" or "unsigned
               char" on Perl 5.14 or later
   h           interpret integer as C type "short" or
               "unsigned short"
   j           interpret integer as C type "intmax_t" on Perl
               5.14 or later; and prior to Perl 5.30, only with
               a C99 compiler (unportable)
   l           interpret integer as C type "long" or
               "unsigned long"
   q, L, or ll interpret integer as C type "long long",
               "unsigned long long", or "quad" (typically
               64-bit integers)
   t           interpret integer as C type "ptrdiff_t" on Perl
               5.14 or later
   z           interpret integer as C type "size_t" on Perl 5.14
               or later
   hh          Perl 5.14 以降で整数を C の "char" または "unsigned char"
               型として解釈する
   h           整数を C の "char" または "unsigned char" 型として解釈する
   j           Perl 5.14 以降 Perl 5.30 以前の C99 コンパイラのみで整数を
               C の "intmax_t" 型として解釈する (移植性なし)
   l           整数を C の "long" または "unsigned long" と解釈する
   h           整数を C の "short" または "unsigned short" と解釈する
   q, L or ll  整数を C の "long long", "unsigned long long",
               "quads"(典型的には 64 ビット整数) のどれかと解釈する
   t           Perl 5.14 以降で整数を C の "ptrdiff_t" 型として解釈する
   z           Perl 5.14 以降で整数を C の "size_t" 型として解釈する

As of 5.14, none of these raises an exception if they are not supported on your platform. However, if warnings are enabled, a warning of the printf warning class is issued on an unsupported conversion flag. Should you instead prefer an exception, do this:

5.14 から、プラットフォームがこれらに対応していないときでも例外が 発生しなくなりました。 しかし、もし警告が有効になっているなら、 非対応変換フラグに関して printf 警告クラスの警告が発生します。 例外の方がお好みなら、以下のようにします:

    use warnings FATAL => "printf";

If you would like to know about a version dependency before you start running the program, put something like this at its top:

プログラムの実行開始前にバージョン依存について知りたいなら、先頭に 以下のようなものを書きます:

    use 5.014;  # for hh/j/t/z/ printf modifiers

You can find out whether your Perl supports quads via Config:

Perl が 64 ビット整数に対応しているかどうかは Config を使って 調べられます:

    use Config;
    if ($Config{use64bitint} eq "define"
        || $Config{longsize} >= 8) {
        print "Nice quads!\n";
    }

For floating-point conversions (e f g E F G), numbers are usually assumed to be the default floating-point size on your platform (double or long double), but you can force "long double" with q, L, or ll if your platform supports them. You can find out whether your Perl supports long doubles via Config:

浮動小数点数変換 (e f g E F G) では、普通はプラットフォームのデフォルトの 不動小数点数のサイズ (double か long double) を仮定しますが、 プラットフォームが対応しているなら、q, L, ll に対して "long double" を強制できます。 Perl が long double に対応しているかどうかは Config を使って 調べられます:

    use Config;
    print "long doubles\n" if $Config{d_longdbl} eq "define";

You can find out whether Perl considers "long double" to be the default floating-point size to use on your platform via Config:

Perl が "long double" をデフォルトの浮動小数点数として扱っているかどうかは Config を使って調べられます:

    use Config;
    if ($Config{uselongdouble} eq "define") {
        print "long doubles by default\n";
    }

It can also be that long doubles and doubles are the same thing:

long double と double が同じ場合もあります:

        use Config;
        ($Config{doublesize} == $Config{longdblsize}) &&
                print "doubles are long doubles\n";

The size specifier V has no effect for Perl code, but is supported for compatibility with XS code. It means "use the standard size for a Perl integer or floating-point number", which is the default.

サイズ指定子 V は Perl のコードには何の影響もありませんが、これは XS コードとの互換性のために対応しています。 これは「Perl 整数 (または浮動小数点数) として標準的なサイズを使う」ことを 意味し、これはデフォルトです。

order of arguments

(引数の順序)

Normally, sprintf takes the next unused argument as the value to format for each format specification. If the format specification uses * to require additional arguments, these are consumed from the argument list in the order they appear in the format specification before the value to format. Where an argument is specified by an explicit index, this does not affect the normal order for the arguments, even when the explicitly specified index would have been the next argument.

通常、sprintf は各フォーマット指定について、 使われていない次の引数を フォーマットする値として使います。 追加の引数を要求するためにフォーマット指定 * を使うと、 これらはフォーマットする値の のフォーマット指定に現れる順番に 引数リストから消費されます。 引数の位置が明示的なインデックスを使って指定された場合、 (明示的に指定したインデックスが次の引数の場合でも) これは通常の引数の順番に影響を与えません。

So:

それで:

    printf "<%*.*s>", $a, $b, $c;

uses $a for the width, $b for the precision, and $c as the value to format; while:

とすると $a を幅に、$b を精度に、$c をフォーマットの値に 使います; 一方:

  printf '<%*1$.*s>', $a, $b;

would use $a for the width and precision, and $b as the value to format.

とすると $a を幅と精度に、$b をフォーマットの値に使います。

Here are some more examples; be aware that when using an explicit index, the $ may need escaping:

以下にさらなる例を示します; 明示的にインデックスを使う場合、$ は エスケープする必要があることに注意してください:

 printf "%2\$d %d\n",      12, 34;     # will print "34 12\n"
 printf "%2\$d %d %d\n",   12, 34;     # will print "34 12 34\n"
 printf "%3\$d %d %d\n",   12, 34, 56; # will print "56 12 34\n"
 printf "%2\$*3\$d %d\n",  12, 34,  3; # will print " 34 12\n"
 printf "%*1\$.*f\n",       4,  5, 10; # will print "5.0000\n"

If use locale (including use locale ':not_characters') is in effect and POSIX::setlocale has been called, the character used for the decimal separator in formatted floating-point numbers is affected by the LC_NUMERIC locale. See perllocale and POSIX.

(use locale ':not_characters' を含む)use locale が有効で、 POSIX::setlocale が呼び出されている場合、 フォーマットされた浮動小数点数の小数点として使われる文字は LC_NUMERIC ロケールの影響を受けます。 perllocalePOSIX を参照してください。

sqrt EXPR
sqrt

Return the positive square root of EXPR. If EXPR is omitted, uses $_. Works only for non-negative operands unless you've loaded the Math::Complex module.

EXPR の正の平方根を返します。 EXPR が省略されると、$_ を使います。 Math::Complex モジュールを使わない場合は、負の数の引数は 扱えません。

    use Math::Complex;
    print sqrt(-4);    # prints 2i
srand EXPR
srand

Sets and returns the random number seed for the rand operator.

rand 演算子のためのシード値を設定して返します。

The point of the function is to "seed" the rand function so that rand can produce a different sequence each time you run your program. When called with a parameter, srand uses that for the seed; otherwise it (semi-)randomly chooses a seed. In either case, starting with Perl 5.14, it returns the seed. To signal that your code will work only on Perls of a recent vintage:

この関数のポイントは、プログラムを実行するごとに rand 関数が 異なる乱数列を生成できるように rand 関数の「種」を 設定することです。 srand を引数付きで呼び出すと、これを種として使います; さもなければ(だいたい)ランダムに種を選びます。 どちらの場合でも、Perl 5.14 からは種を返します。 特定の時期の Perl でのみ 動作することを知らせるには以下のようにします:

    use 5.014;  # so srand returns the seed

If srand is not called explicitly, it is called implicitly without a parameter at the first use of the rand operator. However, there are a few situations where programs are likely to want to call srand. One is for generating predictable results, generally for testing or debugging. There, you use srand($seed), with the same $seed each time. Another case is that you may want to call srand after a fork to avoid child processes sharing the same seed value as the parent (and consequently each other).

srand が明示的に呼び出されなかった場合、最初に rand 演算子を使った時点で暗黙に引数なしで呼び出されます。 しかし、最近の Perl でプログラムが srand を 呼び出したいであろう状況がいくつかあります。 一つはテストやデバッグのために予測可能な結果を生成するためです。 この場合、srand($seed) ($seed は毎回同じ値を使う) を使います。 もう一つの場合としては、子プロセスが親や他の子プロセスと同じ種の値を 共有することを避けるために、fork の後に srand を 呼び出したいかもしれません。

Do not call srand() (i.e., without an argument) more than once per process. The internal state of the random number generator should contain more entropy than can be provided by any seed, so calling srand again actually loses randomness.

srand (引数なし)をプロセス中で複数回 呼び出しては いけません。 乱数生成器の内部状態はどのような種によって提供されるものよりも 高いエントロピーを持っているので、srand() を再び呼び出すと ランダム性が 失われます

Most implementations of srand take an integer and will silently truncate decimal numbers. This means srand(42) will usually produce the same results as srand(42.1). To be safe, always pass srand an integer.

srand のほとんどの実装では整数を取り、小数を暗黙に 切り捨てます。 これは、srand(42) は普通 srand(42.1) と同じ結果になることを意味します。 安全のために、srand には常に整数を渡しましょう。

A typical use of the returned seed is for a test program which has too many combinations to test comprehensively in the time available to it each run. It can test a random subset each time, and should there be a failure, log the seed used for that run so that it can later be used to reproduce the same results.

返された種の典型的な利用法は、実行毎のテストを利用可能な時間内に完全に 行うには組み合わせが多すぎるテストプログラム用です。 毎回ランダムなサブセットをテストし、もし失敗したら、その実行で使った 種をログに出力することで、後で同じ結果を再現するために使えます。

rand is not cryptographically secure. You should not rely on it in security-sensitive situations. As of this writing, a number of third-party CPAN modules offer random number generators intended by their authors to be cryptographically secure, including: Data::Entropy, Crypt::Random, Math::Random::Secure, and Math::TrulyRandom.

rand は暗号学的に安全ではありません。 セキュリティ的に重要な状況でこれに頼るべきではありません。 これを書いている時点で、いくつかのサードパーティ CPAN モジュールが 作者によって暗号学的に安全であることを目的とした乱数生成器を 提供しています: Data::Entropy, Crypt::Random, Math::Random::Secure, Math::TrulyRandom などです。

stat FILEHANDLE
stat EXPR
stat DIRHANDLE
stat

Returns a 13-element list giving the status info for a file, either the file opened via FILEHANDLE or DIRHANDLE, or named by EXPR. If EXPR is omitted, it stats $_ (not _!). Returns the empty list if stat fails. Typically used as follows:

FILEHANDLE か DIRHANDLE を通じてオープンされているファイルか、 EXPR で指定されるファイルの情報を与える、13 要素のリストを返します。 EXPR が省略されると、 $_ が用いられます (_ ではありません!)。 stat に失敗した場合には、空リストを返します。 普通は、以下のようにして使います:

    my ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
        $atime,$mtime,$ctime,$blksize,$blocks)
           = stat($filename);

Not all fields are supported on all filesystem types. Here are the meanings of the fields:

全てのファイルシステムで全てのフィールドに対応しているわけではありません。 フィールドの意味は以下の通りです。

  0 dev      device number of filesystem
  1 ino      inode number
  2 mode     file mode  (type and permissions)
  3 nlink    number of (hard) links to the file
  4 uid      numeric user ID of file's owner
  5 gid      numeric group ID of file's owner
  6 rdev     the device identifier (special files only)
  7 size     total size of file, in bytes
  8 atime    last access time in seconds since the epoch
  9 mtime    last modify time in seconds since the epoch
 10 ctime    inode change time in seconds since the epoch (*)
 11 blksize  preferred I/O size in bytes for interacting with the
             file (may vary from file to file)
 12 blocks   actual number of system-specific blocks allocated
             on disk (often, but not always, 512 bytes each)
  0 dev      ファイルシステムのデバイス番号
  1 ino      inode 番号
  2 mode     ファイルモード (タイプとパーミッション)
  3 nlink    ファイルへの(ハード)リンクの数
  4 uid      ファイル所有者のユーザー ID の数値
  5 gid      ファイル所有者のグループ ID の数値
  6 rdev     デバイス識別子(特殊ファイルのみ)
  7 size     ファイルサイズ(バイト単位)
  8 atime    紀元から、最後にアクセスされた時刻までの秒数
  9 mtime    紀元から、最後に修正(modify)された時刻までの秒数
 10 ctime    紀元から、inode 変更(change)された時刻までの秒数 (*)
 11 blksize  ファイルとの相互作用のために適した I/O バイト数
             (ファイルごとに異なるかもしれない)
 12 blocks   ディスクに割り当てたシステム依存のブロック(常にでは
             ありませんがたいていはそれぞれ 512 バイト)の数

(The epoch was at 00:00 January 1, 1970 GMT.)

(紀元は GMT で 1970/01/01 00:00:00。)

(*) Not all fields are supported on all filesystem types. Notably, the ctime field is non-portable. In particular, you cannot expect it to be a "creation time"; see "Files and Filesystems" in perlport for details.

(*) 全てのフィールドが全てのファイルシステムタイプで対応しているわけでは ありません。 明らかに、ctime のフィールドは移植性がありません。 特に、これから「作成時刻」を想定することは出来ません; 詳細については "Files and Filesystems" in perlport を参照してください。

If stat is passed the special filehandle consisting of an underline, no stat is done, but the current contents of the stat structure from the last stat, lstat, or filetest are returned. Example:

下線だけの _ という特別なファイルハンドルを stat に 渡すと、実際には stat を行なわず、stat 構造体に残っている 前回の stat, lstat や ファイルテストの情報が返されます。 例:

    if (-x $file && (($d) = stat(_)) && $d < 0) {
        print "$file is executable NFS file\n";
    }

(This works on machines only for which the device number is negative under NFS.)

(これは、NFS のもとでデバイス番号が負になるマシンでのみ動作します。)

On some platforms inode numbers are of a type larger than perl knows how to handle as integer numerical values. If necessary, an inode number will be returned as a decimal string in order to preserve the entire value. If used in a numeric context, this will be converted to a floating-point numerical value, with rounding, a fate that is best avoided. Therefore, you should prefer to compare inode numbers using eq rather than ==. eq will work fine on inode numbers that are represented numerically, as well as those represented as strings.

一部のプラットフォームでは、inode 番号は perl が整数値として 扱い方を知っているものよりも大きい型になっています。 もし必要なら、inode 番号は、値全体を保存するために 10 進文字列として 返されます。 数値コンテキストで使うと、これは丸めを伴う浮動小数点数に変換され、 できるだけ避けるべき結果になります。 従って、inode 番号の比較には == ではなく eq を使うべきです。 eq は、inode 番号が数値で表現されていても、文字列で表現されていても うまく動作します。

Because the mode contains both the file type and its permissions, you should mask off the file type portion and (s)printf using a "%o" if you want to see the real permissions.

モードにはファイルタイプとその権限の両方が含まれているので、 本当の権限を見たい場合は、(s)printf で "%" を使うことで ファイルタイプをマスクするべきです。

    my $mode = (stat($filename))[2];
    printf "Permissions are %04o\n", $mode & 07777;

In scalar context, stat returns a boolean value indicating success or failure, and, if successful, sets the information associated with the special filehandle _.

スカラコンテキストでは、stat は成功か失敗を表す真偽値を 返し、成功した場合は、特別なファイルハンドル _ に結び付けられた 情報をセットします。

The File::stat module provides a convenient, by-name access mechanism:

File::stat モジュールは、便利な名前によるアクセス機構を提供します。

    use File::stat;
    my $sb = stat($filename);
    printf "File is %s, size is %s, perm %04o, mtime %s\n",
           $filename, $sb->size, $sb->mode & 07777,
           scalar localtime $sb->mtime;

You can import symbolic mode constants (S_IF*) and functions (S_IS*) from the Fcntl module:

モード定数 (S_IF*) と関数 (S_IS*) を Fcntl モジュールから インポートできます。

    use Fcntl ':mode';

    my $mode = (stat($filename))[2];

    my $user_rwx      = ($mode & S_IRWXU) >> 6;
    my $group_read    = ($mode & S_IRGRP) >> 3;
    my $other_execute =  $mode & S_IXOTH;

    printf "Permissions are %04o\n", S_IMODE($mode), "\n";

    my $is_setuid     =  $mode & S_ISUID;
    my $is_directory  =  S_ISDIR($mode);

You could write the last two using the -u and -d operators. Commonly available S_IF* constants are:

最後の二つは -u-d 演算子を使っても書けます。 一般に利用可能な S_IF* 定数は以下のものです。

    # Permissions: read, write, execute, for user, group, others.

    S_IRWXU S_IRUSR S_IWUSR S_IXUSR
    S_IRWXG S_IRGRP S_IWGRP S_IXGRP
    S_IRWXO S_IROTH S_IWOTH S_IXOTH

    # Setuid/Setgid/Stickiness/SaveText.
    # Note that the exact meaning of these is system-dependent.

    S_ISUID S_ISGID S_ISVTX S_ISTXT

    # File types.  Not all are necessarily available on
    # your system.

    S_IFREG S_IFDIR S_IFLNK S_IFBLK S_IFCHR
    S_IFIFO S_IFSOCK S_IFWHT S_ENFMT

    # The following are compatibility aliases for S_IRUSR,
    # S_IWUSR, and S_IXUSR.

    S_IREAD S_IWRITE S_IEXEC

and the S_IF* functions are

一般に利用可能な S_IF* 関数は以下のものです。

    S_IMODE($mode)    the part of $mode containing the permission
                      bits and the setuid/setgid/sticky bits

    S_IFMT($mode)     the part of $mode containing the file type
                      which can be bit-anded with (for example)
                      S_IFREG or with the following functions

    # The operators -f, -d, -l, -b, -c, -p, and -S.

    S_ISREG($mode) S_ISDIR($mode) S_ISLNK($mode)
    S_ISBLK($mode) S_ISCHR($mode) S_ISFIFO($mode) S_ISSOCK($mode)

    # No direct -X operator counterpart, but for the first one
    # the -g operator is often equivalent.  The ENFMT stands for
    # record flocking enforcement, a platform-dependent feature.

    S_ISENFMT($mode) S_ISWHT($mode)

See your native chmod(2) and stat(2) documentation for more details about the S_* constants. To get status info for a symbolic link instead of the target file behind the link, use the lstat function.

S_* 定数に関する詳細についてはネイティブの chmod(2)stat(2) の ドキュメントを参照してください。 リンクの先にあるファイルではなく、シンボリックリンクそのものの情報を 得たい場合は、lstat 関数を使ってください。

Portability issues: "stat" in perlport.

移植性の問題: "stat" in perlport

state VARLIST
state TYPE VARLIST
state VARLIST : ATTRS
state TYPE VARLIST : ATTRS

state declares a lexically scoped variable, just like my. However, those variables will never be reinitialized, contrary to lexical variables that are reinitialized each time their enclosing block is entered. See "Persistent Private Variables" in perlsub for details.

state はちょうど my と同様に、 レキシカルなスコープの変数を宣言します。 しかし、レキシカル変数がブロックに入る毎に再初期化されるのと異なり、 この変数は決して再初期化されません。 詳しくは "Persistent Private Variables" in perlsub を参照してください。

If more than one variable is listed, the list must be placed in parentheses. With a parenthesised list, undef can be used as a dummy placeholder. However, since initialization of state variables in such lists is currently not possible this would serve no purpose.

複数の変数を指定する場合、かっこで囲まなければなりません。 かっこで囲まれたリストでは、undef はダミーの プレースホルダとして使えます。 しかし、そのようなリストでの state 変数の初期化は現在のところできないので、 これは無意味です。

state is available only if the "state" feature is enabled or if it is prefixed with CORE::. The "state" feature is enabled automatically with a use v5.10 (or higher) declaration in the current scope.

state"state" 機能 が有効か CORE:: を 前置した場合にのみ利用可能です。 "state" 機能 は現在のスコープで use v5.10 (またはそれ以上) を宣言した場合自動的に有効になります。

study SCALAR
study

At this time, study does nothing. This may change in the future.

現時点では、study は何もしません。 これは将来変更されるかもしれません。

Prior to Perl version 5.16, it would create an inverted index of all characters that occurred in the given SCALAR (or $_ if unspecified). When matching a pattern, the rarest character from the pattern would be looked up in this index. Rarity was based on some static frequency tables constructed from some C programs and English text.

Perl バージョン 5.16 より前では、 与えられた SCALAR (または指定されていなかった場合は $_)に 現れた全ての文字の転置インデックスを作ります。 パターンにマッチングしたとき、 パターン中の最も頻度の少ない文字がこのインデックスから探されます。 頻度は、C プログラムと英語の文章から構築された静的頻度テーブルを 基にしています。

sub NAME BLOCK
sub NAME (PROTO) BLOCK
sub NAME : ATTRS BLOCK
sub NAME (PROTO) : ATTRS BLOCK

This is subroutine definition, not a real function per se. Without a BLOCK it's just a forward declaration. Without a NAME, it's an anonymous function declaration, so does return a value: the CODE ref of the closure just created.

これはサブルーチン定義であり、本質的には 実際の関数ではありません。 BLOCK なしの場合、これは単に前方宣言です。 NAME なしの場合は、無名関数定義であり、値(作成したブロックの コードリファレンス)を返します: 単にクロージャの CODE リファレンスが 作成されます。

See perlsub and perlref for details about subroutines and references; see attributes and Attribute::Handlers for more information about attributes.

サブルーチンとリファレンスに関する詳細については、perlsubperlref を参照してください; 属性に関する更なる情報については attributesAttribute::Handlers を参照してください。

__SUB__

A special token that returns a reference to the current subroutine, or undef outside of a subroutine.

現在のサブルーチンのリファレンスを返す特殊トークン; サブルーチンの外側では undef

The behaviour of __SUB__ within a regex code block (such as /(?{...})/) is subject to change.

(/(?{...})/ のような) 正規表現コードブロックの中の __SUB__ の振る舞いは変更される予定です。

This token is only available under use v5.16 or the "current_sub" feature. See feature.

このトークンは use v5.16 または "current_sub" 機能 でのみ 利用可能です。 feature を参照してください。

substr EXPR,OFFSET,LENGTH,REPLACEMENT
substr EXPR,OFFSET,LENGTH
substr EXPR,OFFSET

Extracts a substring out of EXPR and returns it. First character is at offset zero. If OFFSET is negative, starts that far back from the end of the string. If LENGTH is omitted, returns everything through the end of the string. If LENGTH is negative, leaves that many characters off the end of the string.

EXPR から、部分文字列を取り出して返します。 最初の文字がオフセット 0 となります。 OFFSET に負の値を設定すると、EXPR の終わりからのオフセットとなります。 LENGTH を省略すると、EXPR の最後まですべてが返されます。 LENGTH が負の値だと、文字列の最後から指定された数だけ文字を取り除きます。

    my $s = "The black cat climbed the green tree";
    my $color  = substr $s, 4, 5;      # black
    my $middle = substr $s, 4, -11;    # black cat climbed the
    my $end    = substr $s, 14;        # climbed the green tree
    my $tail   = substr $s, -4;        # tree
    my $z      = substr $s, -4, 2;     # tr

You can use the substr function as an lvalue, in which case EXPR must itself be an lvalue. If you assign something shorter than LENGTH, the string will shrink, and if you assign something longer than LENGTH, the string will grow to accommodate it. To keep the string the same length, you may need to pad or chop your value using sprintf.

substr を左辺値として 使用することも可能で、その場合には、EXPR が自身左辺値でなければなりません。 LENGTH より短いものを代入したときには、 EXPR は短くなり、LENGTH より長いものを代入したときには、 EXPR はそれに合わせて伸びることになります。 EXPR の長さを一定に保つためには、sprintf を 使って、代入する値の長さを調整することが、必要になるかもしれません。

If OFFSET and LENGTH specify a substring that is partly outside the string, only the part within the string is returned. If the substring is beyond either end of the string, substr returns the undefined value and produces a warning. When used as an lvalue, specifying a substring that is entirely outside the string raises an exception. Here's an example showing the behavior for boundary cases:

OFFSET と LENGTH として文字列の外側を含むような部分文字列が指定されると、 文字列の内側の部分だけが返されます。 部分文字列が文字列の両端の外側の場合、 substr は未定義値を返し、 警告が出力されます。 左辺値として使った場合、文字列の完全に外側を部分文字列として指定すると 例外が発生します。 以下は境界条件の振る舞いを示す例です:

    my $name = 'fred';
    substr($name, 4) = 'dy';         # $name is now 'freddy'
    my $null = substr $name, 6, 2;   # returns "" (no warning)
    my $oops = substr $name, 7;      # returns undef, with warning
    substr($name, 7) = 'gap';        # raises an exception

An alternative to using substr as an lvalue is to specify the replacement string as the 4th argument. This allows you to replace parts of the EXPR and return what was there before in one operation, just as you can with splice.

substr を左辺値として使う 代わりの方法は、置き換える文字列を 4 番目の引数として指定することです。 これにより、EXPR の一部を置き換え、置き換える前が何であったかを返す、 ということを(splice と同様) 1 動作で行えます。

    my $s = "The black cat climbed the green tree";
    my $z = substr $s, 14, 7, "jumped from";    # climbed
    # $s is now "The black cat jumped from the green tree"

Note that the lvalue returned by the three-argument version of substr acts as a 'magic bullet'; each time it is assigned to, it remembers which part of the original string is being modified; for example:

3 引数の substr によって返された 左辺値は「魔法の弾丸」のように振舞うことに注意してください; これが代入される毎に、元の文字列のどの部分が変更されたかが思い出されます; 例えば:

    my $x = '1234';
    for (substr($x,1,2)) {
        $_ = 'a';   print $x,"\n";    # prints 1a4
        $_ = 'xyz'; print $x,"\n";    # prints 1xyz4
        $x = '56789';
        $_ = 'pq';  print $x,"\n";    # prints 5pq9
    }

With negative offsets, it remembers its position from the end of the string when the target string is modified:

負数のオフセットの場合、ターゲット文字列が修正されたときに文字列の末尾からの 位置を覚えます:

    my $x = '1234';
    for (substr($x, -3, 2)) {
        $_ = 'a';   print $x,"\n";    # prints 1a4, as above
        $x = 'abcdefg';
        print $_,"\n";                # prints f
    }

Prior to Perl version 5.10, the result of using an lvalue multiple times was unspecified. Prior to 5.16, the result with negative offsets was unspecified.

バージョン 5.10 より前の Perl では、複数回左辺値を使った場合の結果は 未定義でした。 5.16 より前では、負のオフセットの結果は未定義です。

symlink OLDFILE,NEWFILE

Creates a new filename symbolically linked to the old filename. Returns 1 for success, 0 otherwise. On systems that don't support symbolic links, raises an exception. To check for that, use eval:

NEWFILE として、OLDFILE へのシンボリックリンクを生成します。 成功時には 1 を返し、失敗時には 0 を返します。 シンボリックリンクをサポートしていないシステムでは、 例外が発生します。 これをチェックするには、eval を使用します:

    my $symlink_exists = eval { symlink("",""); 1 };

Portability issues: "symlink" in perlport.

移植性の問題: "symlink" in perlport

syscall NUMBER, LIST

Calls the system call specified as the first element of the list, passing the remaining elements as arguments to the system call. If unimplemented, raises an exception. The arguments are interpreted as follows: if a given argument is numeric, the argument is passed as an int. If not, the pointer to the string value is passed. You are responsible to make sure a string is pre-extended long enough to receive any result that might be written into a string. You can't use a string literal (or other read-only string) as an argument to syscall because Perl has to assume that any string pointer might be written through. If your integer arguments are not literals and have never been interpreted in a numeric context, you may need to add 0 to them to force them to look like numbers. This emulates the syswrite function (or vice versa):

LIST の最初の要素で指定するシステムコールを、残りの要素をその システムコールの引数として呼び出します。 実装されていない場合には、例外が発生します。 引数は、以下のように解釈されます: 引数が数字であれば、int として 引数を渡します。 そうでなければ、文字列値へのポインタが渡されます。 文字列に結果を受け取るときには、その結果を受け取るのに十分なくらいに、 文字列を予め伸ばしておく必要があります。 文字列リテラル(あるいはその他の読み込み専用の文字列)を syscall の引数として使うことはできません; Perl は全ての文字列ポインタは書き込まれると仮定しなければならないからです。 整数引数が、リテラルでなく、数値コンテキストで評価されたことのない ものであれば、数値として解釈されるように、 0 を足しておく必要があるかもしれません。 以下は syswrite 関数(あるいは その逆)をエミュレートします。

    require 'syscall.ph';        # may need to run h2ph
    my $s = "hi there\n";
    syscall(SYS_write(), fileno(STDOUT), $s, length $s);

Note that Perl supports passing of up to only 14 arguments to your syscall, which in practice should (usually) suffice.

Perl は、システムコールに最大 14 個の引数しか渡せませんが、 (普通は)実用上問題はないでしょう。

Syscall returns whatever value returned by the system call it calls. If the system call fails, syscall returns -1 and sets $! (errno). Note that some system calls can legitimately return -1. The proper way to handle such calls is to assign $! = 0 before the call, then check the value of $! if syscall returns -1.

syscall は、呼び出したシステムコールが返した値を返します。 システムコールが失敗すると、syscall-1 を 返し、$!(errno) を設定します。 システムコールが正常に -1 を返す 場合がある ことに注意してください。 このようなシステムコールを正しく扱うには、 $! = 0 をシステムコールの前に実行し、それから syscall-1 を返した時には $! の値を調べてください。

There's a problem with syscall(SYS_pipe()): it returns the file number of the read end of the pipe it creates, but there is no way to retrieve the file number of the other end. You can avoid this problem by using pipe instead.

syscall(&SYS_pipe) には問題があり、作ったパイプの、読み出し側の ファイル番号を返しますが、もう一方のファイル番号を得る方法がありません。 この問題を避けるためには、代わりに pipe を 使ってください。

Portability issues: "syscall" in perlport.

移植性の問題: "syscall" in perlport

sysopen FILEHANDLE,FILENAME,MODE
sysopen FILEHANDLE,FILENAME,MODE,PERMS

Opens the file whose filename is given by FILENAME, and associates it with FILEHANDLE. If FILEHANDLE is an expression, its value is used as the real filehandle wanted; an undefined scalar will be suitably autovivified. This function calls the underlying operating system's open(2) function with the parameters FILENAME, MODE, and PERMS.

FILENAME で与えられたファイル名のファイルをオープンし、 FILEHANDLE と結び付けます。 FILEHANDLE が式の場合、その値は実際の求めているファイルハンドルの名前として 扱われます; 未定義のスカラは適切に自動有効化されます。 この関数呼び出しはシステムの open(2) 関数を FILENAME, MODE, PERMS の 引数で呼び出すことを基礎としています。

Returns true on success and undef otherwise.

成功時は真を、さもなければ undef を返します。

The possible values and flag bits of the MODE parameter are system-dependent; they are available via the standard module Fcntl. See the documentation of your operating system's open(2) syscall to see which values and flag bits are available. You may combine several flags using the |-operator.

MODE パラメータに指定できるフラグビットと値はシステム依存です; これは標準モジュール Fcntl 経由で利用可能です。 どのようなフラグビットと値が利用可能であるかについては、 OS の open(2) システムコールに関する文書を参照してください。 | 演算子を使って複数のフラグを結合することができます。

Some of the most common values are O_RDONLY for opening the file in read-only mode, O_WRONLY for opening the file in write-only mode, and O_RDWR for opening the file in read-write mode.

もっともよく使われる値は、ファイルを読み込み専用で開く O_RDONLY、 ファイルを書き込み専用で開く O_WRONLY、 ファイルを読み書き両用で開く O_RDWR です。

For historical reasons, some values work on almost every system supported by Perl: 0 means read-only, 1 means write-only, and 2 means read/write. We know that these values do not work under OS/390 and on the Macintosh; you probably don't want to use them in new code.

歴史的な理由により、Perl が対応しているほとんどのシステムで使える値が あります:0 は読み込み専用、1 は書き込み専用、2 は読み書き両用を意味します。 OS/390 と Macintosh では動作 しない ことが分かっています; 新しく書くコードではこれらは使わないほうがよいでしょう。

If the file named by FILENAME does not exist and the open call creates it (typically because MODE includes the O_CREAT flag), then the value of PERMS specifies the permissions of the newly created file. If you omit the PERMS argument to sysopen, Perl uses the octal value 0666. These permission values need to be in octal, and are modified by your process's current umask.

FILENAME という名前のファイルが存在せず、(典型的には MODE が O_CREAT フラグを含んでいたために) open 呼び出しがそれを作った場合、 PERMS の値は新しく作られたファイルの権限を指定します。 sysopen の PERMS 引数を省略した場合、 Perl は 8 進数 0666 を使います。 これらの権限は 8 進数である必要があり、プロセスの現在の umask で修正されます。

In many systems the O_EXCL flag is available for opening files in exclusive mode. This is not locking: exclusiveness means here that if the file already exists, sysopen fails. O_EXCL may not work on network filesystems, and has no effect unless the O_CREAT flag is set as well. Setting O_CREAT|O_EXCL prevents the file from being opened if it is a symbolic link. It does not protect against symbolic links in the file's path.

多くのシステムではファイルを排他モードで開くために O_EXCL が 利用可能です。 これはロック ではありません: 排他性というのは既にファイルが 存在していた場合、sysopen が 失敗することを意味します。 O_EXCL はネットワークファイルシステムでは動作せず、 またO_CREAT フラグも有効でない限りは効果がありません。 O_CREAT|O_EXCL をセットすると、これがシンボリックリンクだった場合は ファイルを開くことを妨げます。 これはファイルパス中のシンボリックリンクは守りません。

Sometimes you may want to truncate an already-existing file. This can be done using the O_TRUNC flag. The behavior of O_TRUNC with O_RDONLY is undefined.

既に存在しているファイルを切り詰めたい場合もあるかもしれません。 これは O_TRUNC フラグを使うことで行えます。 O_RDONLYO_TRUNC を同時に指定したときの振る舞いは未定義です。

You should seldom if ever use 0644 as argument to sysopen, because that takes away the user's option to have a more permissive umask. Better to omit it. See umask for more on this.

めったなことでは sysopen の引数に 0644 を指定するべきではないでしょう: ユーザーがより寛大な umask を指定する選択肢を奪うからです。 省略した方がいいです。 これに関するさらなる情報については umask を 参照してください。

Note that under Perls older than 5.8.0, sysopen depends on the fdopen(3) C library function. On many Unix systems, fdopen(3) is known to fail when file descriptors exceed a certain value, typically 255. If you need more file descriptors than that, consider using the POSIX::open function. For Perls 5.8.0 and later, PerlIO is (most often) the default.

5.8.0 より古い Perl では、 sysopen は C の fdopen(3) ライブラリ関数に依存していることに注意してください。 多くの Unix システムでは、fdopen(3) はファイル記述子がある値(例えば 255)を 超えると失敗することが知られています。 これより多くのファイル記述子が必要な場合は、 POSIX::open 関数を使うことを検討してください。 Perl 5.8.0 以降では、(ほぼ確実に) PerlIO がデフォルトです。

See perlopentut for a kinder, gentler explanation of opening files.

ファイルを開くことに関するより親切な説明については perlopentut を 参照してください。

Portability issues: "sysopen" in perlport.

移植性の問題: "sysopen" in perlport

sysread FILEHANDLE,SCALAR,LENGTH,OFFSET
sysread FILEHANDLE,SCALAR,LENGTH

Attempts to read LENGTH bytes of data into variable SCALAR from the specified FILEHANDLE, using read(2). It bypasses buffered IO, so mixing this with other kinds of reads, print, write, seek, tell, or eof can cause confusion because the perlio or stdio layers usually buffer data. Returns the number of bytes actually read, 0 at end of file, or undef if there was an error (in the latter case $! is also set). SCALAR will be grown or shrunk so that the last byte actually read is the last byte of the scalar after the read.

read(2) を用いて、指定した FILEHANDLE から、変数 SCALAR へ、LENGTH バイトの データの読み込みを試みます。 これは、バッファ付き IO ルーチンを通りませんから、他の入力関数, print, write, seek, tell, eof と混ぜて使うと、入力がおかしくなるかも しれません; perlio 層や stdio 層は普通データをバッファリングするからです。 ファイルの最後では 0が、エラー時には undef が、それ以外では実際に 読み込まれたデータの長さが返されます (後者の場合は $! も セットされます)。 実際に読み込んだ最後のバイトが read した後の最後のバイトになるので、 SCALAR は伸び縮みします。

An OFFSET may be specified to place the read data at some place in the string other than the beginning. A negative OFFSET specifies placement at that many characters counting backwards from the end of the string. A positive OFFSET greater than the length of SCALAR results in the string being padded to the required size with "\0" bytes before the result of the read is appended.

OFFSET を指定すると、文字列の先頭以外の場所から読み込みを行なえます。 OFFSET に負の値を指定すると、文字列の最後から逆向きに何文字目かで 位置を指定します。 OFFSET が正の値で、SCALAR の長さよりも大きかった場合、文字列は読み込みの結果が 追加される前に、必要なサイズまで "\0" のバイトでパッディングされます。

There is no syseof() function, which is ok, since eof doesn't work well on device files (like ttys) anyway. Use sysread and check for a return value of 0 to decide whether you're done.

syseof() 関数はありませんが、問題ありません; どちらにしろ eof は (tty のような)デバイスファイルに対してはうまく動作しないからです。 sysread を使って、 返り値が 0 かどうかで最後まで読んだかを判断してください。

Note that if the filehandle has been marked as :utf8, sysread will throw an exception. The :encoding(...) layer implicitly introduces the :utf8 layer. See binmode, open, and the open pragma.

ファイルハンドルが :utf8 であるとマークが付けられていると、 sysread は例外を投げます。 :encoding(...) 層は暗黙のうちに :utf8 層が導入されます。 binmode, open, open プラグマを参照してください。

sysseek FILEHANDLE,POSITION,WHENCE

Sets FILEHANDLE's system position in bytes using lseek(2). FILEHANDLE may be an expression whose value gives the name of the filehandle. The values for WHENCE are 0 to set the new position to POSITION; 1 to set it to the current position plus POSITION; and 2 to set it to EOF plus POSITION, typically negative.

FILEHANDLE のシステム位置を バイト単位lseek(2) を使って設定します。 FILEHANDLE は、実際のファイルハンドル名を与える式でもかまいません。 WHENCE の値が、0 ならば、新しい位置を POSITION の位置へ設定します; 1 ならば、現在位置から POSITION 加えた位置へ設定します; 2 ならば、 EOF から POSITION だけ(普通は負の数です)加えた位置へ、新しい位置を 設定します。

Note the emphasis on bytes: even if the filehandle has been set to operate on characters (for example using the :encoding(UTF-8) I/O layer), the seek, tell, and sysseek family of functions use byte offsets, not character offsets, because seeking to a character offset would be very slow in a UTF-8 file.

バイト単位に対する注意: 例え(例えば :encoding(UTF-8) I/O 層を使うなどして) ファイルハンドルが文字単位で処理するように設定されていたとしても、 seek, tell, sysseek シリーズの関数は 文字オフセットではなくバイトオフセットを使います; 文字オフセットでシークするのは UTF-8 ファイルではとても遅いからです。

sysseek bypasses normal buffered IO, so mixing it with reads other than sysread (for example readline or read), print, write, seek, tell, or eof may cause confusion.

sysseek は普通のバッファ付き IO を バイパスしますので、 sysread 以外の (例えば readlineread の)読み込み、 print, write, seek, tell, eof と混ぜて使うと混乱を引き起こします。

For WHENCE, you may also use the constants SEEK_SET, SEEK_CUR, and SEEK_END (start of the file, current position, end of the file) from the Fcntl module. Use of the constants is also more portable than relying on 0, 1, and 2. For example to define a "systell" function:

WHENCE には、Fcntl モジュールで使われている SEEK_SET, SEEK_CUR, SEEK_END (ファイルの先頭、現在位置、ファイルの最後)という定数を 使うこともできます。 定数の使用は 0, 1, 2 に依存するよりも移植性があります。 例えば "systell" 関数を定義するには:

    use Fcntl 'SEEK_CUR';
    sub systell { sysseek($_[0], 0, SEEK_CUR) }

Returns the new position, or the undefined value on failure. A position of zero is returned as the string "0 but true"; thus sysseek returns true on success and false on failure, yet you can still easily determine the new position.

新しい位置を返します; 失敗したときは未定義値を返します。 位置がゼロの場合は、"0 but true" の文字列として返されます; 従って sysseek は成功時に真を返し、 失敗時に偽を返しますが、簡単に新しい位置を判定できます。

system LIST
system PROGRAM LIST

Does exactly the same thing as exec, except that a fork is done first and the parent process waits for the child process to exit. Note that argument processing varies depending on the number of arguments. If there is more than one argument in LIST, or if LIST is an array with more than one value, starts the program given by the first element of the list with arguments given by the rest of the list. If there is only one scalar argument, the argument is checked for shell metacharacters, and if there are any, the entire argument is passed to the system's command shell for parsing (this is /bin/sh -c on Unix platforms, but varies on other platforms). If there are no shell metacharacters in the argument, it is split into words and passed directly to execvp, which is more efficient. On Windows, only the system PROGRAM LIST syntax will reliably avoid using the shell; system LIST, even with more than one element, will fall back to the shell if the first spawn fails.

exec とほとんど同じですが、まず fork を行ない、 親プロセスではチャイルドプロセスが終了するのを wait します。 exec の項で述べたように、引数の処理は、引数の数によって異なることに 注意してください。 LIST に複数の引数がある場合、または LIST が複数の要素からなる配列の場合、 リストの最初の要素で与えられるプログラムを、リストの残りの要素を引数として 起動します。 スカラの引数が一つだけの場合、引数はシェルのメタ文字をチェックされ、もし あればパースのために引数全体がシステムコマンドシェル (これは Unix プラットフォームでは /bin/sh -c ですが、他のプラットフォームでは 異なります)に渡されます。 シェルのメタ文字がなかった場合、引数は単語に分解されて直接 execvp に 渡されます; この方がより効率的です。 Windows では、system PROGRAM LIST 構文のみが安定してシェルの使用を 回避します; system LIST は、2 要素以上でも、最初の spawn が失敗すると シェルにフォールバックします。

Perl will attempt to flush all files opened for output before any operation that may do a fork, but this may not be supported on some platforms (see perlport). To be safe, you may need to set $| ($AUTOFLUSH in English) or call the autoflush method of IO::Handle on any open handles.

v5.6.0 から、Perl は書き込み用に開いている全てのファイルに対して fork を行う前にフラッシュしようとしますが、これに対応していない プラットフォームもあります(perlport を参照してください)。 安全のために、$| (English モジュールでは $AUTOFLUSH) をセットするか、全ての開いているハンドルに対して IO::Handleautoflush メソッドを 呼び出す必要があるかもしれません。

The return value is the exit status of the program as returned by the wait call. To get the actual exit value, shift right by eight (see below). See also exec. This is not what you want to use to capture the output from a command; for that you should use merely backticks or qx//, as described in "`STRING`" in perlop. Return value of -1 indicates a failure to start the program or an error of the wait(2) system call (inspect $! for the reason).

返り値は、wait が返すプログラムの exit 状態です。 実際の exit 値を得るには 右に 8 ビットシフトしてください(後述)。 exec も参照してください。 これはコマンドからの出力を捕らえるために使うものではありません; そのような用途には、"`STRING`" in perlop に記述されている 逆クォートや qx// を使用してください。 -1 の返り値はプログラムを開始させることに失敗したか、wait(2) システムコールがエラーを出したことを示します (理由は $! を調べてください)。

If you'd like to make system (and many other bits of Perl) die on error, have a look at the autodie pragma.

もし system (及び Perl のその他の多くの部分) でエラー時に die したいなら、autodie プラグマを見てみてください。

Like exec, system allows you to lie to a program about its name if you use the system PROGRAM LIST syntax. Again, see exec.

exec と同様に、system でも system PROGRAM LIST の文法を使うことで、プログラムに対してその名前を 嘘をつくことができます。 再び、exec を参照してください。

Since SIGINT and SIGQUIT are ignored during the execution of system, if you expect your program to terminate on receipt of these signals you will need to arrange to do so yourself based on the return value.

SIGINTSIGQUITsystem の実行中は無視されるので、 これらのシグナルを受信して終了させることを想定したプログラムの場合、 返り値を利用するように変更する必要があります。

    my @args = ("command", "arg1", "arg2");
    system(@args) == 0
        or die "system @args failed: $?";

If you'd like to manually inspect system's failure, you can check all possible failure modes by inspecting $? like this:

system の失敗を手動で検査したいなら、以下のように $? を調べることで、全ての失敗の可能性をチェックできます:

    if ($? == -1) {
        print "failed to execute: $!\n";
    }
    elsif ($? & 127) {
        printf "child died with signal %d, %s coredump\n",
            ($? & 127),  ($? & 128) ? 'with' : 'without';
    }
    else {
        printf "child exited with value %d\n", $? >> 8;
    }

Alternatively, you may inspect the value of ${^CHILD_ERROR_NATIVE} with the W*() calls from the POSIX module.

または、POSIX モジュールの W*() 呼び出しを使って ${^CHILD_ERROR_NATIVE} の値を 調べることもできます。

When system's arguments are executed indirectly by the shell, results and return codes are subject to its quirks. See "`STRING`" in perlop and exec for details.

system の引数がシェルによって間接的に実行された場合、 結果と返り値はシェルの癖によって変更されることがあります。 詳細については "`STRING`" in perlopexec を 参照してください。

Since system does a fork and wait it may affect a SIGCHLD handler. See perlipc for details.

systemforkwait を行うので、 SIGCHLD ハンドラの影響を受けます。 詳しくは perlipc を参照してください。

Portability issues: "system" in perlport.

移植性の問題: "system" in perlport

syswrite FILEHANDLE,SCALAR,LENGTH,OFFSET
syswrite FILEHANDLE,SCALAR,LENGTH
syswrite FILEHANDLE,SCALAR

Attempts to write LENGTH bytes of data from variable SCALAR to the specified FILEHANDLE, using write(2). If LENGTH is not specified, writes whole SCALAR. It bypasses buffered IO, so mixing this with reads (other than sysread)), print, write, seek, tell, or eof may cause confusion because the perlio and stdio layers usually buffer data. Returns the number of bytes actually written, or undef if there was an error (in this case the errno variable $! is also set). If the LENGTH is greater than the data available in the SCALAR after the OFFSET, only as much data as is available will be written.

write(2) を使って、指定した FILEHANDLEへ、変数 SCALAR から、LENGTH バイトの データの書き込みを試みます。 LENGTH が指定されなかった場合、 SCALAR 全体を書き込みます。 これは、バッファ付き IO ルーチンを通りませんから、他の入力関数 (sysread 以外), print, write, seek, tell, eof と混ぜて使うと、出力がおかしくなるかもしれません; perlio 層と stdio 層は普通データをバッファリングするからです。 実際に読み込まれたデータの長さか、エラー時には undef が 返されます(この場合エラー変数 $! もセットされます)。 LENGTH が OFFSET 以降の SCALAR の利用可能なデータより大きかった場合、 利用可能なデータのみが書き込まれます。

An OFFSET may be specified to write the data from some part of the string other than the beginning. A negative OFFSET specifies writing that many characters counting backwards from the end of the string. If SCALAR is of length zero, you can only use an OFFSET of 0.

OFFSET を指定すると、SCALAR の先頭以外の場所から、 データを取り出して、書き込みを行なうことができます。 OFFSET に負の値を指定すると、文字列の最後から逆向きに数えて 何バイト目から書き込むかを示します。 SCALAR の長さが 0 の場合、OFFSET は 0 のみ使用できます。

WARNING: If the filehandle is marked :utf8, syswrite will raise an exception. The :encoding(...) layer implicitly introduces the :utf8 layer. Alternately, if the handle is not marked with an encoding but you attempt to write characters with code points over 255, raises an exception. See binmode, open, and the open pragma.

警告: ファイルハンドルが :utf8 であるとマークが付けられていると、 syswrite は例外を投げます。 :encoding(...) 層は暗黙のうちに :utf8 層が導入されます。 または、もしハンドルにエンコーディングが記録されていない状態で 255 を超える符号位置の文字を書き込もうとすると、例外が発生します。 binmode, open, open プラグマを参照してください。

tell FILEHANDLE
tell

Returns the current position in bytes for FILEHANDLE, or -1 on error. FILEHANDLE may be an expression whose value gives the name of the actual filehandle. If FILEHANDLE is omitted, assumes the file last read.

FILEHANDLE の現在の位置を バイト数で 返します; エラーの場合は -1 を 返します。 FILEHANDLE は、実際のファイルハンドル名を示す式でもかまいません。 FILEHANDLE が省略された場合には、最後に読み込みを行なったファイルについて 調べます。

Note the emphasis on bytes: even if the filehandle has been set to operate on characters (for example using the :encoding(UTF-8) I/O layer), the seek, tell, and sysseek family of functions use byte offsets, not character offsets, because seeking to a character offset would be very slow in a UTF-8 file.

バイト単位に対する注意: 例え(例えば :encoding(UTF-8) I/O 層を使うなどして) ファイルハンドルが文字単位で処理するように設定されていたとしても、 seek, tell, sysseek シリーズの関数は 文字オフセットではなくバイトオフセットを使います; 文字オフセットでシークするのは UTF-8 ファイルではとても遅いからです。

The return value of tell for the standard streams like the STDIN depends on the operating system: it may return -1 or something else. tell on pipes, fifos, and sockets usually returns -1.

STDIN のような標準ストリームに対する tell の返り値は OS に依存します: -1 やその他の値が返ってくるかもしれません。 パイプ、FIFO、ソケットに対して tell を使うと、普通は -1 が返ります。

There is no systell function. Use sysseek($fh, 0, 1) for that.

systell 関数はありません。 代わりに sysseek($fh, 0, 1) を 使ってください。

Do not use tell (or other buffered I/O operations) on a filehandle that has been manipulated by sysread, syswrite, or sysseek. Those functions ignore the buffering, while tell does not.

sysread, syswrite, sysseek で操作された ファイルハンドルに tell (またはその他のバッファリング I/O 操作) を使わないでください。 これらの関数はバッファリングを無視しますが、tell は 違います。

telldir DIRHANDLE

Returns the current position of the readdir routines on DIRHANDLE. Value may be given to seekdir to access a particular location in a directory. telldir has the same caveats about possible directory compaction as the corresponding system library routine.

DIRHANDLE 上の readdir ルーチンに対する現在位置を 返します。 値は、そのディレクトリで特定の位置をアクセスするため、 seekdir に渡すことができます。 telldir は同名のシステムライブラリルーチンと同じく、 ディレクトリ縮小時の問題が考えられます。

tie VARIABLE,CLASSNAME,LIST

This function binds a variable to a package class that will provide the implementation for the variable. VARIABLE is the name of the variable to be enchanted. CLASSNAME is the name of a class implementing objects of correct type. Any additional arguments are passed to the appropriate constructor method of the class (meaning TIESCALAR, TIEHANDLE, TIEARRAY, or TIEHASH). Typically these are arguments such as might be passed to the dbm_open(3) function of C. The object returned by the constructor is also returned by the tie function, which would be useful if you want to access other methods in CLASSNAME.

この関数は、変数を、その変数の実装を行なうクラスと結び付けます。 VARIABLE は、魔法をかける変数の名前です。 CLASSNAME は、正しい型のオブジェクトを実装するクラスの名前です。 他に引数があれば、そのクラスの適切なコンストラクタメソッドに渡されます (つまり TIESCALAR, TIEHANDLE, TIEARRAY, TIEHASH)。 通常、これらは、C の dbm_open(3) などの関数に渡す引数となります。 コンストラクタで返されるオブジェクトはまた tie 関数でも返されます; これは CLASSNAME の他のメソッドにアクセスしたいときに便利です。

Note that functions such as keys and values may return huge lists when used on large objects, like DBM files. You may prefer to use the each function to iterate over such. Example:

DBM ファイルのような大きなオブジェクトでは、keysvalues のような関数は、大きなリストを返す可能性があります。 そのような場合では、each 関数を使って繰り返しを行なった方が よいかもしれません。 例:

    # print out history file offsets
    use NDBM_File;
    tie(my %HIST, 'NDBM_File', '/usr/lib/news/history', 1, 0);
    while (my ($key,$val) = each %HIST) {
        print $key, ' = ', unpack('L', $val), "\n";
    }

A class implementing a hash should have the following methods:

ハッシュを実装するクラスでは、次のようなメソッドを用意します:

    TIEHASH classname, LIST
    FETCH this, key
    STORE this, key, value
    DELETE this, key
    CLEAR this
    EXISTS this, key
    FIRSTKEY this
    NEXTKEY this, lastkey
    SCALAR this
    DESTROY this
    UNTIE this

A class implementing an ordinary array should have the following methods:

通常の配列を実装するクラスでは、次のようなメソッドを用意します:

    TIEARRAY classname, LIST
    FETCH this, key
    STORE this, key, value
    FETCHSIZE this
    STORESIZE this, count
    CLEAR this
    PUSH this, LIST
    POP this
    SHIFT this
    UNSHIFT this, LIST
    SPLICE this, offset, length, LIST
    EXTEND this, count
    DELETE this, key
    EXISTS this, key
    DESTROY this
    UNTIE this

A class implementing a filehandle should have the following methods:

ファイルハンドルを実装するクラスでは、次のようなメソッドを用意します:

    TIEHANDLE classname, LIST
    READ this, scalar, length, offset
    READLINE this
    GETC this
    WRITE this, scalar, length, offset
    PRINT this, LIST
    PRINTF this, format, LIST
    BINMODE this
    EOF this
    FILENO this
    SEEK this, position, whence
    TELL this
    OPEN this, mode, LIST
    CLOSE this
    DESTROY this
    UNTIE this

A class implementing a scalar should have the following methods:

スカラ変数を実装するクラスでは、次のようなメソッドを用意します:

    TIESCALAR classname, LIST
    FETCH this,
    STORE this, value
    DESTROY this
    UNTIE this

Not all methods indicated above need be implemented. See perltie, Tie::Hash, Tie::Array, Tie::Scalar, and Tie::Handle.

上記の全てのメソッドを実装する必要はありません。 perltie, Tie::Hash, Tie::Array, Tie::Scalar, Tie::Handle を参照してください。

Unlike dbmopen, the tie function will not use or require a module for you; you need to do that explicitly yourself. See DB_File or the Config module for interesting tie implementations.

dbmopen と違い、 tie 関数はモジュールを use したり require したりしません; 自分で明示的に行う必要があります。 tie の興味深い実装については DB_FileConfig モジュールを参照してください。

For further details see perltie, tied.

更なる詳細については perltietied を 参照してください。

tied VARIABLE

Returns a reference to the object underlying VARIABLE (the same value that was originally returned by the tie call that bound the variable to a package.) Returns the undefined value if VARIABLE isn't tied to a package.

VARIABLE の基となるオブジェクトへのリファレンスを返します (変数をパッケージに結びつけるために tie 呼び出しをしたときの 返り値と同じものです)。 VARIABLE がパッケージと結び付けられていない場合は未定義値を返します。

time

Returns the number of non-leap seconds since whatever time the system considers to be the epoch, suitable for feeding to gmtime and localtime. On most systems the epoch is 00:00:00 UTC, January 1, 1970; a prominent exception being Mac OS Classic which uses 00:00:00, January 1, 1904 in the current local time zone for its epoch.

gmtimelocaltime への入力形式に 合っている、システムが紀元と考える時点からの連続秒数を返します。 ほとんどのシステムでは紀元は UTC 1970 年 1 月 1 日 00:00:00 です; 特徴的な例外としては、古い Mac OS ではローカルタイムゾーンの 1904 年 1 月 1 日 00:00:00 を紀元として使います。

For measuring time in better granularity than one second, use the Time::HiRes module from Perl 5.8 onwards (or from CPAN before then), or, if you have gettimeofday(2), you may be able to use the syscall interface of Perl. See perlfaq8 for details.

1 秒よりも細かい時間を計測するためには、Perl 5.8 以降(それ以前では CPANから)の Time::HiRes モジュールを使うか、 gettimeofday(2) があるなら、Perl の syscall インターフェースを使ってください。 詳しくは perlfaq8 を参照してください。

For date and time processing look at the many related modules on CPAN. For a comprehensive date and time representation look at the DateTime module.

日付と時刻の処理は、多くの関連するモジュールが CPAN にあります。 包括的な日付と時刻の表現については、CPAN の DateTime モジュールを 参照してください。

times

Returns a four-element list giving the user and system times in seconds for this process and any exited children of this process.

現プロセス及び終了したその子プロセスに対する、ユーザ時間とシステム時間を 秒で示した、4 要素のリスト値を返します。

    my ($user,$system,$cuser,$csystem) = times;

In scalar context, times returns $user.

スカラコンテキストでは、times$user を返します。

Children's times are only included for terminated children.

子プロセスに対する times は、終了した子プロセスのみ含められます。

Portability issues: "times" in perlport.

移植性の問題: "times" in perlport

tr///

The transliteration operator. Same as y///. See "Quote-Like Operators" in perlop.

文字変換演算子です。 y/// と同じです。 "Quote-Like Operators" in perlop を参照してください。

truncate FILEHANDLE,LENGTH
truncate EXPR,LENGTH

Truncates the file opened on FILEHANDLE, or named by EXPR, to the specified length. Raises an exception if truncate isn't implemented on your system. Returns true if successful, undef on error.

FILEHANDLE 上にオープンされたファイルか、EXPR で名前を表わしたファイルを、 指定した長さに切り詰めます。 システム上に truncate が実装されていなければ、例外が発生します。 成功すれば真を、エラー時には undef を返します。

The behavior is undefined if LENGTH is greater than the length of the file.

LENGTH がファイルの長さより大きい場合の振る舞いは未定義です。

The position in the file of FILEHANDLE is left unchanged. You may want to call seek before writing to the file.

FILEHANDLE のファイルの位置は変わりません。 ファイルに書き込む前に seek を 呼び出したいかもしれません。

Portability issues: "truncate" in perlport.

移植性の問題: "truncate" in perlport

uc EXPR
uc

Returns an uppercased version of EXPR. This is the internal function implementing the \U escape in double-quoted strings. It does not attempt to do titlecase mapping on initial letters. See ucfirst for that.

EXPR を大文字に変換したものを返します。 これは、ダブルクォート文字列における、\U エスケープを 実装する内部関数です。 先頭文字の タイトル文字マッピングは試みません。 このためには ucfirst を参照してください。

If EXPR is omitted, uses $_.

EXPR が省略されると、$_ を使います。

This function behaves the same way under various pragmas, such as in a locale, as lc does.

この関数は、ロケールのようなさまざまなプラグマの影響下では、 lc と同様に振る舞います。

ucfirst EXPR
ucfirst

Returns the value of EXPR with the first character in uppercase (titlecase in Unicode). This is the internal function implementing the \u escape in double-quoted strings.

最初の文字だけを大文字にした、EXPR を返します (Unicode では titlecase)。 これは、ダブルクォート文字列における、\u エスケープを 実装する内部関数です。

If EXPR is omitted, uses $_.

EXPR が省略されると、$_ を使います。

This function behaves the same way under various pragmas, such as in a locale, as lc does.

この関数は、ロケールのようなさまざまなプラグマの影響下では、 lc と同様に振る舞います。

umask EXPR
umask

Sets the umask for the process to EXPR and returns the previous value. If EXPR is omitted, merely returns the current umask.

現在のプロセスの umask を EXPR に設定し、以前の値を返します。 EXPR が省略されると、単にその時点の umask の値を返します。

The Unix permission rwxr-x--- is represented as three sets of three bits, or three octal digits: 0750 (the leading 0 indicates octal and isn't one of the digits). The umask value is such a number representing disabled permissions bits. The permission (or "mode") values you pass mkdir or sysopen are modified by your umask, so even if you tell sysopen to create a file with permissions 0777, if your umask is 0022, then the file will actually be created with permissions 0755. If your umask were 0027 (group can't write; others can't read, write, or execute), then passing sysopen 0666 would create a file with mode 0640 (because 0666 &~ 027 is 0640).

Unix パーミッション rwxr-x--- は 3 ビットの三つの組、 または 3 桁の 8 進数として表現されます: 0750 (先頭の 0 は 8 進数を意味し、実際の値ではありません)。 umask の値は無効にするパーミッションビットのこのような 数値表現です。 mkdirsysopen で渡されたパーミッション (または「モード」)の値は umask で修正され、たとえ sysopen0777 のパーミッションで ファイルを作るように指定しても、umask が 0022 なら、 結果としてファイルは 0755 のパーミッションで作成されます。 umask0027 (グループは書き込めない; その他は読み込み、 書き込み、実行できない) のとき sysopen0666 を渡すと、 ファイルはモード 0640 (なぜなら 0666 &~ 0270640)で作成されます。

Here's some advice: supply a creation mode of 0666 for regular files (in sysopen) and one of 0777 for directories (in mkdir) and executable files. This gives users the freedom of choice: if they want protected files, they might choose process umasks of 022, 027, or even the particularly antisocial mask of 077. Programs should rarely if ever make policy decisions better left to the user. The exception to this is when writing files that should be kept private: mail files, web browser cookies, .rhosts files, and so on.

以下は助言です: 作成モードとして、 (sysopen による)通常ファイルでは 0666 を、(mkdir による)ディレクトリでは 0777 を指定しましょう。 これにより、ユーザーに選択の自由を与えます: もしファイルを守りたいなら、 プロセスの umask として 022, 027, あるいは特に非社交的な 077 を選択できます。 プログラムがユーザーより適切なポリシー選択ができることは稀です。 例外は、プライベートに保つべきファイル(メール、ウェブブラウザのクッキー、 .rhosts ファイルなど)を書く場合です。

If umask(2) is not implemented on your system and you are trying to restrict access for yourself (i.e., (EXPR & 0700) > 0), raises an exception. If umask(2) is not implemented and you are not trying to restrict access for yourself, returns undef.

umask(2) が実装されていないシステムで、自分自身 へのアクセスを 制限しようとした(つまり (EXPR & 0700) > 0)場合、例外が発生します。 umask(2) が実装されていないシステムで、自分自身へのアクセスは 制限しようとしなかった場合、undef を返します。

Remember that a umask is a number, usually given in octal; it is not a string of octal digits. See also oct, if all you have is a string.

umask は通常 8 進数で与えられる数値であることを忘れないでください; 8 進数の 文字列 ではありません。 文字列しかない場合、 oct も参照してください。

Portability issues: "umask" in perlport.

移植性の問題: "umask" in perlport

undef EXPR
undef

Undefines the value of EXPR, which must be an lvalue. Use only on a scalar value, an array (using @), a hash (using %), a subroutine (using &), or a typeglob (using *). Saying undef $hash{$key} will probably not do what you expect on most predefined variables or DBM list values, so don't do that; see delete. Always returns the undefined value. You can omit the EXPR, in which case nothing is undefined, but you still get an undefined value that you could, for instance, return from a subroutine, assign to a variable, or pass as a parameter. Examples:

左辺値である EXPR の値を未定義にします。 スカラ値、(@ を使った)配列、(% を使った)ハッシュ、(& を使った) サブルーチン、(* を使った)型グロブだけに使用します。 特殊変数や DBM リスト値に undef $hash{$key} などとしても おそらく期待通りの結果にはなりませんから、しないでください; delete を参照してください。 常に未定義値を返します。 EXPR は省略することができ、その場合には何も未定義にされませんが 未定義値は返されますので、それをたとえば、 サブルーチンの返り値、変数への割り当て、引数などとして使うことができます。 例:

    undef $foo;
    undef $bar{'blurfl'};      # Compare to: delete $bar{'blurfl'};
    undef @ary;
    undef %hash;
    undef &mysub;
    undef *xyz;       # destroys $xyz, @xyz, %xyz, &xyz, etc.
    return (wantarray ? (undef, $errmsg) : undef) if $they_blew_it;
    select undef, undef, undef, 0.25;
    my ($x, $y, undef, $z) = foo();    # Ignore third value returned

Note that this is a unary operator, not a list operator.

これはリスト演算子ではなく、単項演算子であることに注意してください。

unlink LIST
unlink

Deletes a list of files. On success, it returns the number of files it successfully deleted. On failure, it returns false and sets $! (errno):

LIST に含まれるファイルを削除します。 成功時は削除に成功したファイルの数を返します。 失敗時は偽を返して $! (error) をセットします:

    my $unlinked = unlink 'a', 'b', 'c';
    unlink @goners;
    unlink glob "*.bak";

On error, unlink will not tell you which files it could not remove. If you want to know which files you could not remove, try them one at a time:

エラーの場合、unlink はどのファイルが削除できなかったかを 知らせません。 どのファイルが削除できなかったかを知りたい場合は、一つずつ削除してください:

     foreach my $file ( @goners ) {
         unlink $file or warn "Could not unlink $file: $!";
     }

Note: unlink will not attempt to delete directories unless you are superuser and the -U flag is supplied to Perl. Even if these conditions are met, be warned that unlinking a directory can inflict damage on your filesystem. Finally, using unlink on directories is not supported on many operating systems. Use rmdir instead.

注: スーパーユーザ権限で、Perl に -U を付けて実行した場合でなければ、 unlink はディレクトリを削除しようとすることはありません。 この条件にあう場合にも、ディレクトリの削除は、 ファイルシステムに多大な損害を与える可能性があります。 最後に、unlink をディレクトリに使うのはほとんどの OS では 対応していません。 代わりに rmdir を使ってください。

If LIST is omitted, unlink uses $_.

LIST が省略されると、unlink$_ を 使います。

unpack TEMPLATE,EXPR
unpack TEMPLATE

unpack does the reverse of pack: it takes a string and expands it out into a list of values. (In scalar context, it returns merely the first value produced.)

unpackpack の逆を 行ないます: 構造体を表わす文字列をとり、 リスト値に展開し、その配列値を返します。 (スカラコンテキストでは、単に最初の値を返します。)

If EXPR is omitted, unpacks the $_ string. See perlpacktut for an introduction to this function.

EXPR が省略されると、$_ の文字列を unpack します。 この関数の説明については perlpacktut を参照してください。

The string is broken into chunks described by the TEMPLATE. Each chunk is converted separately to a value. Typically, either the string is a result of pack, or the characters of the string represent a C structure of some kind.

文字列は TEMPLATE で示された固まりに分割されます。 それぞれの固まりは別々に値に変換されます。 典型的には、文字列は pack の結果あるいはある種の C の構造体の文字列表現の文字列です。

The TEMPLATE has the same format as in the pack function. Here's a subroutine that does substring:

TEMPLATE は、pack 関数と同じフォーマットを使います。 部分文字列を取り出すうサブルーチンの例を示します:

    sub substr {
        my ($what, $where, $howmuch) = @_;
        unpack("x$where a$howmuch", $what);
    }

and then there's

これもそうです。

    sub ordinal { unpack("W",$_[0]); } # same as ord()

In addition to fields allowed in pack, you may prefix a field with a %<number> to indicate that you want a <number>-bit checksum of the items instead of the items themselves. Default is a 16-bit checksum. The checksum is calculated by summing numeric values of expanded values (for string fields the sum of ord($char) is taken; for bit fields the sum of zeroes and ones).

pack で利用可能なフィールドの他に、 フィールドの前に %<数値> というものを付けて、 項目自身の代わりに、その項目の <数値>-ビットのチェックサムを 計算させることができます。 デフォルトは、16-ビットチェックサムです。 チェックサムは展開された値の数値としての値の合計 (文字列フィールドの場合は ord($char) の合計; ビットフィールドの場合は 0 と 1 の合計) が用いられます。

For example, the following computes the same number as the System V sum program:

たとえば、以下のコードは System V の sum プログラムと同じ値を計算します。

    my $checksum = do {
        local $/;  # slurp!
        unpack("%32W*", readline) % 65535;
    };

The following efficiently counts the number of set bits in a bit vector:

以下は、効率的にビットベクターの設定されているビットを 数えるものです。

    my $setbits = unpack("%32b*", $selectmask);

The p and P formats should be used with care. Since Perl has no way of checking whether the value passed to unpack corresponds to a valid memory location, passing a pointer value that's not known to be valid is likely to have disastrous consequences.

pP は注意深く使うべきです。 Perl は unpack に渡された値が有効なメモリ位置を 指しているかどうかを確認する方法がないので、有効かどうかわからない ポインタ値を渡すと悲惨な結果を引き起こすかもしれません。

If there are more pack codes or if the repeat count of a field or a group is larger than what the remainder of the input string allows, the result is not well defined: the repeat count may be decreased, or unpack may produce empty strings or zeros, or it may raise an exception. If the input string is longer than one described by the TEMPLATE, the remainder of that input string is ignored.

多くの pack コードがある場合や、フィールドやグループの繰り返し回数が 入力文字列の残りより大きい場合、結果は未定義です: 繰り返し回数が減らされる場合もありますし、 unpack が空文字列や 0 を 返すこともありますし、例外が発生します。 もし入力文字列が TEMPLATE で表現されているものより大きい場合、 入力文字列の残りは無視されます。

See pack for more examples and notes.

さらなる例と注意に関しては pack を参照してください。

unshift ARRAY,LIST

Does the opposite of a shift. Or the opposite of a push, depending on how you look at it. Prepends list to the front of the array and returns the new number of elements in the array.

shift の逆操作を行ないます。 見方を変えれば、push の逆操作とも考えられます。 LIST を ARRAY の先頭に入れて、新しくできた配列の要素の数を返します。

    unshift(@ARGV, '-e') unless $ARGV[0] =~ /^-/;

Note the LIST is prepended whole, not one element at a time, so the prepended elements stay in the same order. Use reverse to do the reverse.

LIST は、はらばらにではなく、一度に登録されるので、順番はそのままです。 逆順に登録するには、reverse を使ってください。

Starting with Perl 5.14, an experimental feature allowed unshift to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.

Perl 5.14 から、unshift がスカラ式を 取ることが出来るという実験的機能がありました。 この実験は失敗と見なされ、Perl 5.24 で削除されました。

untie VARIABLE

Breaks the binding between a variable and a package. (See tie.) Has no effect if the variable is not tied.

変数とパッケージの間の結合を解きます。 (tie を参照してください。) 結合されていない場合は何も起きません。

use Module VERSION LIST
use Module VERSION
use Module LIST
use Module
use VERSION

Imports some semantics into the current package from the named module, generally by aliasing certain subroutine or variable names into your package. It is exactly equivalent to

指定したモジュールから、現在のパッケージにさまざまな内容をインポートします; 多くは、パッケージのサブルーチン名や、変数名に別名を付けることで、 実現されています。 これは、以下は等価ですが:

    BEGIN { require Module; Module->import( LIST ); }

except that Module must be a bareword. The importation can be made conditional by using the if module.

Module が 裸の単語でなければならない ことを除けば、です。 インポートは、if を使って条件付きで行うことができます。

In the use VERSION form, VERSION may be either a v-string such as v5.24.1, which will be compared to $^V (aka $PERL_VERSION), 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; Perl will not attempt to parse the rest of the file. Compare with require, which can do a similar check at run time. Symmetrically, no VERSION allows you to specify that you want a version of Perl older than the specified one.

use VERSION の形式では、VERSION は v5.24.1 のような v-文字列 ($^V (またの名を $PERL_VERSION) と比較されます) か、5.024001 の形の数値形式 ($] と比較されます) で 指定します。 VERSION が Perl の現在のバージョンより大きいと、例外が発生します; Perl はファイルの残りを読み込みません。 require と似ていますが、これは実行時に チェックされます。 対称的に、no VERSION は指定されたバージョンより古いバージョンの Perl で 動作させたいことを意味します。

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

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

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

This is often useful if you need to check the current Perl version before useing library modules that won't work with older versions of Perl. (We try not to do this more than we have to.)

これは古いバージョンの Perl で動かなくなったライブラリモジュールを use する前に、現在の Perl のバージョンを 調べたい場合に有用です。 (我々は必要な場合以外にそのようなことがないように努力していますが。)

use VERSION also lexically enables all features available in the requested version as defined by the feature pragma, disabling any features not in the requested version's feature bundle. See feature. Similarly, if the specified Perl version is greater than or equal to 5.12.0, strictures are enabled lexically as with use strict. Any explicit use of use strict or no strict overrides use VERSION, even if it comes before it. Later use of use VERSION will override all behavior of a previous use VERSION, possibly removing the strict and feature added by use VERSION. use VERSION does not load the feature.pm or strict.pm files.

use VERSION は、feature プラグマで定義されたように、指定された バージョンで利用可能な全ての機能を有効にし、指定されたバージョンの機能の 束にない機能をレキシカルに無効にします。 feature を参照してください。 同様に、指定された Perl のバージョンが 5.12.0 以上の場合、 制限は use strict と同様にレキシカルに有効になります。 明示的に use strictno strict を使うと、例え先に 指定されていたとしても、use VERSION を上書きします。 後から使った use VERSION は先の use VERSION の全ての振る舞いを上書きするので、 use VERSION によって追加された strictfeature を 削除することがあります。 use VERSIONfeature.pmstrict.pm ファイルは読み込みません。

The BEGIN forces the require and import to happen at compile time. The require makes sure the module is loaded into memory if it hasn't been yet. The import is not a builtin; it's just an ordinary static method call into the Module package to tell the module to import the list of features back into the current package. The module can implement its import method any way it likes, though most modules just choose to derive their import method via inheritance from the Exporter class that is defined in the Exporter module. See Exporter. If no import method can be found, then the call is skipped, even if there is an AUTOLOAD method.

BEGIN によって、requireimport は、コンパイル時に 実行されることになります。 require は、モジュールがまだメモリに ロードされていなければ、ロードします。 import は、組込みの関数ではありません; さまざまな機能を 現在のパッケージにインポートするように Module パッケージに伝えるために 呼ばれる、通常の静的メソッドです。 モジュール側では、import メソッドをどのようにでも 実装することができますが、多くのモジュールでは、 Exporter モジュールで定義された、 Exporter クラスからの継承によって、import メソッドを 行なうようにしています。 Exporterモジュールを参照してください。 importメソッドが見つからなかった場合、AUTOLOAD メソッドが あったとしても呼び出しはスキップされます。

If you do not want to call the package's import method (for instance, to stop your namespace from being altered), explicitly supply the empty list:

パッケージの import メソッドを呼び出したくない場合(例えば、 名前空間を変更したくない場合など)は、明示的に空リストを指定してください:

    use Module ();

That is exactly equivalent to

これは以下と完全に等価です:

    BEGIN { require Module }

If the VERSION argument is present between Module and LIST, then the use will call the VERSION method in class Module with the given version as an argument:

Module と LIST の間に VERSION 引数がある場合、 use は Module クラスの VERSION メソッドを、与えられたバージョンを引数として呼び出します:

    use Module 12.34;

is equivalent to:

は以下と等価です:

    BEGIN { require Module; Module->VERSION(12.34) }

The default VERSION method, inherited from the UNIVERSAL class, croaks if the given version is larger than the value of the variable $Module::VERSION.

デフォルトの default VERSION メソッド は、 UNIVERSAL クラスから継承したもので、 与えられたバージョンが 変数 $Module::VERSION の値より大きい場合に 警告を出します。

The VERSION argument cannot be an arbitrary expression. It only counts as a VERSION argument if it is a version number literal, starting with either a digit or v followed by a digit. Anything that doesn't look like a version literal will be parsed as the start of the LIST. Nevertheless, many attempts to use an arbitrary expression as a VERSION argument will appear to work, because Exporter's import method handles numeric arguments specially, performing version checks rather than treating them as things to export.

VERSION 引数は任意の式ではありません。 VERSION 引数が数値または v に引き続いて数値であるバージョン番号リテラルの 場合にのみ扱われます。 バージョンリテラルのように見えないものは LIST の開始としてパースされます。 それにも関わらず、VERSION 引数として任意の式を使おうとする 多くの試みは動作しているように見えます; なぜなら Exporterimport メソッドは数値引数を特別に扱い、 それらをエクスポートするべきものと扱わずにバージョンチェックを 実行するからです。

Again, there is a distinction between omitting LIST (import called with no arguments) and an explicit empty LIST () (import not called). Note that there is no comma after VERSION!

繰り返すと、LIST を省略する(import が引数なしで 呼び出される)ことと明示的に空の LIST () を指定する (import は呼び出されない)ことは違います。 VERSION の後ろにカンマが不要なことに注意してください!

Because this is a wide-open interface, pragmas (compiler directives) are also implemented this way. Some of the currently implemented pragmas are:

これは、広く公開されているインタフェースですので、 プラグマ (コンパイラディレクティブ) も、この方法で実装されています。 現在実装されているプラグマには、以下のようなものがあります:

    use constant;
    use diagnostics;
    use integer;
    use sigtrap  qw(SEGV BUS);
    use strict   qw(subs vars refs);
    use subs     qw(afunc blurfl);
    use warnings qw(all);
    use sort     qw(stable);

Some of these pseudo-modules import semantics into the current block scope (like strict or integer, unlike ordinary modules, which import symbols into the current package (which are effective through the end of the file).

通常のモジュールが、現在のパッケージにシンボルをインポートする (これは、ファイルの終わりまで有効です) のに対して、これらの擬似モジュールの 一部(strictinteger など)は、現在の ブロックスコープにインポートを行ないます。

Because use takes effect at compile time, it doesn't respect the ordinary flow control of the code being compiled. In particular, putting a use inside the false branch of a conditional doesn't prevent it from being processed. If a module or pragma only needs to be loaded conditionally, this can be done using the if pragma:

use はコンパイル時に有効なので、コードが コンパイルされる際の通常の流れ制御には従いません。 特に、条件文のうち成立しない側の中に use を 書いても、処理を妨げられません。 モジュールやプラグマを条件付きでのみ読み込みたい場合、 if プラグマを使って実現できます:

    use if $] < 5.008, "utf8";
    use if WANT_WARNINGS, warnings => qw(all);

There's a corresponding no declaration that unimports meanings imported by use, i.e., it calls Module->unimport(LIST) instead of import. It behaves just as import does with VERSION, an omitted or empty LIST, or no unimport method being found.

これに対して、no 宣言という、 use によってインポートされたものを、 インポートされていないことにするものがあります; つまり、 import の代わりに Module->unimport(LIST) を呼び出します。 これは VERSION、省略された LIST、空の LIST、unimport メソッドが見つからない 場合などの観点では、import と同様に振る舞います。

    no integer;
    no strict 'refs';
    no warnings;

Care should be taken when using the no VERSION form of no. It is only meant to be used to assert that the running Perl is of a earlier version than its argument and not to undo the feature-enabling side effects of use VERSION.

nono VERSION 形式を使うときには 注意を払うべきです。 これは引数で指定されたバージョンよりも前の Perl で実行されたときに アサートされることを意味する だけ で、use VERSION によって 有効にされた副作用をなかったことにするもの ではありません

See perlmodlib for a list of standard modules and pragmas. See perlrun for the -M and -m command-line options to Perl that give use functionality from the command-line.

標準モジュールやプラグマの一覧は、perlmodlib を参照してください。 コマンドラインから use 機能を 指定するための -M-m の コマンドラインオプションについては perlrun を参照してください。

utime LIST

Changes the access and modification times on each file of a list of files. The first two elements of the list must be the NUMERIC access and modification times, in that order. Returns the number of files successfully changed. The inode change time of each file is set to the current time. For example, this code has the same effect as the Unix touch(1) command when the files already exist and belong to the user running the program:

ファイルのアクセス時刻と修正(modification) 時刻を変更します。 LIST の最初の二つの要素に、数値で表わしたアクセス時刻と修正時刻を 順に指定します。 変更に成功したファイルの数を返します。 各ファイルの inode 変更(change)時刻には、その時点の時刻が設定されます。 例えば、このコードはファイルが 既に存在して いて、ユーザーが 実行しているプログラムに従っているなら、 Unix の touch(1) コマンドと同じ効果があります。

    #!/usr/bin/perl
    my $atime = my $mtime = time;
    utime $atime, $mtime, @ARGV;

Since Perl 5.8.0, if the first two elements of the list are undef, the utime(2) syscall from your C library is called with a null second argument. On most systems, this will set the file's access and modification times to the current time (i.e., equivalent to the example above) and will work even on files you don't own provided you have write permission:

Perl 5.8.0 から、リストの最初の二つの要素が undef である 場合、C ライブラリの utime(2) システムコールを、秒の引数を null として 呼び出します。 ほとんどのシステムでは、これによってファイルのアクセス時刻と修正時刻を 現在の時刻にセットし(つまり、上記の例と等価です)、 書き込み権限があれば他のユーザーのファイルに対しても動作します。

    for my $file (@ARGV) {
        utime(undef, undef, $file)
            || warn "Couldn't touch $file: $!";
    }

Under NFS this will use the time of the NFS server, not the time of the local machine. If there is a time synchronization problem, the NFS server and local machine will have different times. The Unix touch(1) command will in fact normally use this form instead of the one shown in the first example.

NFS では、これはローカルマシンの時刻ではなく、NFS サーバーの時刻が 使われます。 時刻同期に問題がある場合、NFS サーバーとローカルマシンで違う時刻に なっている場合があります。 実際のところ、Unix の touch(1) コマンドは普通、最初の例ではなく、 この形を使います。

Passing only one of the first two elements as undef is equivalent to passing a 0 and will not have the effect described when both are undef. This also triggers an uninitialized warning.

最初の二つの要素のうち、一つだけに undef を渡すと、その 要素は 0 を渡すのと等価となり、上述の、両方に undef を 渡した時と同じ効果ではありません。 この場合は、未初期化の警告が出ます。

On systems that support futimes(2), you may pass filehandles among the files. On systems that don't support futimes(2), passing filehandles raises an exception. Filehandles must be passed as globs or glob references to be recognized; barewords are considered filenames.

futimes(2) に対応しているシステムでは、ファイルハンドルを引数として 渡せます。 futimes(2) に対応していないシステムでは、ファイルハンドルを渡すと 例外が発生します。 ファイルハンドルを認識させるためには、グロブまたはリファレンスとして 渡されなければなりません; 裸の単語はファイル名として扱われます。

Portability issues: "utime" in perlport.

移植性の問題: "utime" in perlport

values HASH
values ARRAY

In list context, returns a list consisting of all the values of the named hash. In Perl 5.12 or later only, will also return a list of the values of an array; prior to that release, attempting to use an array argument will produce a syntax error. In scalar context, returns the number of values.

リストコンテキストでは、指定したハッシュのすべての値を返します。 Perl 5.12 以降でのみ、配列の全ての値からなるリストも返します; このリリースの前では、配列要素に使おうとすると文法エラーが発生します。 スカラコンテキストでは、値の数を返します。

Hash entries are returned in an apparently random order. The actual random order is specific to a given hash; the exact same series of operations on two hashes may result in a different order for each hash. Any insertion into the hash may change the order, as will any deletion, with the exception that the most recent key returned by each or keys may be deleted without changing the order. So long as a given hash is unmodified you may rely on keys, values and each to repeatedly return the same order as each other. See "Algorithmic Complexity Attacks" in perlsec for details on why hash order is randomized. Aside from the guarantees provided here the exact details of Perl's hash algorithm and the hash traversal order are subject to change in any release of Perl. Tied hashes may behave differently to Perl's hashes with respect to changes in order on insertion and deletion of items.

ハッシュ要素は見かけ上、ランダムな順序で返されます。 実際のランダムな順序はハッシュに固有です; 二つのハッシュに全く同じ一連の 操作を行っても、ハッシュによって異なった順序になります。 ハッシュへの挿入によって順序が変わることがあります; 削除も同様ですが、 each または keys によって返されたもっとも 最近のキーは順序を変えることなく削除できます。 ハッシュが変更されない限り、keys, values, each が繰り返し同じ順序で返すことに依存してもかまいません。 なぜハッシュの順序がランダム化されているかの詳細については "Algorithmic Complexity Attacks" in perlsec を参照してください。 ここで保証したことを除いて、Perl のハッシュアルゴリズムとハッシュ横断順序の 正確な詳細は Perl のリリースによって変更される可能性があります。 tie されたハッシュは、アイテムの挿入と削除の順序に関して Perl のハッシュと 異なった振る舞いをします。

As a side effect, calling values resets the HASH or ARRAY's internal iterator (see each) before yielding the values. In particular, calling values in void context resets the iterator with no other overhead.

副作用として、values を呼び出すと、 値を取り出す前に HASH や ARRAY の 内部反復子(each 参照)をリセットします。 特に、values を無効コンテキストで呼び出すとその他の オーバーヘッドなしで反復子をリセットします。

Apart from resetting the iterator, values @array in list context is the same as plain @array. (We recommend that you use void context keys @array for this, but reasoned that taking values @array out would require more documentation than leaving it in.)

反復子をリセットするということを除けば、 リストコンテキストでの values @array は単なる @array と同じです。 この目的のためには無効コンテキストで keys @array を使うことを お勧めしますが、values @array を取り出すにはそのままにするよりも より多くの文書が必要だと判断しました。)

Note that the values are not copied, which means modifying them will modify the contents of the hash:

値はコピーされないので、返されたリストを変更すると ハッシュの中身が変更されることに注意してください。

    for (values %hash)      { s/foo/bar/g }  # modifies %hash values
    for (@hash{keys %hash}) { s/foo/bar/g }  # same

Starting with Perl 5.14, an experimental feature allowed values to take a scalar expression. This experiment has been deemed unsuccessful, and was removed as of Perl 5.24.

Perl 5.14 から、values がスカラ式を取ることが出来るという 実験的機能がありました。 この実験は失敗と見なされ、Perl 5.24 で削除されました。

To avoid confusing would-be users of your code who are running earlier versions of Perl with mysterious syntax errors, put this sort of thing at the top of your file to signal that your code will work only on Perls of a recent vintage:

あなたのコードを以前のバージョンの Perl で実行したユーザーが不思議な 文法エラーで混乱することを避けるために、コードが最近のバージョンの Perl で のみ 動作することを示すためにファイルの先頭に以下のようなことを 書いてください:

    use 5.012;  # so keys/values/each work on arrays

See also keys, each, and sort.

keys, each, sort も 参照してください。

vec EXPR,OFFSET,BITS

Treats the string in EXPR as a bit vector made up of elements of width BITS and returns the value of the element specified by OFFSET as an unsigned integer. BITS therefore specifies the number of bits that are reserved for each element in the bit vector. This must be a power of two from 1 to 32 (or 64, if your platform supports that).

文字列 EXPR を BITS 幅の要素からなるビットベクターとして扱い、 OFFSET で指定された要素を符号なし整数として返します。 従って、 BITS はビットベクターの中の各要素について予約されるビット数です。 BIT は、1 から 32 まで(プラットホームが 対応していれば 64 まで) の 2 のべき乗でなければなりません。

If BITS is 8, "elements" coincide with bytes of the input string.

BITS が 8 の場合、「要素」は入力文字列の各バイトと一致します。

If BITS is 16 or more, bytes of the input string are grouped into chunks of size BITS/8, and each group is converted to a number as with pack/unpack with big-endian formats n/N (and analogously for BITS==64). See pack for details.

BITS が 16 以上の場合、入力のバイト列は BITS/8 のサイズの固まりに グループ化され、各グループは pack/ unpack のビッグエンディアン フォーマット n/N を用いて(BITS==64 の類似として)数値に変換されます。 詳細は pack を参照してください。

If bits is 4 or less, the string is broken into bytes, then the bits of each byte are broken into 8/BITS groups. Bits of a byte are numbered in a little-endian-ish way, as in 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80. For example, breaking the single input byte chr(0x36) into two groups gives a list (0x6, 0x3); breaking it into 4 groups gives (0x2, 0x1, 0x3, 0x0).

BITS が 4 以下の場合、文字列はバイトに分解され、バイトの各ビットは 8/BITS 個のグループに分割されます。 ビットはリトルエンディアン風に、0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 の順になります。 例えば、入力バイト chr(0x36) を二つのグループに分割すると、 (0x6, 0x3) になります; 4 つに分割すると (0x2, 0x1, 0x3, 0x0) に なります。

vec may also be assigned to, in which case parentheses are needed to give the expression the correct precedence as in

vec は左辺値として、代入の 対象にすることもできます; この場合、式を正しく 先行させるために以下のように括弧が必要です:

    vec($image, $max_x * $x + $y, 8) = 3;

If the selected element is outside the string, the value 0 is returned. If an element off the end of the string is written to, Perl will first extend the string with sufficiently many zero bytes. It is an error to try to write off the beginning of the string (i.e., negative OFFSET).

選択された要素が文字列の外側だった場合、値 0 が返されます。 文字列の最後よりも後ろの要素に書き込もうとした場合、 Perl はまず文字列を必要な分だけ 0 のバイトで拡張します。 文字列の先頭より前に書き込もうとした(つまり OFFSET が負の数だった) 場合はエラーとなります。

If the string happens to be encoded as UTF-8 internally (and thus has the UTF8 flag set), vec tries to convert it to use a one-byte-per-character internal representation. However, if the string contains characters with values of 256 or higher, that conversion will fail, and a deprecation message will be raised. In that situation, vec will operate on the underlying buffer regardless, in its internal UTF-8 representation. In Perl 5.32, this will be a fatal error.

文字列がたまたま内部で UTF-8 でエンコードされている場合(したがって UTF8 フラグがセットされている場合)、 vec はこれを単一バイト文字内部表現に 変換しようとします。 しかし、この文字列に値が 256 以上の文字が含まれている場合、 変換は失敗し、廃止予定メッセージが発生します。 この場合、vec は内部の UTF-8 表現を気にせず、 基となっているバッファに対して操作します。 Perl 5.32 で、これは致命的エラーになります。

Strings created with vec can also be manipulated with the logical operators |, &, ^, and ~. These operators will assume a bit vector operation is desired when both operands are strings. See "Bitwise String Operators" in perlop.

vec で作られた文字列は、論理演算子 |&^, ~ で扱うこともできます。 これらの演算子は、両方の被演算子に文字列を使うと、 ビットベクター演算を行ないます。 "Bitwise String Operators" in perlop を参照してください。

The following code will build up an ASCII string saying 'PerlPerlPerl'. The comments show the string after each step. Note that this code works in the same way on big-endian or little-endian machines.

次のコードは 'PerlPerlPerl' という ASCII 文字列を作成します。 コメントは各行の実行後の文字列を示します。 このコードはビッグエンディアンでもリトルエンディアンでも同じように 動作することに注意してください。

    my $foo = '';
    vec($foo,  0, 32) = 0x5065726C; # 'Perl'

    # $foo eq "Perl" eq "\x50\x65\x72\x6C", 32 bits
    print vec($foo, 0, 8);  # prints 80 == 0x50 == ord('P')

    vec($foo,  2, 16) = 0x5065; # 'PerlPe'
    vec($foo,  3, 16) = 0x726C; # 'PerlPerl'
    vec($foo,  8,  8) = 0x50;   # 'PerlPerlP'
    vec($foo,  9,  8) = 0x65;   # 'PerlPerlPe'
    vec($foo, 20,  4) = 2;      # 'PerlPerlPe'   . "\x02"
    vec($foo, 21,  4) = 7;      # 'PerlPerlPer'
                                   # 'r' is "\x72"
    vec($foo, 45,  2) = 3;      # 'PerlPerlPer'  . "\x0c"
    vec($foo, 93,  1) = 1;      # 'PerlPerlPer'  . "\x2c"
    vec($foo, 94,  1) = 1;      # 'PerlPerlPerl'
                                   # 'l' is "\x6c"

To transform a bit vector into a string or list of 0's and 1's, use these:

ビットベクターを、0 と 1 の文字列や配列に変換するには、 以下のようにします。

    my $bits = unpack("b*", $vector);
    my @bits = split(//, unpack("b*", $vector));

If you know the exact length in bits, it can be used in place of the *.

ビット長が分かっていれば、* の代わりにその長さを使うことができます。

Here is an example to illustrate how the bits actually fall in place:

これはビットが実際にどのような位置に入るかを図示する例です。

  #!/usr/bin/perl -wl

  print <<'EOT';
                                    0         1         2         3
                     unpack("V",$_) 01234567890123456789012345678901
  ------------------------------------------------------------------
  EOT

  for $w (0..3) {
      $width = 2**$w;
      for ($shift=0; $shift < $width; ++$shift) {
          for ($off=0; $off < 32/$width; ++$off) {
              $str = pack("B*", "0"x32);
              $bits = (1<<$shift);
              vec($str, $off, $width) = $bits;
              $res = unpack("b*",$str);
              $val = unpack("V", $str);
              write;
          }
      }
  }

  format STDOUT =
  vec($_,@#,@#) = @<< == @######### @>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  $off, $width, $bits, $val, $res
  .
  __END__

Regardless of the machine architecture on which it runs, the example above should print the following table:

実行するマシンのアーキテクチャに関わらず、 上記の例は以下の表を出力します。

                                    0         1         2         3
                     unpack("V",$_) 01234567890123456789012345678901
  ------------------------------------------------------------------
  vec($_, 0, 1) = 1   ==          1 10000000000000000000000000000000
  vec($_, 1, 1) = 1   ==          2 01000000000000000000000000000000
  vec($_, 2, 1) = 1   ==          4 00100000000000000000000000000000
  vec($_, 3, 1) = 1   ==          8 00010000000000000000000000000000
  vec($_, 4, 1) = 1   ==         16 00001000000000000000000000000000
  vec($_, 5, 1) = 1   ==         32 00000100000000000000000000000000
  vec($_, 6, 1) = 1   ==         64 00000010000000000000000000000000
  vec($_, 7, 1) = 1   ==        128 00000001000000000000000000000000
  vec($_, 8, 1) = 1   ==        256 00000000100000000000000000000000
  vec($_, 9, 1) = 1   ==        512 00000000010000000000000000000000
  vec($_,10, 1) = 1   ==       1024 00000000001000000000000000000000
  vec($_,11, 1) = 1   ==       2048 00000000000100000000000000000000
  vec($_,12, 1) = 1   ==       4096 00000000000010000000000000000000
  vec($_,13, 1) = 1   ==       8192 00000000000001000000000000000000
  vec($_,14, 1) = 1   ==      16384 00000000000000100000000000000000
  vec($_,15, 1) = 1   ==      32768 00000000000000010000000000000000
  vec($_,16, 1) = 1   ==      65536 00000000000000001000000000000000
  vec($_,17, 1) = 1   ==     131072 00000000000000000100000000000000
  vec($_,18, 1) = 1   ==     262144 00000000000000000010000000000000
  vec($_,19, 1) = 1   ==     524288 00000000000000000001000000000000
  vec($_,20, 1) = 1   ==    1048576 00000000000000000000100000000000
  vec($_,21, 1) = 1   ==    2097152 00000000000000000000010000000000
  vec($_,22, 1) = 1   ==    4194304 00000000000000000000001000000000
  vec($_,23, 1) = 1   ==    8388608 00000000000000000000000100000000
  vec($_,24, 1) = 1   ==   16777216 00000000000000000000000010000000
  vec($_,25, 1) = 1   ==   33554432 00000000000000000000000001000000
  vec($_,26, 1) = 1   ==   67108864 00000000000000000000000000100000
  vec($_,27, 1) = 1   ==  134217728 00000000000000000000000000010000
  vec($_,28, 1) = 1   ==  268435456 00000000000000000000000000001000
  vec($_,29, 1) = 1   ==  536870912 00000000000000000000000000000100
  vec($_,30, 1) = 1   == 1073741824 00000000000000000000000000000010
  vec($_,31, 1) = 1   == 2147483648 00000000000000000000000000000001
  vec($_, 0, 2) = 1   ==          1 10000000000000000000000000000000
  vec($_, 1, 2) = 1   ==          4 00100000000000000000000000000000
  vec($_, 2, 2) = 1   ==         16 00001000000000000000000000000000
  vec($_, 3, 2) = 1   ==         64 00000010000000000000000000000000
  vec($_, 4, 2) = 1   ==        256 00000000100000000000000000000000
  vec($_, 5, 2) = 1   ==       1024 00000000001000000000000000000000
  vec($_, 6, 2) = 1   ==       4096 00000000000010000000000000000000
  vec($_, 7, 2) = 1   ==      16384 00000000000000100000000000000000
  vec($_, 8, 2) = 1   ==      65536 00000000000000001000000000000000
  vec($_, 9, 2) = 1   ==     262144 00000000000000000010000000000000
  vec($_,10, 2) = 1   ==    1048576 00000000000000000000100000000000
  vec($_,11, 2) = 1   ==    4194304 00000000000000000000001000000000
  vec($_,12, 2) = 1   ==   16777216 00000000000000000000000010000000
  vec($_,13, 2) = 1   ==   67108864 00000000000000000000000000100000
  vec($_,14, 2) = 1   ==  268435456 00000000000000000000000000001000
  vec($_,15, 2) = 1   == 1073741824 00000000000000000000000000000010
  vec($_, 0, 2) = 2   ==          2 01000000000000000000000000000000
  vec($_, 1, 2) = 2   ==          8 00010000000000000000000000000000
  vec($_, 2, 2) = 2   ==         32 00000100000000000000000000000000
  vec($_, 3, 2) = 2   ==        128 00000001000000000000000000000000
  vec($_, 4, 2) = 2   ==        512 00000000010000000000000000000000
  vec($_, 5, 2) = 2   ==       2048 00000000000100000000000000000000
  vec($_, 6, 2) = 2   ==       8192 00000000000001000000000000000000
  vec($_, 7, 2) = 2   ==      32768 00000000000000010000000000000000
  vec($_, 8, 2) = 2   ==     131072 00000000000000000100000000000000
  vec($_, 9, 2) = 2   ==     524288 00000000000000000001000000000000
  vec($_,10, 2) = 2   ==    2097152 00000000000000000000010000000000
  vec($_,11, 2) = 2   ==    8388608 00000000000000000000000100000000
  vec($_,12, 2) = 2   ==   33554432 00000000000000000000000001000000
  vec($_,13, 2) = 2   ==  134217728 00000000000000000000000000010000
  vec($_,14, 2) = 2   ==  536870912 00000000000000000000000000000100
  vec($_,15, 2) = 2   == 2147483648 00000000000000000000000000000001
  vec($_, 0, 4) = 1   ==          1 10000000000000000000000000000000
  vec($_, 1, 4) = 1   ==         16 00001000000000000000000000000000
  vec($_, 2, 4) = 1   ==        256 00000000100000000000000000000000
  vec($_, 3, 4) = 1   ==       4096 00000000000010000000000000000000
  vec($_, 4, 4) = 1   ==      65536 00000000000000001000000000000000
  vec($_, 5, 4) = 1   ==    1048576 00000000000000000000100000000000
  vec($_, 6, 4) = 1   ==   16777216 00000000000000000000000010000000
  vec($_, 7, 4) = 1   ==  268435456 00000000000000000000000000001000
  vec($_, 0, 4) = 2   ==          2 01000000000000000000000000000000
  vec($_, 1, 4) = 2   ==         32 00000100000000000000000000000000
  vec($_, 2, 4) = 2   ==        512 00000000010000000000000000000000
  vec($_, 3, 4) = 2   ==       8192 00000000000001000000000000000000
  vec($_, 4, 4) = 2   ==     131072 00000000000000000100000000000000
  vec($_, 5, 4) = 2   ==    2097152 00000000000000000000010000000000
  vec($_, 6, 4) = 2   ==   33554432 00000000000000000000000001000000
  vec($_, 7, 4) = 2   ==  536870912 00000000000000000000000000000100
  vec($_, 0, 4) = 4   ==          4 00100000000000000000000000000000
  vec($_, 1, 4) = 4   ==         64 00000010000000000000000000000000
  vec($_, 2, 4) = 4   ==       1024 00000000001000000000000000000000
  vec($_, 3, 4) = 4   ==      16384 00000000000000100000000000000000
  vec($_, 4, 4) = 4   ==     262144 00000000000000000010000000000000
  vec($_, 5, 4) = 4   ==    4194304 00000000000000000000001000000000
  vec($_, 6, 4) = 4   ==   67108864 00000000000000000000000000100000
  vec($_, 7, 4) = 4   == 1073741824 00000000000000000000000000000010
  vec($_, 0, 4) = 8   ==          8 00010000000000000000000000000000
  vec($_, 1, 4) = 8   ==        128 00000001000000000000000000000000
  vec($_, 2, 4) = 8   ==       2048 00000000000100000000000000000000
  vec($_, 3, 4) = 8   ==      32768 00000000000000010000000000000000
  vec($_, 4, 4) = 8   ==     524288 00000000000000000001000000000000
  vec($_, 5, 4) = 8   ==    8388608 00000000000000000000000100000000
  vec($_, 6, 4) = 8   ==  134217728 00000000000000000000000000010000
  vec($_, 7, 4) = 8   == 2147483648 00000000000000000000000000000001
  vec($_, 0, 8) = 1   ==          1 10000000000000000000000000000000
  vec($_, 1, 8) = 1   ==        256 00000000100000000000000000000000
  vec($_, 2, 8) = 1   ==      65536 00000000000000001000000000000000
  vec($_, 3, 8) = 1   ==   16777216 00000000000000000000000010000000
  vec($_, 0, 8) = 2   ==          2 01000000000000000000000000000000
  vec($_, 1, 8) = 2   ==        512 00000000010000000000000000000000
  vec($_, 2, 8) = 2   ==     131072 00000000000000000100000000000000
  vec($_, 3, 8) = 2   ==   33554432 00000000000000000000000001000000
  vec($_, 0, 8) = 4   ==          4 00100000000000000000000000000000
  vec($_, 1, 8) = 4   ==       1024 00000000001000000000000000000000
  vec($_, 2, 8) = 4   ==     262144 00000000000000000010000000000000
  vec($_, 3, 8) = 4   ==   67108864 00000000000000000000000000100000
  vec($_, 0, 8) = 8   ==          8 00010000000000000000000000000000
  vec($_, 1, 8) = 8   ==       2048 00000000000100000000000000000000
  vec($_, 2, 8) = 8   ==     524288 00000000000000000001000000000000
  vec($_, 3, 8) = 8   ==  134217728 00000000000000000000000000010000
  vec($_, 0, 8) = 16  ==         16 00001000000000000000000000000000
  vec($_, 1, 8) = 16  ==       4096 00000000000010000000000000000000
  vec($_, 2, 8) = 16  ==    1048576 00000000000000000000100000000000
  vec($_, 3, 8) = 16  ==  268435456 00000000000000000000000000001000
  vec($_, 0, 8) = 32  ==         32 00000100000000000000000000000000
  vec($_, 1, 8) = 32  ==       8192 00000000000001000000000000000000
  vec($_, 2, 8) = 32  ==    2097152 00000000000000000000010000000000
  vec($_, 3, 8) = 32  ==  536870912 00000000000000000000000000000100
  vec($_, 0, 8) = 64  ==         64 00000010000000000000000000000000
  vec($_, 1, 8) = 64  ==      16384 00000000000000100000000000000000
  vec($_, 2, 8) = 64  ==    4194304 00000000000000000000001000000000
  vec($_, 3, 8) = 64  == 1073741824 00000000000000000000000000000010
  vec($_, 0, 8) = 128 ==        128 00000001000000000000000000000000
  vec($_, 1, 8) = 128 ==      32768 00000000000000010000000000000000
  vec($_, 2, 8) = 128 ==    8388608 00000000000000000000000100000000
  vec($_, 3, 8) = 128 == 2147483648 00000000000000000000000000000001
wait

Behaves like wait(2) on your system: it waits for a child process to terminate and returns the pid of the deceased process, or -1 if there are no child processes. The status is returned in $? and ${^CHILD_ERROR_NATIVE}. Note that a return value of -1 could mean that child processes are being automatically reaped, as described in perlipc.

wait(2) と同様に振る舞います: チャイルドプロセスが終了するのを待ち、 消滅したプロセスの pid を返します; チャイルドプロセスが存在しないときには、 -1 を返します。 ステータスは $?${^CHILD_ERROR_NATIVE} に返されます。 perlipc に書いているように、返り値が -1 の場合は子プロセスが 自動的に刈り取られたことを意味するかもしれないことに注意してください。

If you use wait in your handler for $SIG{CHLD}, it may accidentally wait for the child created by qx or system. See perlipc for details.

wait$SIG{CHLD} のハンドラで使うと、誤って qxsystem によって 作られた子を待つことになるかも知れません。 詳しくは perlipc を参照してください。

Portability issues: "wait" in perlport.

移植性の問題: "wait" in perlport

waitpid PID,FLAGS

Waits for a particular child process to terminate and returns the pid of the deceased process, or -1 if there is no such child process. A non-blocking wait (with WNOHANG in FLAGS) can return 0 if there are child processes matching PID but none have terminated yet. The status is returned in $? and ${^CHILD_ERROR_NATIVE}.

特定の子プロセスが終了するのを待ち、消滅したプロセスの pid を 返します; 指定した子プロセスが存在しないときには、-1 を返します。 (FLAGS に WNOHANG を指定した) 非ブロッキング wait は、 PID がマッチングする子プロセスがいてもまだ終了していない場合に 0 を 返すことがあります。 ステータスは $?${^CHILD_ERROR_NATIVE} に返されます。

A PID of 0 indicates to wait for any child process whose process group ID is equal to that of the current process. A PID of less than -1 indicates to wait for any child process whose process group ID is equal to -PID. A PID of -1 indicates to wait for any child process.

PID に 0 を指定すると、プロセスグループ ID が現在のプロセスと同じである 任意の子プロセスを wait します。 PID に -1 以下を指定すると、プロセスグループ ID が -PID に等しい 任意の子プロセスを wait します。 PID に -1 を指定すると任意の子プロセスを wait します。

If you say

以下のようにするか

    use POSIX ":sys_wait_h";

    my $kid;
    do {
        $kid = waitpid(-1, WNOHANG);
    } while $kid > 0;

or

または

    1 while waitpid(-1, WNOHANG) > 0;

then you can do a non-blocking wait for all pending zombie processes (see "WAIT" in POSIX). Non-blocking wait is available on machines supporting either the waitpid(2) or wait4(2) syscalls. However, waiting for a particular pid with FLAGS of 0 is implemented everywhere. (Perl emulates the system call by remembering the status values of processes that have exited but have not been harvested by the Perl script yet.)

とすると、ブロックが起こらないようにして、全ての待機中ゾンビプロセスを wait します ("WAIT" in POSIX を参照してください)。 ブロックなしの wait は、システムコール wait_pid(2) か、 システムコール wait4(2) をサポートしているマシンで利用可能です。 しかしながら、特定の pid を 0 の FLAGS での wait はどこでも 実装されています。 (exit したプロセスのステータス値を覚えておいて、Perl がシステムコールを エミュレートしますが、Perl スクリプトには取り入れられていません。)

Note that on some systems, a return value of -1 could mean that child processes are being automatically reaped. See perlipc for details, and for other examples.

システムによっては、返り値が -1 の場合は子プロセスが自動的に 刈り取られたことを意味するかもしれないことに注意してください。 詳細やその他の例については perlipc を参照してください。

Portability issues: "waitpid" in perlport.

移植性の問題: "waitpid" in perlport

wantarray

Returns true if the context of the currently executing subroutine or eval is looking for a list value. Returns false if the context is looking for a scalar. Returns the undefined value if the context is looking for no value (void context).

現在実行中のサブルーチンか eval ブロックのコンテキストが、 リスト値を要求するものであれば、真を返します。 スカラを要求するコンテキストであれば、偽を返します。 何も値を要求しない(無効コンテキスト)場合は未定義値を返します。

    return unless defined wantarray; # don't bother doing more
    my @a = complex_calculation();
    return wantarray ? @a : "@a";

wantarray's result is unspecified in the top level of a file, in a BEGIN, UNITCHECK, CHECK, INIT or END block, or in a DESTROY method.

ファイルのトップレベル、BEGIN, UNITCHECK, CHECK, INIT, END ブロック内、DESTROY メソッド内では wantarray の結果は 未定義です。

This function should have been named wantlist() instead.

この関数は wantlist() という名前にするべきでした。

warn LIST

Emits a warning, usually by printing it to STDERR. warn interprets its operand LIST in the same way as die, but is slightly different in what it defaults to when LIST is empty or makes an empty string. If it is empty and $@ already contains an exception value then that value is used after appending "\t...caught". If it is empty and $@ is also empty then the string "Warning: Something's wrong" is used.

(通常は STDERR に表示することで) 警告を出力します。 warn はそのオペランド LIST を die と同様に解釈しますが、 LIST が空や空文字列を作る時に何をデフォルトとするかが少し異なります。 それが空かつ、$@ に既に 例外値が入っている場合、"\t...caught" を追加した値が 用いられます。 もしこれが空で $@ も空の場合は、"Warning: Something's wrong" という 文字列が使われます。

By default, the exception derived from the operand LIST is stringified and printed to STDERR. This behaviour can be altered by installing a $SIG{__WARN__} handler. If there is such a handler then no message is automatically printed; it is the handler's responsibility to deal with the exception as it sees fit (like, for instance, converting it into a die). Most handlers must therefore arrange to actually display the warnings that they are not prepared to deal with, by calling warn again in the handler. Note that this is quite safe and will not produce an endless loop, since __WARN__ hooks are not called from inside one.

デフォルトでは、LIST オペランドから生成された例外は 文字列化されて STDERR に表示されます。 この振る舞いは、$SIG{__WARN__} ハンドラを設定することで 置き換えられます。 このようなハンドラが設定されている場合は何の メッセージも自動的には表示されません; 例外をどう扱うか(例えば die に変換するか)はハンドラの 責任ということです。 従ってほとんどのハンドラは、扱おうと準備していない警告を表示するために、 ハンドラの中で warn を再び呼び出します。 __WARN__ フックはハンドラ内では呼び出されないので、これは十分安全で、 無限ループを引き起こすことはないということに注意してください。

You will find this behavior is slightly different from that of $SIG{__DIE__} handlers (which don't suppress the error text, but can instead call die again to change it).

この振る舞いは $SIG{__DIE__} ハンドラ(エラーテキストは 削除しませんが、代わりに die をもう一度呼び出すことで 変更できます)とは少し違うことに気付くことでしょう。

Using a __WARN__ handler provides a powerful way to silence all warnings (even the so-called mandatory ones). An example:

__WARN__ ハンドラを使うと、(いわゆる必須のものを含む)全ての 警告を黙らせる強力な手段となります。 例:

    # wipe out *all* compile-time warnings
    BEGIN { $SIG{'__WARN__'} = sub { warn $_[0] if $DOWARN } }
    my $foo = 10;
    my $foo = 20;          # no warning about duplicate my $foo,
                           # but hey, you asked for it!
    # no compile-time or run-time warnings before here
    $DOWARN = 1;

    # run-time warnings enabled after here
    warn "\$foo is alive and $foo!";     # does show up

See perlvar for details on setting %SIG entries and for more examples. See the Carp module for other kinds of warnings using its carp and cluck functions.

%SIG エントリのセットに関する詳細とさらなる例に関しては perlvar を参照してください。 carp 関数と cluck 関数を用いた警告の方法に関しては Carp モジュールを参照してください。

write FILEHANDLE
write EXPR
write

Writes a formatted record (possibly multi-line) to the specified FILEHANDLE, using the format associated with that file. By default the format for a file is the one having the same name as the filehandle, but the format for the current output channel (see the select function) may be set explicitly by assigning the name of the format to the $~ variable.

指定された FILEHANDLE に対して、そのファイルに対応させた フォーマットを使って、(複数行の場合もある) 整形された レコードを書き出します。 デフォルトでは、ファイルに対応するフォーマットは、ファイルハンドルと 同じ名前のものですが、その時点の出力チャネル (select 関数の項を 参照してください) のフォーマットは、その名前を明示的に変数 $~ に代入することで、変更が可能です。

Top of form processing is handled automatically: if there is insufficient room on the current page for the formatted record, the page is advanced by writing a form feed and a special top-of-page format is used to format the new page header before the record is written. By default, the top-of-page format is the name of the filehandle with _TOP appended, or top in the current package if the former does not exist. This would be a problem with autovivified filehandles, but it may be dynamically set to the format of your choice by assigning the name to the $^ variable while that filehandle is selected. The number of lines remaining on the current page is in variable $-, which can be set to 0 to force a new page.

ページの先頭の処理は、自動的に行なわれます: 現在のページに整形された レコードを出力するだけのスペースがない場合には、改ページを行なってページを 進め、新しいページヘッダを整形するため、ページ先頭フォーマットが使われ、 その後でレコードが書かれます。 デフォルトでは、ページ先頭フォーマットは、ファイルハンドルの名前に _TOP をつなげたものか、前者が存在しないなら、現在のパッケージの top です。 これは自動有効化されたファイルハンドルで問題になる可能性がありますが、 ファイルハンドルが選択されている間に、 変数 $^ に名前を設定すれば、動的にフォーマットを 変更することができます。 そのページの残り行数は、変数 $- に入っており、この変数を 0 に設定することで、強制的に改ページを行なうことができます。

If FILEHANDLE is unspecified, output goes to the current default output channel, which starts out as STDOUT but may be changed by the select operator. If the FILEHANDLE is an EXPR, then the expression is evaluated and the resulting string is used to look up the name of the FILEHANDLE at run time. For more on formats, see perlform.

FILEHANDLE を指定しないと、出力はその時点のデフォルト出力チャネルに対して 行なわれます; これは、スクリプトの開始時点では STDOUT ですが、 select 演算子で変更することができます。 FILEHANDLE が EXPR ならば、式が評価され、その結果の文字列が 実行時に FILEHANDLE の名前として見られます。 フォーマットについて、さらには、perlform を参照してください。

Note that write is not the opposite of read. Unfortunately.

write は read の 反対のことをするもの ではありません。 残念ながら。

y///

The transliteration operator. Same as tr///. See "Quote-Like Operators" in perlop.

文字変換演算子です。 tr/// と同じです。 "Quote-Like Operators" in perlop を参照してください。

Non-function Keywords by Cross-reference

perldata

__DATA__
__END__

These keywords are documented in "Special Literals" in perldata.

これらのキーワードは "Special Literals" in perldata で文書化されています。

perlmod

BEGIN
CHECK
END
INIT
UNITCHECK

These compile phase keywords are documented in "BEGIN, UNITCHECK, CHECK, INIT and END" in perlmod.

これらのコンパイルフェーズキーワードは "BEGIN, UNITCHECK, CHECK, INIT and END" in perlmod で文書化されています。

perlobj

DESTROY

This method keyword is documented in "Destructors" in perlobj.

このメソッドキーワードは "Destructors" in perlobj で文書化されています。

perlop

and
cmp
eq
ge
gt
le
lt
ne
not
or
x
xor

These operators are documented in perlop.

これらの演算子は perlop で文書化されています。

perlsub

AUTOLOAD

This keyword is documented in "Autoloading" in perlsub.

このキーワードは "Autoloading" in perlsub で文書化されています。

perlsyn

else
elsif
for
foreach
if
unless
until
while

These flow-control keywords are documented in "Compound Statements" in perlsyn.

これらのフロー制御キーワードは "Compound Statements" in perlsyn で 文書化されています。

elseif

The "else if" keyword is spelled elsif in Perl. There's no elif or else if either. It does parse elseif, but only to warn you about not using it.

"else if" キーワードは Perl では elsif と綴ります。 elifelse if はありません。 elseif はパースされますが、使わないように警告するためだけです。

See the documentation for flow-control keywords in "Compound Statements" in perlsyn.

"Compound Statements" in perlsyn のフロー制御キーワードに関する文章を 参照してください。

default
given
when

These flow-control keywords related to the experimental switch feature are documented in "Switch Statements" in perlsyn.

これらの実験的な switch 機能に関連するフロー制御キーワードは "Switch Statements" in perlsyn で文書化されています。