5.38.0

名前

perldata - Perl data types

perldata - Perl のデータ型

説明

変数名

Perl has three built-in data types: scalars, arrays of scalars, and associative arrays of scalars, known as "hashes". A scalar is a single string (of any size, limited only by the available memory), number, or a reference to something (which will be discussed in perlref). Normal arrays are ordered lists of scalars indexed by number, starting with 0. Hashes are unordered collections of scalar values indexed by their associated string key.

Perl には、スカラ、スカラの配列、「ハッシュ」とも呼ばれるスカラの 連想配列という 3 つの組み込みデータ型があります。 スカラは単一の(任意の長さの)文字列(利用可能メモリによってのみ 制限されます)か、数値か、何かへのリファレンス(これは perlref で 議論します)のいずれかです。 通常の配列は 0 を基点とする数値で添え字づけされるスカラの順序付き リストです。 ハッシュ配列は、文字列のキーのインデックスと、それに結び付けられた スカラ値の、順序のない集合です。

Values are usually referred to by name, or through a named reference. The first character of the name tells you to what sort of data structure it refers. The rest of the name tells you the particular value to which it refers. Usually this name is a single identifier, that is, a string beginning with a letter or underscore, and containing letters, underscores, and digits. In some cases, it may be a chain of identifiers, separated by :: (or by the deprecated '); all but the last are interpreted as names of packages, to locate the namespace in which to look up the final identifier (see "Packages" in perlmod for details). For a more in-depth discussion on identifiers, see "Identifier parsing". It's possible to substitute for a simple identifier, an expression that produces a reference to the value at runtime. This is described in more detail below and in perlref.

値は通常、名前もしくは名前付きのリファレンスを通して参照されます。 名前の最初にある文字は、その名前がどのような構造のデータを 参照しているのかを区別します。 名前の残りの部分は、参照する値を特定するものです。 通常、この名前は一つの 識別子、つまり、英字か下線から始まって それに英字、下線、数字が続く文字列のことです。 一部のケースにおいては ::(あるいは廃止予定の ') で分けられた 識別子の並びであってもかまいません; これの最後のもの以外の名前は、最後の 部分にある識別子をその名前空間に置くためのパッケージの名前として 解釈されます(詳細は "Packages" in perlmod を参照してください)。 識別子に関するより深い議論に関しては、"Identifier parsing" を 参照してください。 リファレンスを生成する式の単純な識別子を、実行時に値に置き換えることも 可能です。 これはこの文書の後の部分と、perlref に詳細な説明があります。

Perl also has its own built-in variables whose names don't follow these rules. They have strange names so they don't accidentally collide with one of your normal variables. Strings that match parenthesized parts of a regular expression are saved under names containing only digits after the $ (see perlop and perlre). In addition, several special variables that provide windows into the inner working of Perl have names containing punctuation characters. These are documented in perlvar.

Perl はこれらの規則に従っていない名前を持っている組み込みの変数も 持っています。 これらは変わった名前をもっているので、あなたが使った普通の 変数との間で間違って衝突することがありません。 正規表現の括弧づけされた部分(parenthesized parts)の文字列は $ の後に 数字だけが続いている名前で保存されます( perlopperlre を 参照してください)。 それに加え、Perl の内部的な動作に対する窓を開けている幾つかの 特殊変数が、句読点文字を含む名前を持っています。 これらは perlvar で文書化されています。

Scalar values are always named with '$', even when referring to a scalar that is part of an array or a hash. The '$' symbol works semantically like the English word "the" in that it indicates a single value is expected.

スカラ値の参照は、配列やハッシュの一要素であるスカラを参照する場合でも、 常に名前に '$' を付けます。 シンボル '$' は文法的に英単語 "the" のように働き、単一の値が 想定されていることを示しています。

    $days               # the simple scalar value "days"
    $days[28]           # the 29th element of array @days
    $days{'Feb'}        # the 'Feb' value from hash %days
    $#days              # the last index of array @days

Entire arrays (and slices of arrays and hashes) are denoted by '@', which works much as the word "these" or "those" does in English, in that it indicates multiple values are expected.

配列全体(および配列やハッシュのスライス)は '@' で示します; これは英単語での "these" や "those" のように働き、複数の値が 想定されていることを示します。

    @days               # ($days[0], $days[1],... $days[n])
    @days[3,4,5]        # same as ($days[3],$days[4],$days[5])
    @days{'a','c'}      # same as ($days{'a'},$days{'c'})

Entire hashes are denoted by '%':

ハッシュ全体は '%' で示します:

    %days               # (key1, val1, key2, val2 ...)

In addition, subroutines are named with an initial '&', though this is optional when unambiguous, just as the word "do" is often redundant in English. Symbol table entries can be named with an initial '*', but you don't really care about that yet (if ever :-).

さらに、サブルーチンは名前の前に '&' を付けて示しますが、英語でもほとんど 使われなくなった "do" のように、曖昧にならなければ、省略できます。 シンボルテーブルのエントリは、名前に '*' を付けて示すことができますが、 (気にする気があっても :-)まだ気にする必要はありません。

Every variable type has its own namespace, as do several non-variable identifiers. This means that you can, without fear of conflict, use the same name for a scalar variable, an array, or a hash--or, for that matter, for a filehandle, a directory handle, a subroutine name, a format name, or a label. This means that $foo and @foo are two different variables. It also means that $foo[1] is a part of @foo, not a part of $foo. This may seem a bit weird, but that's okay, because it is weird.

変数のすべての型には、いくつかの変数でない識別子と同様、 それぞれの名前空間があります。 これは、衝突を心配せずに、スカラ変数、配列、ハッシュ -- さらに ファイルハンドル、ディレクトリハンドル、サブルーチン名、フォーマット名、 ラベルに、同じ名前を付けることができることを意味します。 つまり、$foo@foo は 2 つの異なる変数であるということです。 また、$foo[1]@foo の一部であって、$foo の一部ではありません。 少々奇妙に思えるかもしれませんが、それで良いのです; 奇妙なのですから。

Because variable references always start with '$', '@', or '%', the "reserved" words aren't in fact reserved with respect to variable names. They are reserved with respect to labels and filehandles, however, which don't have an initial special character. You can't have a filehandle named "log", for instance. Hint: you could say open(LOG,'logfile') rather than open(log,'logfile'). Using uppercase filehandles also improves readability and protects you from conflict with future reserved words. Case is significant--"FOO", "Foo", and "foo" are all different names. Names that start with a letter or underscore may also contain digits and underscores.

変数の参照は、いつも '$'、'@'、'%' で始まりますから、「予約」語は、 変数名としては、本当の意味で予約されているわけではありません。 しかしながら、先頭に特別な文字を付けない、ラベルやファイルハンドルとしては、 予約されている ことになります。 たとえば、"log" といった名前のファイルハンドルを使うことはできません。 ヒント: open(log,'logfile') などではなく、 open(LOG,'logfile') としてください。 大文字のファイルハンドルを使えば、読みやすくもなりますし、 将来に渡る予約語との衝突も避けられます。 大文字と小文字は 区別されます から、"FOO"、"Foo"、"foo" は、 すべて違う名前です。 英字と下線で始まる名前は、名前の一部に数字や下線を含むことができます。

It is possible to replace such an alphanumeric name with an expression that returns a reference to the appropriate type. For a description of this, see perlref.

そのような英数字の名前を、適切な型へのリファレンスを返す式で 置き換えることも可能です。 詳しくは、perlref を参照してください。

Names that start with a digit may contain only more digits. Names that do not start with a letter, underscore, digit or a caret are limited to one character, e.g., $% or $$. (Most of these one character names have a predefined significance to Perl. For instance, $$ is the current process id. And all such names are reserved for Perl's possible use.)

数字で始まる名前には、数字しか含めることができません。 英字、下線、数字、キャレット以外の文字で始まる名前は、 $%$$ のように 1 文字に限定されます。 (これら 1 文字の名前の多くは、Perl があらかじめ意味を定めています。 たとえば、$$ はカレントプロセスのプロセス ID を示します。 そしてこれらの名前全ては Perl 自身の仕様のために予約されています。)

識別子のパース

Up until Perl 5.18, the actual rules of what a valid identifier was were a bit fuzzy. However, in general, anything defined here should work on previous versions of Perl, while the opposite -- edge cases that work in previous versions, but aren't defined here -- probably won't work on newer versions. As an important side note, please note that the following only applies to bareword identifiers as found in Perl source code, not identifiers introduced through symbolic references, which have much fewer restrictions. If working under the effect of the use utf8; pragma, the following rules apply:

Perl 5.18 まで、何が正当な識別子かに関する実際の規則は少し曖昧でした。 しかし、一般的に、ここで定義されたものは過去のバージョンの Perl でも 動作するはずです; しかし、逆 -- 以前のバージョンで動作していたエッジケースで ここで定義されていないもの -- はおそらく新しいバージョンでは動作しません。 重要な補足として、後述するものは Perl ソースコードに現れる裸の識別子のみに 適用されるもので、遥かに制限の少ないシンボリックリファレンスで導入される 識別子には適用されないことに注意してください。 use utf8; プラグマが有効な場合、以下の規則が適用されます:

    / (?[ ( \p{Word} & \p{XID_Start} ) + [_] ])
      (?[ ( \p{Word} & \p{XID_Continue} ) ]) *    /x

That is, a "start" character followed by any number of "continue" characters. Perl requires every character in an identifier to also match \w (this prevents some problematic cases); and Perl additionally accepts identifier names beginning with an underscore.

つまり、「開始」文字に引き続いて任意の数の「継続」文字です。 Perl は識別子の全ての文字について \w にマッチングすることを要求します (これにより一部の問題を回避します); また、Perl は下線で始まる識別子も 受け入れます。

If not under use utf8, the source is treated as ASCII + 128 extra generic characters, and identifiers should match

use utf8 が有効でない場合、ソースは ASCII + 128 の追加の一般文字として 扱われ、識別子は以下にマッチしなければなりません

    / (?aa) (?!\d) \w+ /x

That is, any word character in the ASCII range, as long as the first character is not a digit.

つまり、 ASCII の範囲の任意の単語文字で、先頭が数字でないものです。

There are two package separators in Perl: A double colon (::) and a single quote ('). Use of ' as the package separator is deprecated and will be removed in Perl 5.40. Normal identifiers can start or end with a double colon, and can contain several parts delimited by double colons. Single quotes have similar rules, but with the exception that they are not legal at the end of an identifier: That is, $'foo and $foo'bar are legal, but $foo'bar' is not.

Perl には二つのパッケージセパレータがあります: コロン二つ (::) と シングルクォート (') です。 パッケージ区切り文字としての ' の使用は廃止予定で、 Perl 5.40 で削除される予定です。 通常の識別子はコロン二つで開始または終了でき、コロン二つで区切られた 複数の部分を含むことができます。 シングルクォートは似たような規則を持ちますが、識別子の末尾に付けるのは 不正であるという例外があります: つまり、$'foo$foo'bar は正当ですが、 $foo'bar' は違います。

Additionally, if the identifier is preceded by a sigil -- that is, if the identifier is part of a variable name -- it may optionally be enclosed in braces.

さらに、識別子の先頭に印 (sigil) が付いている場合 -- つまり、 識別子が変数名の一部の場合 -- 識別子はオプションで中かっこで囲むことも できます。

While you can mix double colons with singles quotes, the quotes must come after the colons: $::::'foo and $foo::'bar are legal, but $::'::foo and $foo'::bar are not.

コロン二つとシングルクォートを混ぜることは出来ますが、シングルクォートは コロンの後に来なければなりません: $::::'foo$foo::'bar は正当ですが、 $::'::foo$foo'::bar は違います。

Put together, a grammar to match a basic identifier becomes

まとめると、基本識別子にマッチングする文法は

 /
  (?(DEFINE)
      (?<variable>
          (?&sigil)
          (?:
                  (?&normal_identifier)
              |   \{ \s* (?&normal_identifier) \s* \}
          )
      )
      (?<normal_identifier>
          (?: :: )* '?
           (?&basic_identifier)
           (?: (?= (?: :: )+ '? | (?: :: )* ' ) (?&normal_identifier) )?
          (?: :: )*
      )
      (?<basic_identifier>
        # is use utf8 on?
          (?(?{ (caller(0))[8] & $utf8::hint_bits })
              (?&Perl_XIDS) (?&Perl_XIDC)*
            | (?aa) (?!\d) \w+
          )
      )
      (?<sigil> [&*\$\@\%])
      (?<Perl_XIDS> (?[ ( \p{Word} & \p{XID_Start} ) + [_] ]) )
      (?<Perl_XIDC> (?[ \p{Word} & \p{XID_Continue} ]) )
  )
 /x

Meanwhile, special identifiers don't follow the above rules; For the most part, all of the identifiers in this category have a special meaning given by Perl. Because they have special parsing rules, these generally can't be fully-qualified. They come in six forms (but don't use forms 5 and 6):

一方、特殊識別子はこの規則に従いません; ほとんどの部分において、このカテゴリの 全ての識別子は Perl によって特別な意味を与えられています。 これらは特別なパース規則を持つので、一般的に完全に定義できません。 これらには六つの形式があります(但し型式 5 と 6 は使わないでください):

  1. A sigil, followed solely by digits matching \p{POSIX_Digit}, like $0, $1, or $10000.

    印に引き続いて $0, $1, $10000 のように \p{POSIX_Digit} に マッチングするもの。

  2. A sigil followed by a single character matching the \p{POSIX_Punct} property, like $! or %+, except the character "{" doesn't work.

    $!%+ のように、印に引き続いて \p{POSIX_Punct} 特性に マッチングする単一の文字; 但し、文字 "{" は動作しません。

  3. A sigil, followed by a caret and any one of the characters [][A-Z^_?\], like $^V or $^].

    印に引き続いてキャレットと ($^V$^W のような) [][A-Z^_?\] の いずれかの文字。

  4. Similar to the above, a sigil, followed by bareword text in braces, where the first character is a caret. The next character is any one of the characters [][A-Z^_?\], followed by ASCII word characters. An example is ${^GLOBAL_PHASE}.

    前述と同様に、印に引き続いて中かっこで囲まれた裸の単語; その最初の文字は キャレット。 次の文字は [][A-Z^_?\] で、引き続いて ASCII 文字。 例は ${^GLOBAL_PHASE}

  5. A sigil, followed by any single character in the range [\xA1-\xAC\xAE-\xFF] when not under "use utf8". (Under "use utf8", the normal identifier rules given earlier in this section apply.) Use of non-graphic characters (the C1 controls, the NO-BREAK SPACE, and the SOFT HYPHEN) has been disallowed since v5.26.0. The use of the other characters is unwise, as these are all reserved to have special meaning to Perl, and none of them currently do have special meaning, though this could change without notice.

    "use utf8" の基でない場合に、印に引き続いて [\xA1-\xAC\xAE-\xFF] の範囲の単一の文字。 ("use utf8" の元では、この章の前の部分に書かれている通常の 識別子規則が適用されます。) 非表示文字 (C1 制御文字、NO-BREAK SPACE, SOFT HYPHEN) の仕様は v5.26.0 から使えません。 その他の文字の使用も賢明ではありません; これらは全て Perl が特別な 意味を持つために予約されていて、どれも現在は特別な意味を持っていませんが、 これは警告為しに変更されるかもしれないからです。

    Note that an implication of this form is that there are identifiers only legal under "use utf8", and vice-versa, for example the identifier $état is legal under "use utf8", but is otherwise considered to be the single character variable followed by the bareword "tat", the combination of which is a syntax error.

    この型式により、"use utf8" の基でのみ有効な識別子やその逆が あることに注意してください; 例えば、識別子 $état"use utf8" の基では有効ですが、さもなければこれは 1 文字変数 に引き続く裸の単語 "tat" と考えられ、この組み合わせは 文法エラーになります。

  6. This is a combination of the previous two forms. It is valid only when not under "use utf8" (normal identifier rules apply when under "use utf8"). The form is a sigil, followed by text in braces, where the first character is any one of the characters in the range [\x80-\xFF] followed by ASCII word characters up to the trailing brace.

    これは前述の二つの型式の組み合わせです。 これは "use utf8" の基でない場合にのみ有効です ("use utf8" の基では通常の識別子規則が適用されますす). この型式は印に引き続いて中かっこで囲まれたテキストで、その最初の文字は [\x80-\xFF] で、それに引き続いて閉じ中かっこまで ASCII 単語文字です。

    The same caveats as the previous form apply: The non-graphic characters are no longer allowed with "use utf8", it is unwise to use this form at all, and utf8ness makes a big difference.

    一つ前の型式と同じ問題があります: 非表示文字は "use utf8" ではもはや 許可されず、この型式自体が賢明では無く、utf8 かどうかで大きな違いがあります。

Prior to Perl v5.24, non-graphical ASCII control characters were also allowed in some situations; this had been deprecated since v5.20.

Perl v5.24 より前では、非表示 ASCII 制御文字も場合によっては許されていました; これは v5.20 から廃止予定でした。

コンテキスト

The interpretation of operations and values in Perl sometimes depends on the requirements of the context around the operation or value. There are two major contexts: list and scalar. Certain operations return list values in contexts wanting a list, and scalar values otherwise. If this is true of an operation it will be mentioned in the documentation for that operation. In other words, Perl overloads certain operations based on whether the expected return value is singular or plural. Some words in English work this way, like "fish" and "sheep".

Perl における演算や値の解釈は、その演算や値の置かれたコンテキストからの 要求に依存する場合があります。 このコンテキストというものには大きく二つあり、リストコンテキストと スカラコンテキストと呼ばれます。 リストが要求されるコンテキストではリスト値を返し、 そうでなければスカラ値を返すような演算も存在します。 そのような演算については、ドキュメントでその演算に触れるときに 付記しています。 言い方を変えると、Perl では、ある種の演算が一つの値を返して欲しいか、 複数の値を返して欲しいかによって多重定義されているということです。 "fish" や "sheep" といった、単複同形の英単語と似ているかもしれません。

In a reciprocal fashion, an operation provides either a scalar or a list context to each of its arguments. For example, if you say

逆に演算子は、その引数がスカラコンテキストかリストコンテキストの いずれかで解釈されるかを決めてしまいます。 例えば、以下のようにすると:

    int( <STDIN> )

the integer operation provides scalar context for the <> operator, which responds by reading one line from STDIN and passing it back to the integer operation, which will then find the integer value of that line and return that. If, on the other hand, you say

int 演算子は、自分の引数である <> 演算子がスカラコンテキストで 評価されることを期待するため、STDIN から一行を読み出して int 演算子に渡します; それから、その行から整数値を取り出して 返すことになります。 これに対して、以下のようにすると:

    sort( <STDIN> )

then the sort operation provides list context for <>, which will proceed to read every line available up to the end of file, and pass that list of lines back to the sort routine, which will then sort those lines and return them as a list to whatever the context of the sort was.

sort 演算子は <> 演算子がリストコンテキストで評価されるために 、 <> は STDIN から読める限り最後の行まで読み出して、 そのリストを sort のルーチンに渡します; それから受け取った行のリストを ソートし、その結果のリストが戻り値となります。

Assignment is a little bit special in that it uses its left argument to determine the context for the right argument. Assignment to a scalar evaluates the right-hand side in scalar context, while assignment to an array or hash evaluates the righthand side in list context. Assignment to a list (or slice, which is just a list anyway) also evaluates the right-hand side in list context.

代入演算は少し特殊です; 代入では、右引数のコンテキストを決めるために左引数が 使われます。 スカラへの代入では、右側をスカラコンテキストで評価しますが、 配列やハッシュに対する代入では、右側をリストコンテキストで 評価することになります。 リスト(あるいはスライス; 要するにリストですが)への代入も、 右側をリストコンテキストで評価することになります。

When you use the use warnings pragma or Perl's -w command-line option, you may see warnings about useless uses of constants or functions in "void context". Void context just means the value has been discarded, such as a statement containing only "fred"; or getpwuid(0);. It still counts as scalar context for functions that care whether or not they're being called in list context.

use warnings プラグマや Perl の -w コマンドラインオプションを使うと、 「無効コンテキスト」での定数や関数の無意味な使用について警告が出ます。 無効コンテキストは、"fred";getpwuid(0); のみを含む文のように、 単に値が捨てられることを意味します。 リストコンテキストで呼び出されたかどうかを考慮する関数にとっては、 これはやはりスカラコンテキストとして扱われます。

User-defined subroutines may choose to care whether they are being called in a void, scalar, or list context. Most subroutines do not need to bother, though. That's because both scalars and lists are automatically interpolated into lists. See "wantarray" in perlfunc for how you would dynamically discern your function's calling context.

ユーザが定義するサブルーチンは、自分が無効、スカラ、リストのどの コンテキストで呼ばれたかを意識することができます。 しかし、多くのサブルーチンでは意識する必要もないでしょう。 スカラ値とリストは自動的にリストに展開されるからです。 関数が呼び出されたコンテキストを動的に識別する方法については、 "wantarray" in perlfunc を参照してください。

スカラ値

All data in Perl is a scalar, an array of scalars, or a hash of scalars. A scalar may contain one single value in any of three different flavors: a number, a string, or a reference. In general, conversion from one form to another is transparent. Although a scalar may not directly hold multiple values, it may contain a reference to an array or hash which in turn contains multiple values.

Perlにおける全てのデータは、スカラか、スカラの配列か、スカラの ハッシュとなります。 スカラは、数値、文字列、リファレンスのいずれか一つの値を保持します。 一般的には、ある種類から他の種類への変換は透過的です。 スカラは直接複数の値を保持することはできませんが、複数の値を保持している 配列やハッシュに対するリファレンスを保持することができます。

Scalars aren't necessarily one thing or another. There's no place to declare a scalar variable to be of type "string", type "number", type "reference", or anything else. Because of the automatic conversion of scalars, operations that return scalars don't need to care (and in fact, cannot care) whether their caller is looking for a string, a number, or a reference. Perl is a contextually polymorphic language whose scalars can be strings, numbers, or references (which includes objects). Although strings and numbers are considered pretty much the same thing for nearly all purposes, references are strongly-typed, uncastable pointers with builtin reference-counting and destructor invocation.

スカラは何かであることを宣言する必要はありません。 あるスカラ変数が、「文字列」型、「数値」型、「リファレンス」型、 あるいはその他の型であるように宣言する方法はありません。 これは、スカラ、スカラを返す操作の自動変換はその呼び出し元が 文字列、数値、リファレンスのどれを対象にしているのかを気に する必要がない(実際は、気にすることができない)ためです。 Perl はスカラが文字列、数値、リファレンス (オブジェクトを含みます)を 保持することのできる文脈的多態言語 (contextually polymorphic language) です。 文字列と数値は、ほとんど全ての目的に対して適当であるように思われますが、 リファレンスは組み込みのリファレンスカウントとデストラクタとを 持っている、キャストすることのできない強く型付けされたポインタです。

A scalar value is interpreted as FALSE in the Boolean sense if it is undefined, the null string or the number 0 (or its string equivalent, "0"), and TRUE if it is anything else. The Boolean context is just a special kind of scalar context where no conversion to a string or a number is ever performed. Negation of a true value by ! or not returns a special false value. When evaluated as a string it is treated as "", but as a number, it is treated as 0. Most Perl operators that return true or false behave this way.

スカラ値は、その値が未定義値か空文字列か数値の 0 (あるいは同値な文字列 "0") の場合には、真偽値の偽として扱われ、それ以外のもの全てでは 真として扱われます。 真偽値コンテキストは、単に文字列や数値への変換が行われなかった 特別なスカラコンテキストとして扱われます。 !not によって真の値を否定すると、特別な偽の値を返します。 これが文字列として評価されるとこれは "" として扱われますが、 数値として評価されると、これは 0 として扱われます。 真または偽を返すほとんどの Perl 演算子はこのように振る舞います。

There are actually two varieties of null strings (sometimes referred to as "empty" strings), a defined one and an undefined one. The defined version is just a string of length zero, such as "". The undefined version is the value that indicates that there is no real value for something, such as when there was an error, or at end of file, or when you refer to an uninitialized variable or element of an array or hash. Although in early versions of Perl, an undefined scalar could become defined when first used in a place expecting a defined value, this no longer happens except for rare cases of autovivification as explained in perlref. You can use the defined() operator to determine whether a scalar value is defined (this has no meaning on arrays or hashes), and the undef() operator to produce an undefined value.

空文字列には、実は定義済みと未定義の 2 種類があります。 定義済みの値は "" のような、単に長さ 0 の文字列です。 未定義の空文字列は、エラーがあったときや、ファイルの終わりに達したとき、 初期化していない変数や配列やハッシュの要素を参照したときなど、 何かに対する実際の値が存在しないことを示します。 初期のバージョンの Perl では、未定義のスカラは、最初に定義済みで あるかのように使ったときに定義済みとなり得ますが、これはもはや、 perlref で説明している自動有効化が起きる稀な場合を除いて、起こりません。 値が定義済みであるかどうかを調べるために defined() 演算子を 使うことができ(これは配列やハッシュに対しては無意味です)、 未定義値を生成するために undef() 演算子を使えます。

To find out whether a given string is a valid non-zero number, it's sometimes enough to test it against both numeric 0 and also lexical "0" (although this will cause noises if warnings are on). That's because strings that aren't numbers count as 0, just as they do in awk:

与えられた文字列が正当な非ゼロの数値であるかどうかを確かめるには、 数値の 0 か lexical な "0" に対してテストすれば十分な場合もあります (もっともこれは警告が有効ならノイズを引き起こします)。 数値ではない文字列は、awk のように 0 とはみなすことはしないからです:

    if ($str == 0 && $str ne "0")  {
        warn "That doesn't look like a number";
    }

That method may be best because otherwise you won't treat IEEE notations like NaN or Infinity properly. At other times, you might prefer to determine whether string data can be used numerically by calling the POSIX::strtod() function or by inspecting your string with a regular expression (as documented in perlre).

このメソッドは最良です; なぜなら、さもなければ NaNInfinity のような IEEE 記法の 属性を扱えないからです。 その他の場合、データが数値であるかどうかを検査するためには、 POSIX::strtod() 関数を呼び出すか、(perlre に記述されているように) 正規表現を使って文字列を調べるとよいでしょう。

    warn "has nondigits"        if     /\D/;
    warn "not a natural number" unless /^\d+$/;             # rejects -3
    warn "not an integer"       unless /^-?\d+$/;           # rejects +3
    warn "not an integer"       unless /^[+-]?\d+$/;
    warn "not a decimal number" unless /^-?\d+\.?\d*$/;     # rejects .2
    warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)$/;
    warn "not a C float"
        unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/;

The length of an array is a scalar value. You may find the length of array @days by evaluating $#days, as in csh. However, this isn't the length of the array; it's the subscript of the last element, which is a different value since there is ordinarily a 0th element. Assigning to $#days actually changes the length of the array. Shortening an array this way destroys intervening values. Lengthening an array that was previously shortened does not recover values that were in those elements.

配列の大きさはスカラ値です。 配列 @days の大きさは、csh のように $#days を評価するとわかります。 しかし、これは大きさではありません; 最後の要素に対する添え字になり、通常は 0 番目の要素があるので違う値に なります。 $#days に代入を行なうと実際の配列の大きさも変化します。 この方法で配列を小さくすると、見えなくなった部分の値は破壊されます。 小さくした配列を再び大きくしても、以前存在した要素に対する前の値が 回復することはありません。

You can also gain some minuscule measure of efficiency by pre-extending an array that is going to get big. You can also extend an array by assigning to an element that is off the end of the array. You can truncate an array down to nothing by assigning the null list () to it. The following are equivalent:

大きくなるであろう配列をあらかじめ大きくしておくことで、 ほんの少しだけ効率を向上させることもできます。 最後の要素よりも後ろに離れた位置に代入を行なうことでも、 配列を大きくすることができます。 配列に空リスト () を代入すると、何も無い状態にまで切り詰められます。 以下は等価です:

    @whatever = ();
    $#whatever = -1;

If you evaluate an array in scalar context, it returns the length of the array. (Note that this is not true of lists, which return the last value, like the C comma operator, nor of built-in functions, which return whatever they feel like returning.) The following is always true:

配列をスカラコンテキストで評価すると、配列の大きさが返されます。 (これはリストに対しては成り立たないことに注意してください; この場合には、C のカンマ演算子と同じように最後の値が返され、 組み込み関数のように値を返すことはしません。) 以下の式は常に真となります:

    scalar(@whatever) == $#whatever + 1;

Some programmers choose to use an explicit conversion so as to leave nothing to doubt:

曖昧さをなくすために明示的に変換することを選ぶプログラマもいます:

    $element_count = scalar(@whatever);

If you evaluate a hash in scalar context, it returns a false value if the hash is empty. If there are any key/value pairs, it returns a true value. A more precise definition is version dependent.

ハッシュをスカラコンテキストで評価した場合、ハッシュが空のときにだけ 偽の値が返されます。 キー/値のペアが登録されていれば、真の値を返します。 より正確な定義はバージョンに依存します。

Prior to Perl 5.25 the value returned was a string consisting of the number of used buckets and the number of allocated buckets, separated by a slash. This is pretty much useful only to find out whether Perl's internal hashing algorithm is performing poorly on your data set. For example, you stick 10,000 things in a hash, but evaluating %HASH in scalar context reveals "1/16", which means only one out of sixteen buckets has been touched, and presumably contains all 10,000 of your items. This isn't supposed to happen.

Perl 5.25 より前では、返される値は使用しているエントリの数と、 割り付けられているエントリの数を、スラッシュで区切った文字列でした。 これは、与えたデータに対して、Perl の内部のハッシュのアルゴリズムが、 うまく動作しないかを確認するときくらいにしか使えませんが。 たとえば、ハッシュに 10,000 個 のものを入れ、%HASH をスカラコンテキストで 評価したときに 1/16 が得られれば、16 のうち一つのエントリだけが使われ、 おそらくそこに 10,000個 すべてが入っていることを意味します。 これはほとんど起こりそうもないことです。

As of Perl 5.25 the return was changed to be the count of keys in the hash. If you need access to the old behavior you can use Hash::Util::bucket_ratio() instead.

Perl 5.25 から、ハッシュ内のキーの数を返すように変わりました。 古い振る舞いにアクセスする必要がある場合、 代わりに Hash::Util::bucket_ratio() を使ってください。

If a tied hash is evaluated in scalar context, the SCALAR method is called (with a fallback to FIRSTKEY).

tie したハッシュがスカラコンテキストで評価されると、 (FIRSTKEY へのフォールバックと) SCALAR メソッドが呼び出されます。

You can preallocate space for a hash by assigning to the keys() function. This rounds up the allocated buckets to the next power of two:

keys() 関数に代入をすることによって、ハッシュのためにあらかじめ スペースを割り当てることができます。 その際に、割り当てる要素の数はその数値以上で最小の 2 のべき乗に丸められます:

    keys(%users) = 1000;                # allocate 1024 buckets
    keys(%users) = 1000;                # 1024 要素割り付ける

スカラ値のコンストラクタ

Numeric literals are specified in any of the following floating point or integer formats:

数値リテラルは、以下の浮動小数点数と整数の形式で示されます:

 12345
 12345.67
 .23E-10             # a very small number
 3.14_15_92          # a very important number
 4_294_967_296       # underscore for legibility
 0xff                # hex
 0xdead_beef         # more hex
 0377                # octal (only numbers, begins with 0)
 0o12_345            # alternative octal (introduced in Perl 5.33.5)
 0b011011            # binary
 0x1.999ap-4         # hexadecimal floating point (the 'p' is required)

You are allowed to use underscores (underbars) in numeric literals between digits for legibility (but not multiple underscores in a row: 23__500 is not legal; 23_500 is). You could, for example, group binary digits by threes (as for a Unix-style mode argument such as 0b110_100_100) or by fours (to represent nibbles, as in 0b1010_0110) or in other groups.

数値リテラルを読みやすくするために、数字の間に下線を使えます (しかし連続した複数の下線は使えません: 23__500 は不正です; 23_500 は 妥当です)。 例えば、(Unix 式のモード引数のために、0b110_100_100 のように) 2 進数を 3 桁ごとにグループ分けしたり、(ニブルを表現するために、0b1010_0110 のように) 4 桁ごとにグループ分けしたり、あるいはその他の方法でグループ分け出来ます。

String literals are usually delimited by either single or double quotes. They work much like quotes in the standard Unix shells: double-quoted string literals are subject to backslash and variable substitution; single-quoted strings are not (except for \' and \\). The usual C-style backslash rules apply for making characters such as newline, tab, etc., as well as some more exotic forms. See "Quote and Quote-like Operators" in perlop for a list.

文字列リテラルは、シングルクォートかダブルクォートで区切られます。 これらは、標準 Unix シェルのクォートと同じように扱われます: ダブルクォートの文字列リテラルでは、バックスラッシュの置換と 変数の置換が行なわれ、シングルクォートの文字列では、 (\'\\を除いて)これらの置換は行なわれません。 普通の C 形式でのバックスラッシュの置換規則は、改行やタブを始め、ある種の 変わった形式のためにも使われます。 詳しくは "Quote and Quote-like Operators" in perlop を参照してください。

Hexadecimal, octal, or binary, representations in string literals (e.g. '0xff') are not automatically converted to their integer representation. The hex() and oct() functions make these conversions for you. See "hex" in perlfunc and "oct" in perlfunc for more details.

文字列リテラルの中で ('0xff' のように) 16 進、8 進、2 進で 表現されたものは、その値が表すものに自動的に変換されることはありません。 hex() や oct() といった関数がそのための変換を行います。 詳しくは "hex" in perlfunc"oct" in perlfunc を参照してください。

Hexadecimal floating point can start just like a hexadecimal literal, and it can be followed by an optional fractional hexadecimal part, but it must be followed by p, an optional sign, and a power of two. The format is useful for accurately presenting floating point values, avoiding conversions to or from decimal floating point, and therefore avoiding possible loss in precision. Notice that while most current platforms use the 64-bit IEEE 754 floating point, not all do. Another potential source of (low-order) differences are the floating point rounding modes, which can differ between CPUs, operating systems, and compilers, and which Perl doesn't control.

16 進浮動小数点数は 16 進リテラルのように始まり、オプションの 16 進小数部が引き続きますが、引き続いて p、オプションの符号および 2 の累乗がなければなりません。 この型式は、浮動小数点数を正確に表現し、10 進浮動小数点数との変換を 避けることで起こりうる精度の低下を避けるために有用です。 現在のプラットフォームのほとんどは 64 ビット IEEE 754 を使っていますが、 全てではないことに注意してください。 その他の違いの(より下位の)原因としては、浮動小数点数の丸めモードで、 CPU、オペレーティングシステム、コンパイラによって異なることがあり、 Perl は制御できません。

You can also embed newlines directly in your strings, i.e., they can end on a different line than they begin. This is nice, but if you forget your trailing quote, the error will not be reported until Perl finds another line containing the quote character, which may be much further on in the script. Variable substitution inside strings is limited to scalar variables, arrays, and array or hash slices. (In other words, names beginning with $ or @, followed by an optional bracketed expression as a subscript.) The following code segment prints out "The price is $100."

また、文字列に直接、改行を埋め込むこともできます; つまり、文字列は、開始した 行で終了する必要はないと言うことです。 これは素晴らしいのですが、終了のクォートを付け忘れた場合には、次に クォート文字が見つかるまでの間、Perl はエラーを見つけることが できなくなります; それは、スクリプト上でずっと先になるかもしれません。 文字列中での変数の置換は、スカラ変数、配列、配列やハッシュのスライスに 限定されています。 (言い換えると、$ や@ で始まる識別子か、それに大かっこで括った添え字を つけたものです。) 次のプログラムは "The price is $100." と印字します。

    $Price = '$100';    # not interpolated
    print "The price is $Price.\n";     # interpolated

There is no double interpolation in Perl, so the $100 is left as is.

Perl では二重展開は行われないので、$100 はそのままになります。

By default floating point numbers substituted inside strings use the dot (".") as the decimal separator. If use locale is in effect, and POSIX::setlocale() has been called, the character used for the decimal separator is affected by the LC_NUMERIC locale. See perllocale and POSIX.

デフォルトでは、文字列に置換された浮動小数点数は小数点としてドット (".") を 使います。 use locale が有効で、POSIX::setlocale() が呼び出されている場合、 小数点として使われる文字は LC_NUMERIC ロケールによって影響を受けます。 perllocalePOSIX を参照してください。

中かっこを使った変数名の区切り

As in some shells, you can enclose the variable name in braces as a demarcator to disambiguate it from following alphanumerics and underscores or other text. You must also do this when interpolating a variable into a string to separate the variable name from a following double-colon or an apostrophe since these would be otherwise treated as a package separator:

いくつかのシェルと同じように、変数名の前後に区切りとして中かっこを入れて、 つながっている英数字および下線などから切り離せます。 変数を文字列に展開する時に、後に続くコロン 2 つやシングルクォートと 変数名を分割する場合にもそうしなければなりません; さもなければパッケージのセパレータとして扱われるからです:

    $who = "Larry";
    print PASSWD "${who}::0:0:Superuser:/:/bin/perl\n";
    print "We use ${who}speak when ${who}'s here.\n";

Without the braces, Perl would have looked for a $whospeak, a $who::0, and a $who's variable. The last two would be the $0 and the $s variables in the (presumably) non-existent package who.

中かっこなしでは、Perl は変数 $whospeak, $who::0, $who's を探します。 後ろ二つは、(おそらく)存在しないパッケージ who の変数 $0 と $s に なります。

In fact, a simple identifier within such curly braces is forced to be a string, and likewise within a hash subscript. Neither need quoting. Our earlier example, $days{'Feb'} can be written as $days{Feb} and the quotes will be assumed automatically. But anything more complicated in the subscript will be interpreted as an expression. This means for example that $version{2.0}++ is equivalent to $version{2}++, not to $version{'2.0'}++.

実際には、そのような中かっこの内側にある単純な識別子は、強制的に 文字列になります; ハッシュの添え字も同様です。 どちらもクォートは必要ありません。 先の例にあった、$days{'Feb'}$days{Feb} のように書くことができ、 自動的にクォートが仮定されます。 しかし、添え字により複雑な何かを使っている場合には式として解釈されます。 これは例えば、$version{2.0}++$version{2}++ と等価であり、 $version{'2.0'}++ ではないということを意味します。

There is a similar problem with interpolation with text that looks like array or hash access notation. Placing a simple variable like $who immediately in front of text like "[1]" or "{foo}" would cause the variable to be interpolated as accessing an element of @who or a value stored in %who:

配列やハッシュアクセス記法のように見えるテキストの変数展開にも 同様の問題があります。 "[1]""{foo}" のような文字の直前に $who のような単純な変数を置くと、変数は、@who の要素や %who に保管されている値にアクセスするように展開されます:

    $who = "Larry Wall";
    print "$who[1] is the father of Perl.\n";

would attempt to access index 1 of an array named @who. Again, using braces will prevent this from happening:

これは @who という名前の配列の添え字 1 にアクセスしようとします。 再び、中かっこを使うことでこれが起きるのを防げます:

    $who = "Larry Wall";
    print "${who}[1] is the father of Perl.\n";

will be treated the same as

これは次のものと同様に扱われます:

    $who = "Larry Wall";
    print $who . "[1] is the father of Perl.\n";

This notation also applies to more complex variable descriptions, such as array or hash access with subscripts. For instance

この記法は、添え地突きの配列やハッシュアクセスのような、 より複雑な変数表現にも適用できます。 例えば:

    @name = qw(Larry Curly Moe);
    print "Also ${name[0]}[1] was a member\n";

Without the braces the above example would be parsed as a two level array subscript in the @name array, and under use strict would likely produce a fatal exception, as it would be parsed like this:

中かっこなしでは、前述の例は @name 配列の 2 段階の配列添え字として パースされ、use strict の下ではおそらく致命的な例外が発生します; これは次のようにパースされるからです:

    print "Also " . $name[0][1] . " was a member\n";

and not as the intended:

次のような意図したものにはなりません:

    print "Also " . $name[0] . "[1] was a member\n";

A similar result may be derived by using a backslash on the first character of the subscript or package notation that is not part of the variable you want to access. Thus the above example could also be written:

似たような結果は、アクセスしたい変数の一部ではない、添え字やパッケージ 記法の最初の文字に逆スラッシュを使うことでも得られます。 従って、前述の例は次のようにも書けます:

    @name = qw(Larry Curly Moe);
    print "Also $name[0]\[1] was a member\n";

however for some special variables (multi character caret variables) the demarcated form using curly braces is the only way you can reference the variable at all, and the only way you can access a subscript of the variable via interpolation.

しかし、いくつかの特殊変数 (複数文字キャレット変数) では、 中かっこを使った境界を定める形式は、変数を参照する 唯一の 方法で、 変数展開によって変数の添え字にアクセスできる唯一の方法です。

Consider the magic array @{^CAPTURE} which is populated by the regex engine with the contents of all of the capture buffers in a pattern (see perlvar and perlre). The only way you can access one of these members inside of a string is via the braced (demarcated) form:

マジック配列 @{^CAPTURE} を考えてみます; これは正規表現エンジンによって、 あるパターンの全ての捕捉バッファの内容が展開されます (perlvarperlre 参照)。 文字列の中でこれらの要素の一つにアクセスする 唯一の 方法は、 中かっこを使った(境界を定める)形式によるものです:

    "abc"=~/(.)(.)(.)/
        and print "Second buffer is ${^CAPTURE[1]}";

is equivalent to

これは次と等価です:

    "abc"=~/(.)(.)(.)/
        and print "Second buffer is " . ${^CAPTURE}[1];

Saying @^CAPTURE is a syntax error, so it must be referenced as @{^CAPTURE}, and to access one of its elements in normal code you would write ${^CAPTURE}[1] . However when interpolating in a string "${^CAPTURE}[1]" would be equivalent to ${^CAPTURE} . "[1]", which does not even refer to the same variable! Thus the subscripts must also be placed inside of the braces: "${^CAPTURE[1]}".

@^CAPTURE とするのは文法エラーなので、@{^CAPTURE} として 参照 しなければならず、通常のコードでその要素の一つにアクセスするには、 ${^CAPTURE}[1] と書きます。 しかし、文字列の中で変数展開されるときは、 "${^CAPTURE}[1]"${^CAPTURE} . "[1]" と等価で、 同じ変数を参照すらしません! したがって、添え字 中かっこの 内側 に置かなければなりません: "${^CAPTURE[1]}"

The demarcated form using curly braces can be used with all the different types of variable access, including array and hash slices. For instance code like the following:

中かっこを使った境界を定める形式は、配列とハッシュスライスを含めた、 全ての異なった種類の変数アクセスに使えます。 例えば、次のようなコードは:

    @name = qw(Larry Curly Moe);
    local $" = " and ";
    print "My favorites were @{name[1,2]}.\n";

would output

次のものを出力します:

    My favorites were Curly and Moe.

特殊浮動小数点数: 無限 (Inf) と非数 (NaN)

Floating point values include the special values Inf and NaN, for infinity and not-a-number. The infinity can be also negative.

浮動小数点値には、それぞれ無限と非数を意味する特殊な値 InfNaN を 含みます。 無限は負数の場合もあります。

The infinity is the result of certain math operations that overflow the floating point range, like 9**9**9. The not-a-number is the result when the result is undefined or unrepresentable. Though note that you cannot get NaN from some common "undefined" or "out-of-range" operations like dividing by zero, or square root of a negative number, since Perl generates fatal errors for those.

無限は、9**9**9 のように、浮動小数点の範囲からオーバーフローした 特定の算術演算の結果です。 非数は、結果が未定義や表現不能の場合の結果です。 しかし、0 除算や負数の平方根のような、一般的な「未定義」や 「範囲外」演算では NaN を得ることはできないことに注意してください; Perl はこれらの場合には致命的エラーを発生させます。

The infinity and not-a-number have their own special arithmetic rules. The general rule is that they are "contagious": Inf plus one is Inf, and NaN plus one is NaN. Where things get interesting is when you combine infinities and not-a-numbers: Inf minus Inf and Inf divided by Inf are NaN (while Inf plus Inf is Inf and Inf times Inf is Inf). NaN is also curious in that it does not equal any number, including itself: NaN != NaN.

無限と非数は独自の特殊な算術規則を持ちます。 一般的な規則は、これらは「感染する」ということです: Inf に 1 を足すと Inf で、NaN に 1 を足すと NaN です。 ここで興味深いのは無限や非数を組み合わせた場合です: Inf から Inf を引いた場合と InfInf で割った場合は NaN です (一方 InfInf を足すとis Inf で、InfInf を掛けると Inf です)。 NaN は、自分自身を 含む あらゆる数と等しくないという点で興味深いです: NaN != NaN

Perl doesn't understand Inf and NaN as numeric literals, but you can have them as strings, and Perl will convert them as needed: "Inf" + 1. (You can, however, import them from the POSIX extension; use POSIX qw(Inf NaN); and then use them as literals.)

Perl は InfNaN を数値リテラルとして認識しませんが、 これらを文字列として保持することができ、Perl は必要に応じてこれらを 変換します: "Inf" + 1。 (しかし、POSIX エクステンションからこれらをインポートすることができます; use POSIX qw(Inf NaN); としてこれらをリテラルとして使います。)

Note that on input (string to number) Perl accepts Inf and NaN in many forms. Case is ignored, and the Win32-specific forms like 1.#INF are understood, but on output the values are normalized to Inf and NaN.

入力時 (文字列から数値) は Perl は様々な型式の InfNaN を 受け付けます。 大文字小文字は無視し、1.#INF のような Win32 特有の型式を理解しますが、 出力時の値は Inf および NaN に正規化されます。

バージョン文字列

A literal of the form v1.20.300.4000 is parsed as a string composed of characters with the specified ordinals. This form, known as v-strings, provides an alternative, more readable way to construct strings, rather than use the somewhat less readable interpolation form "\x{1}\x{14}\x{12c}\x{fa0}". This is useful for representing Unicode strings, and for comparing version "numbers" using the string comparison operators, cmp, gt, lt etc. If there are two or more dots in the literal, the leading v may be omitted.

v1.20.300.4000 の形のリテラルは、指定された序数を持つ文字からなる 文字列としてパースされます。 この形はv-文字列と呼ばれ、より読みにくい文字変換形式 "\x{1}\x{14}\x{12c}\x{fa0}" よりも読みやすい文字列を構成する方法を 提供します。 これは Unicode 文字列を表現するためや、バージョン「番号」を文字列比較 演算子 cmp, gt, lt などを使って比較するときに便利です。 もしリテラルに 2 つ以上のドットがある場合、先頭の v は省略できます。

    print v9786;              # prints SMILEY, "\x{263a}"
    print v102.111.111;       # prints "foo"
    print 102.111.111;        # same

Such literals are accepted by both require and use for doing a version check. Note that using the v-strings for IPv4 addresses is not portable unless you also use the inet_aton()/inet_ntoa() routines of the Socket package.

このようなリテラルは requireuse でバージョンチェックを行う場合に 受け入れられます。 v-文字列を IPv4 アドレスに使うと、Socket パッケージの inet_aton()/inet_ntoa() ルーチンも使わない限り、移植性がないことに 注意してください。

Note that since Perl 5.8.1 the single-number v-strings (like v65) are not v-strings before the => operator (which is usually used to separate a hash key from a hash value); instead they are interpreted as literal strings ('v65'). They were v-strings from Perl 5.6.0 to Perl 5.8.0, but that caused more confusion and breakage than good. Multi-number v-strings like v65.66 and 65.66.67 continue to be v-strings always.

Perl 5.8.1 から、 (v65 のような) 単一の数値のv-文字列は => 演算子 (ハッシュキーとハッシュの値を分けるために普通使われます) の前では v-文字列ではないことに注意してください; これはリテラル文字列 ('v65') として 扱われます。 これは Perl 5.6.0 から Perl 5.8.0 ではv-文字列でしたが、これはよいことよりも 大きな混乱と破壊を招きました。 v65.6665.66.67 のような複数の数値の v-文字列 は常にv-文字列で あり続けます。

特殊なリテラル

The special literals __FILE__, __LINE__, and __PACKAGE__ represent the current filename, line number, and package name at that point in your program. __SUB__ gives a reference to the current subroutine. They may be used only as separate tokens; they will not be interpolated into strings. If there is no current package (due to an empty package; directive), __PACKAGE__ is the undefined value. (But the empty package; is no longer supported, as of version 5.10.) Outside of a subroutine, __SUB__ is the undefined value. __SUB__ is only available in 5.16 or higher, and only with a use v5.16 or use feature "current_sub" declaration.

__FILE__, __LINE__, __PACKAGE__ という特殊なリテラルはそれぞれ、 カレントのファイル名、行番号、パッケージ名を表わします。 __SUB__ は現在のサブルーチンへのリファレンスを与えます。 これらは独立したトークンとしてのみ用いられます; 文字列中に展開されることはありません。 (空の package; 指示子によって)カレントパッケージが存在しない場合、 __PACKAGE__ は未定義値となります。 (しかし空の package; はバージョン 5.10 以降もはや対応していません。) サブルーチンの外側では、__SUB__ は未定義値です。 __SUB__ は 5.16 以降で、use v5.16 または use feature "current_sub" 宣言がある場合にのみ利用可能です。

The two control characters ^D and ^Z, and the tokens __END__ and __DATA__ may be used to indicate the logical end of the script before the actual end of file. Any following text is ignored by the interpreter unless read by the program as described below.

二つの制御文字 ^D と ^Z、およびトークン __END__ と __DATA__ は、 実際のファイルの終端より前にある論理的なスクリプトの終端を示すために 使うことができます。 これらの後にあるテキストは、後述するようにプログラムによって 読み込まれない限り、インタプリタから無視されます。

Text after __DATA__ may be read via the filehandle PACKNAME::DATA, where PACKNAME is the package that was current when the __DATA__ token was encountered. The filehandle is left open pointing to the line after __DATA__. The program should close DATA when it is done reading from it. (Leaving it open leaks filehandles if the module is reloaded for any reason, so it's a safer practice to close it.) For compatibility with older scripts written before __DATA__ was introduced, __END__ behaves like __DATA__ in the top level script (but not in files loaded with require or do) and leaves the remaining contents of the file accessible via main::DATA.

しかし、__DATA__ 以降のテキストはファイルハンドル PACKNAME::DATA を 通して読み出すことができます; ここで PACKNAME は __DATA__ トークンに 遭遇した時点でのカレントのパッケージ名です。 ファイルハンドルは __DATA__ の後の行を指して開かれたままです。 プログラムはここからデータを読み終わったら close DATA するべきです。 (これを開いたままにしておくと何らかの理由でモジュールが 再読み込みされたときにファイルハンドルがリークするので、閉じておくのが より安全な慣例です。) __DATA__ が導入される前に書かれた古いスクリプトとの互換性のために、 __END__ は、スクリプト(但し requiredo で読み込まれたファイルでは ないもの)のトップレベルでの __DATA__ のように振る舞い、 ファイルの残りの内容は main::DATA でアクセス可能なままになります。

  while (my $line = <DATA>) { print $line; }
  close DATA;
  __DATA__
  Hello world.

The DATA file handle by default has whatever PerlIO layers were in place when Perl read the file to parse the source. Normally that means that the file is being read bytewise, as if it were encoded in Latin-1, but there are two major ways for it to be otherwise. Firstly, if the __END__/__DATA__ token is in the scope of a use utf8 pragma then the DATA handle will be in UTF-8 mode. And secondly, if the source is being read from perl's standard input then the DATA file handle is actually aliased to the STDIN file handle, and may be in UTF-8 mode because of the PERL_UNICODE environment variable or perl's command-line switches.

デフォルトの DATA ファイルハンドルは has whatever PerlIO layers were in place when Perl read the file to parse the source. 通常これは、ファイルは Latin-1 でエンコードされているかのように バイト単位で読み込まれることを意味しますが、 そうならない場合が主に二つあります。 まず、 __END__/__DATA__ トークンが use utf8 プラグマのスコープ内にある場合、 DATA ハンドルは UTF-8 モードになります。 そして次に、ソースが perl の標準入力から読み込まれている場合、 DATA ファイルハンドルは実際には STDIN ファイルハンドルの別名で、 これは PERL_UNICODE 環境変数や perl のコマンドラインオプションによって UTF-8 モードになっているかも知れません。

See SelfLoader for more description of __DATA__, and an example of its use. Note that you cannot read from the DATA filehandle in a BEGIN block: the BEGIN block is executed as soon as it is seen (during compilation), at which point the corresponding __DATA__ (or __END__) token has not yet been seen.

__DATA__ の詳細とそれをつかった例は SelfLoader を参照してください。 BEGIN ブロックでは、ファイルハンドル DATA から読み出せないことに 注意してください; BEGIN ブロックはそれが見つかった時点で即実行されるので、 __DATA__(や __END__)トークンがどこにあるのかがわからないのです。

裸の単語

A word that has no other interpretation in the grammar will be treated as if it were a quoted string. These are known as "barewords". As with filehandles and labels, a bareword that consists entirely of lowercase letters risks conflict with future reserved words, and if you use the use warnings pragma or the -w switch, Perl will warn you about any such words. Perl limits barewords (like identifiers) to about 250 characters. Future versions of Perl are likely to eliminate these arbitrary limitations.

文法的に別の解釈ができない単語は、クォート文字列であるかのように扱われます。 これは「裸の単語」(bareword) と呼ばれます。 ファイルハンドルやラベルと同様に、小文字だけからなる裸の単語は将来、 予約語とぶつかる危険があります; そのような単語があった場合、 use warnings プラグマや -w スイッチをつけることでPerl がそのような 単語を指摘してくれます。 Perl は (識別子のような) 裸の単語をおそよ 250 文字に制限しています。 将来のバージョンの Perl はこれらの恣意的な制限は取り除かれるでしょう。

Some people may wish to outlaw barewords entirely. If you say

裸の単語をなくして欲しいという人もいます。 以下のようにすると:

    use strict 'subs';

then any bareword that would NOT be interpreted as a subroutine call produces a compile-time error instead. The restriction lasts to the end of the enclosing block. An inner block may countermand this by saying no strict 'subs'.

サブルーチンコールと解釈できない裸の単語がコンパイル時にエラーとなります。 この制約は囲っているブロックの終わりまで有効です。 内側のブロックで no strict 'subs'と書くことで、この機能を 撤回することもできます。

配列の展開

Arrays and slices are interpolated into double-quoted strings by joining the elements with the delimiter specified in the $" variable ($LIST_SEPARATOR if "use English;" is specified), space by default. The following are equivalent:

配列とスライスは、ダブルクォート文字列中で、要素を変数 <$"> ("use English;" が指定されていれば $LIST_SEPARATOR) 中に 示す区切り文字(デフォルトはスペース) でつなげて展開されます。 以下は等価です:

    $temp = join($", @ARGV);
    system "echo $temp";

    system "echo @ARGV";

Within search patterns (which also undergo double-quotish substitution) there is an unfortunate ambiguity: Is /$foo[bar]/ to be interpreted as /${foo}[bar]/ (where [bar] is a character class for the regular expression) or as /${foo[bar]}/ (where [bar] is the subscript to array @foo)? If @foo doesn't otherwise exist, then it's obviously a character class. If @foo exists, Perl takes a good guess about [bar], and is almost always right. If it does guess wrong, or if you're just plain paranoid, you can force the correct interpretation with curly braces as above.

検索パターン (ここでも、ダブルクォートのような置換が行なわれます) の中では、 解釈する上で不幸な曖昧さがあります: /$foo[bar]/ は、/${foo}[bar]/ と 解釈される(この場合 [bar]は、正規表現の文字クラス) のでしょうか、それとも /${foo[bar]}/ と解釈される (この場合 [bar] は、配列 @foo の添え字) のでしょうか? @foo が他に存在しない場合には、明らかに文字クラスとなります。 @foo が存在すれば、Perl が [bar] の意味に見当をつけますが、たいてい 正しい解釈をします。 もし見当があたっていないときや偏執的にこだわりたい時には、上に 書いたように中かっこを付けて強制的に解釈のしかたを決めることができます。

If you're looking for the information on how to use here-documents, which used to be here, that's been moved to "Quote and Quote-like Operators" in perlop.

以前ここにあった、ヒアドキュメントの使い方に関する情報を探しているのなら、 その情報は "Quote and Quote-like Operators" in perlop に移動しました。

リスト値のコンストラクター

List values are denoted by separating individual values by commas (and enclosing the list in parentheses where precedence requires it):

リスト値は、個々の値をコンマで区切って (必要に応じて括弧で括って) 示されます:

    (LIST)

In a context not requiring a list value, the value of what appears to be a list literal is simply the value of the final element, as with the C comma operator. For example,

リスト値が要求されていないコンテキストでは、リストリテラルのように みえる値の場合は、C のコンマ演算子の場合のように、単に最後の要素の 値が使われます。 例えば:

    @foo = ('cc', '-E', $bar);

assigns the entire list value to array @foo, but

これはリスト値全体を配列 @foo に代入しますが:

    $foo = ('cc', '-E', $bar);

assigns the value of variable $bar to the scalar variable $foo. Note that the value of an actual array in scalar context is the length of the array; the following assigns the value 3 to $foo:

これは変数 $bar の値をスカラ変数 $foo に代入します。 本物の配列がスカラコンテキストで評価されたときの値は、その配列の 大きさとなります; 以下の例では、$foo に 3 という値が代入されます:

    @foo = ('cc', '-E', $bar);
    $foo = @foo;                # $foo gets 3

You may have an optional comma before the closing parenthesis of a list literal, so that you can say:

リストリテラルの閉じ括弧の前には余分にコンマを置いてかまいませんので、 以下のように書くことができます:

    @foo = (
        1,
        2,
        3,
    );

To use a here-document to assign an array, one line per element, you might use an approach like this:

配列への代入にヒアドキュメントを使うには、要素毎に 1 行となり、 以下のような手法が使えます:

    @sauces = <<End_Lines =~ m/(\S.*\S)/g;
        normal tomato
        spicy tomato
        green chile
        pesto
        white wine
    End_Lines

LISTs do automatic interpolation of sublists. That is, when a LIST is evaluated, each element of the list is evaluated in list context, and the resulting list value is interpolated into LIST just as if each individual element were a member of LIST. Thus arrays and hashes lose their identity in a LIST--the list

リストの中にリストがある場合には、自動的に展開されてしまいます。 これは、外側のリストが評価されると、リストの個々の要素がリストコンテキストで 評価され、その結果のリスト値の個々の値が、元のリストの要素であるかのように 展開されるのです。 つまり、リストの中では配列もハッシュも、その性質が現れてきません -- 以下のリストは

    (@foo,@bar,&SomeSub,%glarch)

contains all the elements of @foo followed by all the elements of @bar, followed by all the elements returned by the subroutine named SomeSub called in list context, followed by the key/value pairs of %glarch. To make a list reference that does NOT interpolate, see perlref.

@foo のすべての要素の後に @bar のすべての要素を続け、 その後に SomeSub というサブルーチンが返すすべての要素を続け、 最後に %glarch のキー/値のペアを続けたものを要素として持ちます。 展開 されない リストのリファレンスを作るためには、perlref を 参照してください。

The null list is represented by (). Interpolating it in a list has no effect. Thus ((),(),()) is equivalent to (). Similarly, interpolating an array with no elements is the same as if no array had been interpolated at that point.

空リストは () で表わされます。 リスト中で空リストを展開しても何も起こりません。 つまり、 ((),(),()) は () と等価です。 同様に、要素のない配列を展開することは、その場所に何も 展開しなかったのと同じことになります。

This interpolation combines with the facts that the opening and closing parentheses are optional (except when necessary for precedence) and lists may end with an optional comma to mean that multiple commas within lists are legal syntax. The list 1,,3 is a concatenation of two lists, 1, and 3, the first of which ends with that optional comma. 1,,3 is (1,),(3) is 1,3 (And similarly for 1,,,3 is (1,),(,),3 is 1,3 and so on.) Not that we'd advise you to use this obfuscation.

この展開は、開きかっこと閉じかっこは(優先順位のための必要性がなければ) 省略可能であるということと、リスト中に複数のカンマがあっても文法的に 有効なので、リストの最後に追加のカンマをつけられるということを 組み合わせたものです。 リスト 1,,3 は 2 つのリスト 1,3 の結合であり、 1 つ目のリストはオプションのカンマで終わっています。 1,,3(1,),(3)1,3 です (そして同様に 1,,,3(1,),(,),31,3 です、以下同様。) この暗黒面を使うよう勧めているわけではありません。

A list value may also be subscripted like a normal array. You must put the list in parentheses to avoid ambiguity. For example:

リスト値にも通常の配列と同じように、添え字をつけることができます。 リストには、曖昧さをなくすために、括弧を付けなくてはなりません。 例えば:

    # Stat returns list value.
    $time = (stat($file))[8];

    # SYNTAX ERROR HERE.
    $time = stat($file)[8];  # OOPS, FORGOT PARENTHESES

    # Find a hex digit.
    $hexdigit = ('a','b','c','d','e','f')[$digit-10];

    # A "reverse comma operator".
    return (pop(@foo),pop(@foo))[0];

Lists may be assigned to only when each element of the list is itself legal to assign to:

リスト自身を構成する個々の要素すべてに代入が許される場合にのみ、 全体のリストに代入を行なうことができます:

    ($x, $y, $z) = (1, 2, 3);

    ($map{'red'}, $map{'blue'}, $map{'green'}) = (0x00f, 0x0f0, 0xf00);

An exception to this is that you may assign to undef in a list. This is useful for throwing away some of the return values of a function:

この例外として、リストにundefを代入することもできます。 これは関数の戻り値の一部を捨て去るのに便利です:

    ($dev, $ino, undef, undef, $uid, $gid) = stat($file);

As of Perl 5.22, you can also use (undef)x2 instead of undef, undef. (You can also do ($x) x 2, which is less useful, because it assigns to the same variable twice, clobbering the first value assigned.)

Perl 5.22 から、undef, undef の代わりに (undef)x2 も使えます。 (($x) x 2 ともできますが、あまり有用ではありません; これは 同じ変数に 2 回代入され、最初に代入された値が上書きされるからです。)

When you assign a list of scalars to an array, all previous values in that array are wiped out and the number of elements in the array will now be equal to the number of elements in the right-hand list -- the list from which assignment was made. The array will automatically resize itself to precisely accommodate each element in the right-hand list.

スカラのリストを配列に代入すると、その配列の以前の値は全て削除されて 配列の要素数は右側のリスト -- 代入の元となるリスト -- の要素数と 同じになります。 配列は右側のリストの各要素に正確に適合するように自動的にサイズを変更します。

    use warnings;
    my (@xyz, $x, $y, $z);

    @xyz = (1, 2, 3);
    print "@xyz\n";                             # 1 2 3

    @xyz = ('al', 'be', 'ga', 'de');
    print "@xyz\n";                             # al be ga de

    @xyz = (101, 102);
    print "@xyz\n";                             # 101 102

When, however, you assign a list of scalars to another list of scalars, the results differ according to whether the left-hand list -- the list being assigned to -- has the same, more or fewer elements than the right-hand list.

しかし、スカラのリストを他のスカラのリストに代入すると、 左側のリスト -- 代入されるリスト -- が右側のリストと要素数が同じなのか 多いのか少ないのかによって結果が異なります。

    ($x, $y, $z) = (1, 2, 3);
    print "$x $y $z\n";                         # 1 2 3

    ($x, $y, $z) = ('al', 'be', 'ga', 'de');
    print "$x $y $z\n";                         # al be ga

    ($x, $y, $z) = (101, 102);
    print "$x $y $z\n";                         # 101 102
    # Use of uninitialized value $z in concatenation (.)
    # or string at [program] line [line number].

If the number of scalars in the left-hand list is less than that in the right-hand list, the "extra" scalars in the right-hand list will simply not be assigned.

左側のリストのスカラの数が右側のリストより少ない場合、 右側のリストの「余分な」スカラは単に代入されません。

If the number of scalars in the left-hand list is greater than that in the left-hand list, the "missing" scalars will become undefined.

左側のリストのスカラの数が右側のリストより多い場合、 「足りない」スカラは未定義になります。

    ($x, $y, $z) = (101, 102);
    for my $el ($x, $y, $z) {
        (defined $el) ? print "$el " : print "<undef>";
    }
    print "\n";
                                                # 101 102 <undef>

List assignment in scalar context returns the number of elements produced by the expression on the right side of the assignment:

スカラコンテキスト中のリスト代入は、代入の右辺にある式によって 生成された要素の数を返します:

    $x = (($foo,$bar) = (3,2,1));       # set $x to 3, not 2
    $x = (($foo,$bar) = f());           # set $x to f()'s return count

This is handy when you want to do a list assignment in a Boolean context, because most list functions return a null list when finished, which when assigned produces a 0, which is interpreted as FALSE.

これはブールコンテキストでリストの代入をしたいときに便利です; なぜなら、ほとんどのリスト関数は終了時に空リストを返すからです; これは代入が 0 を生成したときには、偽と解釈されます。

It's also the source of a useful idiom for executing a function or performing an operation in list context and then counting the number of return values, by assigning to an empty list and then using that assignment in scalar context. For example, this code:

これはまた、関数の実行や操作の処理をリストコンテキストで行い、 それからそれを空リストにからすからコンテキストでの代入を行うことで 返り値の数を数えるための便利な慣用法のもととなります。 例えば、以下のコードは:

    $count = () = $string =~ /\d+/g;

will place into $count the number of digit groups found in $string. This happens because the pattern match is in list context (since it is being assigned to the empty list), and will therefore return a list of all matching parts of the string. The list assignment in scalar context will translate that into the number of elements (here, the number of times the pattern matched) and assign that to $count. Note that simply using

$string の中で見つかった数字のグループの数を $count に設定します。 これは、(値が空リストに代入されているので)パターンマッチングは リストコンテキストで行われ、従って文字列での全てのマッチした部分の リストが返されるために起こります。 スカラコンテキストでのリスト代入は要素数(ここでは、マッチしたパターンの 数)に変換され、それが $count に代入されます。 単に以下のようにしても:

    $count = $string =~ /\d+/g;

would not have worked, since a pattern match in scalar context will only return true or false, rather than a count of matches.

うまく動かないことに注意してください; スカラコンテキストでの パターンマッチングはマッチした数ではなく、単に真か偽を返すからです。

The final element of a list assignment may be an array or a hash:

リスト代入の最後の要素は、配列やハッシュでもかまいません:

    ($x, $y, @rest) = split;
    my($x, $y, %rest) = @_;

You can actually put an array or hash anywhere in the list, but the first one in the list will soak up all the values, and anything after it will become undefined. This may be useful in a my() or local().

実際は、リストの任意の要素として配列を使うことができますが、 リスト中の最初の配列が、右辺の値をすべて取り込んでしまうため、 それ以降のものは未定義になります。 これは、my() や local() では有用かもしれません。

A hash can be initialized using a literal list holding pairs of items to be interpreted as a key and a value:

ハッシュはキーと値と解釈される値のペアとなるリストリテラルを使って 初期化されます:

    # same as map assignment above
    %map = ('red',0x00f,'blue',0x0f0,'green',0xf00);

While literal lists and named arrays are often interchangeable, that's not the case for hashes. Just because you can subscript a list value like a normal array does not mean that you can subscript a list value as a hash. Likewise, hashes included as parts of other lists (including parameters lists and return lists from functions) always flatten out into key/value pairs. That's why it's good to use references sometimes.

しばしば、リストリテラルと名前付きの配列は互いに交換可能ですが、 ハッシュの場合はそうではありません。 通常の配列がハッシュとしてリスト値で添え字づけできないのと同様に、 リスト値を使って添え字づけすることはできません。 同様に、その一部として別のリストを含むハッシュ(パラメーターリストや 関数の戻り値リストを含みます)は常に平坦なキー/値のペアにされます。 これはリファレンスをきちんと使う理由です。

It is often more readable to use the => operator between key/value pairs. The => operator is mostly just a more visually distinctive synonym for a comma, but it also arranges for its left-hand operand to be interpreted as a string if it's a bareword that would be a legal simple identifier. => doesn't quote compound identifiers, that contain double colons. This makes it nice for initializing hashes:

key/value のペアの間に => 演算子を使うと読みやすくなります。 => 演算子は実質、見た目に判別しやすいカンマ演算子でありますが、 その左側にあるオペランドが正当な単純な識別子であるような 裸の単語であるときに、それを文字列として解釈するようになっています。 => は、2 つのコロンを含むような複合識別子はクォートしません。 これは、ハッシュの初期化を格好よいものにします:

    %map = (
                 red   => 0x00f,
                 blue  => 0x0f0,
                 green => 0xf00,
   );

or for initializing hash references to be used as records:

あるいは、レコードとして使うハッシュリファレンスを初期化するために使います:

    $rec = {
                witch => 'Mable the Merciless',
                cat   => 'Fluffy the Ferocious',
                date  => '10/31/1776',
    };

or for using call-by-named-parameter to complicated functions:

複雑な関数のために名前付きパラメータによる呼び出しを使うためにも使えます:

   $field = $query->radio_group(
               name      => 'group_name',
               values    => ['eenie','meenie','minie'],
               default   => 'meenie',
               linebreak => 'true',
               labels    => \%labels
   );

Note that just because a hash is initialized in that order doesn't mean that it comes out in that order. See "sort" in perlfunc for examples of how to arrange for an output ordering.

ハッシュでは順番に意味がないので、初期化の順序にも意味はないということに 注意してください。 出力の順序を変える方法の例は、"sort" in perlfunc を参照してください。

If a key appears more than once in the initializer list of a hash, the last occurrence wins:

ハッシュの初期化リストにあるキーが複数回現れた場合、最後のものが勝ちます:

    %circle = (
                  center => [5, 10],
                  center => [27, 9],
                  radius => 100,
                  color => [0xDF, 0xFF, 0x00],
                  radius => 54,
    );

    # same as
    %circle = (
                  center => [27, 9],
                  color => [0xDF, 0xFF, 0x00],
                  radius => 54,
    );

This can be used to provide overridable configuration defaults:

これは上書き可能な設定デフォルトの提供に使えます:

    # values in %args take priority over %config_defaults
    %config = (%config_defaults, %args);

添え字

An array can be accessed one scalar at a time by specifying a dollar sign ($), then the name of the array (without the leading @), then the subscript inside square brackets. For example:

配列は、ドル記号 ($)、(先頭の @ なしの)配列名、大かっこで囲われた 添え字、の順で指定することで一度に一つのスカラにアクセスできます。 例えば:

    @myarray = (5, 50, 500, 5000);
    print "The Third Element is", $myarray[2], "\n";

The array indices start with 0. A negative subscript retrieves its value from the end. In our example, $myarray[-1] would have been 5000, and $myarray[-2] would have been 500.

配列の添え字は 0 から始まります。 負数の添え字は後ろから値を取り出します。 前述の例では、$myarray[-1] は 5000 となり、$myarray[-2] は 500 となります。

Hash subscripts are similar, only instead of square brackets curly brackets are used. For example:

ハッシュの添え字も同様ですが、大かっこの代わりに中かっこを使います。 例えば:

    %scientists = 
    (
        "Newton" => "Isaac",
        "Einstein" => "Albert",
        "Darwin" => "Charles",
        "Feynman" => "Richard",
    );

    print "Darwin's First Name is ", $scientists{"Darwin"}, "\n";

You can also subscript a list to get a single element from it:

リストの一つの要素を取り出すためにリストに添え字付けすることもできます:

    $dir = (getpwnam("daemon"))[7];

多次元配列のエミュレーション

Multidimensional arrays may be emulated by subscripting a hash with a list. The elements of the list are joined with the subscript separator (see "$;" in perlvar).

多次元配列はハッシュをリストで添え字付けすることでエミュレートされます。 リストの要素は添え字セパレータで結合されます ("$;" in perlvar 参照)。

    $foo{$x,$y,$z}

is equivalent to

これは次と等価です:

    $foo{join($;, $x, $y, $z)}

The default subscript separator is "\034", the same as SUBSEP in awk.

デフォルトの添え字セパレータは "\034" で、awk の SUBSEP と同じです。

スライス

A slice accesses several elements of a list, an array, or a hash simultaneously using a list of subscripts. It's more convenient than writing out the individual elements as a list of separate scalar values.

スライスは、添え字のリストを使ってリスト、配列、ハッシュの複数の要素に 同時にアクセスします。 これはそれぞれの要素を個々のスカラ値のリストとして扱うより便利です。

    ($him, $her)   = @folks[0,-1];              # array slice
    @them          = @folks[0 .. 3];            # array slice
    ($who, $home)  = @ENV{"USER", "HOME"};      # hash slice
    ($uid, $dir)   = (getpwnam("daemon"))[2,7]; # list slice

Since you can assign to a list of variables, you can also assign to an array or hash slice.

変数のリストに代入できるので、配列やハッシュのスライスにも代入できます。

    @days[3..5]    = qw/Wed Thu Fri/;
    @colors{'red','blue','green'} 
                   = (0xff0000, 0x0000ff, 0x00ff00);
    @folks[0, -1]  = @folks[-1, 0];

The previous assignments are exactly equivalent to

前述の代入は以下と完全に等価です:

    ($days[3], $days[4], $days[5]) = qw/Wed Thu Fri/;
    ($colors{'red'}, $colors{'blue'}, $colors{'green'})
                   = (0xff0000, 0x0000ff, 0x00ff00);
    ($folks[0], $folks[-1]) = ($folks[-1], $folks[0]);

Since changing a slice changes the original array or hash that it's slicing, a foreach construct will alter some--or even all--of the values of the array or hash.

スライスを変更すると、スライスした元の配列やハッシュを変更するので、 foreach 構造は配列やハッシュの値の一部 -- あるいは全部 -- を 置き換えます。

    foreach (@array[ 4 .. 10 ]) { s/peter/paul/ } 

    foreach (@hash{qw[key1 key2]}) {
        s/^\s+//;                       # trim leading whitespace
        s/\s+$//;                       # trim trailing whitespace
        s/\b(\w)(\w*)\b/\u$1\L$2/g;     # "titlecase" words
    }

As a special exception, when you slice a list (but not an array or a hash), if the list evaluates to empty, then taking a slice of that empty list will always yield the empty list in turn. Thus:

特別な例外として、(配列やハッシュではなく)リストをスライスするとき、 リストが空に評価されると、空リストのスライスは常に空リストになります。 従って:

    @a = ()[0,1];          # @a has no elements
    @b = (@a)[0,1];        # @b has no elements
    @c = (sub{}->())[0,1]; # @c has no elements
    @d = ('a','b')[0,1];   # @d has two elements
    @e = (@d)[0,1,8,9];    # @e has four elements
    @f = (@d)[8,9];        # @f has two elements

This makes it easy to write loops that terminate when a null list is returned:

これを使うと、空リストが返ったら終了するループを簡単に書けます:

    while ( ($home, $user) = (getpwent)[7,0] ) {
        printf "%-8s %s\n", $user, $home;
    }

As noted earlier in this document, the scalar sense of list assignment is the number of elements on the right-hand side of the assignment. The null list contains no elements, so when the password file is exhausted, the result is 0, not 2.

この文書で前述したように、リスト代入のスカラ評価は、代入の右側の要素の 数です。 空リストは要素を含まないので、パスワードファイルを読み込み終わると、 結果は 2 ではなく 0 になります。

Slices in scalar context return the last item of the slice.

スカラコンテキストでのスライスはスライスの最後の要素を返します。

    @a = qw/first second third/;
    %h = (first => 'A', second => 'B');
    $t = @a[0, 1];                  # $t is now 'second'
    $u = @h{'first', 'second'};     # $u is now 'B'

If you're confused about why you use an '@' there on a hash slice instead of a '%', think of it like this. The type of bracket (square or curly) governs whether it's an array or a hash being looked at. On the other hand, the leading symbol ('$' or '@') on the array or hash indicates whether you are getting back a singular value (a scalar) or a plural one (a list).

もし、なぜここでハッシュスライスに '%' ではなく '@' を使うのかについて 混乱するなら、次のように考えてみてください。 かっこの種類(大かっこか中かっこか)は、見ているものが配列かハッシュかを つかさどっています。 一方、配列やハッシュの先頭の記号('$' か '@') は、返ってくるものが単一の 値(スカラ)か、複数の値(リスト)かを示しています。

キー/値のハッシュスライス

Starting in Perl 5.20, a hash slice operation with the % symbol is a variant of slice operation returning a list of key/value pairs rather than just values:

Perl 5.20 から、% シンボルでのハッシュスライス操作は、単に値ではなく キー/値の組のリストを返すスライス操作の亜種です。

    %h = (blonk => 2, foo => 3, squink => 5, bar => 8);
    %subset = %h{'foo', 'bar'}; # key/value hash slice
    # %subset is now (foo => 3, bar => 8)
    %removed = delete %h{'foo', 'bar'};
    # %removed is now (foo => 3, bar => 8)
    # %h is now (blonk => 2, squink => 5)

However, the result of such a slice cannot be localized or assigned to. These are otherwise very much consistent with hash slices using the @ symbol.

しかし、このようなスライスの結果は、ローカル化、代入での使用は できません。 それ以外では @ シンボルを使ったハッシュスライスととても一貫性があります。

インデックス/値の配列スライス

Similar to key/value hash slices (and also introduced in Perl 5.20), the % array slice syntax returns a list of index/value pairs:

キー/値ハッシュスライスと同様(Perl 5.20 から導入されましたが) % 配列スライス 文法はインデックス/値の組を返します:

    @a = "a".."z";
    @list = %a[3,4,6];
    # @list is now (3, "d", 4, "e", 6, "g")
    @removed = delete %a[3,4,6]
    # @removed is now (3, "d", 4, "e", 6, "g")
    # @list[3,4,6] are now undef

Note that calling delete on array values is strongly discouraged.

配列の値に対して delete を呼び出すことは 強く非推奨であることに注意してください。

型グロブとファイルハンドル

Perl uses an internal type called a typeglob to hold an entire symbol table entry. The type prefix of a typeglob is a *, because it represents all types. This used to be the preferred way to pass arrays and hashes by reference into a function, but now that we have real references, this is seldom needed.

Perl は 型グロブ と呼ばれる内部型を、シンボルテーブルエントリ全体を 保持するために使っています。 この型グロブの型接頭辞は * です; なぜなら、それが型全てを表すからです。 これは関数に対してリファレンスを使って配列やハッシュを渡すために 好んで使われていた方法でしたが、しかし、私たちは今では本当のリファレンスを 持っていますから、型グロブを使う必要はほとんどありません。

The main use of typeglobs in modern Perl is create symbol table aliases. This assignment:

最近の Perl での型グロブの主な用途は、シンボルテーブルのエイリアスを 作るというものです。 具体的には以下のようにします:

    *this = *that;

makes $this an alias for $that, @this an alias for @that, %this an alias for %that, &this an alias for &that, etc. Much safer is to use a reference. This:

これは $this を $that のエイリアスにし、 @this を $that のエイリアスにし、%this を %that のエイリアスに、 &this を &that のエイリアスにし…のようにします。 より安全にするにはリファレンスを使います。 これは:

    local *Here::blue = \$There::green;

temporarily makes $Here::blue an alias for $There::green, but doesn't make @Here::blue an alias for @There::green, or %Here::blue an alias for %There::green, etc. See "Symbol Tables" in perlmod for more examples of this. Strange though this may seem, this is the basis for the whole module import/export system.

この例では $Here::blue を一時的に $There::green のエイリアスにしますが、 @Here::blue を $There::blue のエイリアスにはしませんし、 同様に %Here::blue を %There::green のエイリアスにはしません。 これに関するさらなる例については "Symbol Tables" in perlmod を 参照してください。 これは奇妙に思えるかもしれませんが、これが モジュールのインポート/エクスポートシステムの基盤となっているのです。

Another use for typeglobs is to pass filehandles into a function or to create new filehandles. If you need to use a typeglob to save away a filehandle, do it this way:

型グロブの別の用途には、関数にファイルハンドルを渡したり、 新たなファイルハンドルを生成するというものがあります。 もしファイルハンドルを保存するために型グロブを使う必要があるのなら、 以下のようにします:

    $fh = *STDOUT;

or perhaps as a real reference, like this:

あるいは、以下のように本当のリファレンスを使います:

    $fh = \*STDOUT;

See perlsub for examples of using these as indirect filehandles in functions.

関数中で間接的にファイルハンドルを使う例については perlsub を 参照してください。

Typeglobs are also a way to create a local filehandle using the local() operator. These last until their block is exited, but may be passed back. For example:

型グロブは local() 演算子を使ったローカルなファイルハンドルを 作成するのにも使われます。 それによって作成されたものはそれを囲むブロックが存在する間だけ 存在しますが、呼び出し元へ返すことが可能です。 例えば:

    sub newopen {
        my $path = shift;
        local  *FH;  # not my!
        open   (FH, $path)          or  return undef;
        return *FH;
    }
    $fh = newopen('/etc/passwd');

Now that we have the *foo{THING} notation, typeglobs aren't used as much for filehandle manipulations, although they're still needed to pass brand new file and directory handles into or out of functions. That's because *HANDLE{IO} only works if HANDLE has already been used as a handle. In other words, *FH must be used to create new symbol table entries; *foo{THING} cannot. When in doubt, use *FH.

今では *foo{THING} 表記がありますから、型グロブはファイルハンドルの 操作のために用いられることはそれほどではありませんが、 ファイルハンドルやディレクトリハンドルを関数に対して渡したり、 関数の外へ返すためにはまだ必要となります。 これは *HANDLE{IO} は HANDLE が既にハンドルとして使われた場合にのみ 動作するからです。 言い換えると、*FH は新しいシンボルテーブルのエントリーを作成するために 使わなければなりませんが、*foo{THING} を使うことはできません。 疑わしい場合は、*FH を使ってください。

All functions that are capable of creating filehandles (open(), opendir(), pipe(), socketpair(), sysopen(), socket(), and accept()) automatically create an anonymous filehandle if the handle passed to them is an uninitialized scalar variable. This allows the constructs such as open(my $fh, ...) and open(local $fh,...) to be used to create filehandles that will conveniently be closed automatically when the scope ends, provided there are no other references to them. This largely eliminates the need for typeglobs when opening filehandles that must be passed around, as in the following example:

ファイルハンドルを作成できる全ての関数 (open(), opendir(), pipe(), socketpair(), sysopen(), socket(), and accept()) は、 もし渡されたハンドルが初期化されていないスカラ変数の場合、 無名ファイルハンドルを作成します。 これにより、open(my $fh, ...)open(local $fh,...) のような 構文によって、他からのリファレンスがなければスコープの終わりに自動的に 閉じられる便利なファイルハンドルを作ることができます。 これは、以下の例のように、他に渡す必要があるファイルハンドルを開く時に 型グロブを使う必要性を大きく減らします:

    sub myopen {
        open my $fh, "@_"
             or die "Can't open '@_': $!";
        return $fh;
    }

    {
        my $f = myopen("</etc/motd");
        print <$f>;
        # $f implicitly closed here
    }

Note that if an initialized scalar variable is used instead the result is different: my $fh='zzz'; open($fh, ...) is equivalent to open( *{'zzz'}, ...). use strict 'refs' forbids such practice.

代わりに初期化されたスカラ変数が使われると、結果は異なることに 注意してください: my $fh='zzz'; open($fh, ...)open( *{'zzz'}, ...) と等価です。 このような動作を禁止するには use strict 'refs' を使ってください。

Another way to create anonymous filehandles is with the Symbol module or with the IO::Handle module and its ilk. These modules have the advantage of not hiding different types of the same name during the local(). See the bottom of "open" in perlfunc for an example.

無名ファイルハンドルを作るもう一つの方法は Symbol モジュールか IO::Handle モジュールを使用するというものです。 このモジュールは local() を使ったときのように同じ名前を 隠してしまうようなことがないという利点があります。 これを使った例は "open" in perlfunc の末尾を参照してください。

SEE ALSO

See perlvar for a description of Perl's built-in variables and a discussion of legal variable names. See perlref, perlsub, and "Symbol Tables" in perlmod for more discussion on typeglobs and the *foo{THING} syntax.

Perl の組み込み変数と、有効な変数名に関する議論に関しては、 perlvar を参照してください。 型グロブに関する議論と *foo{THING} 構文に関することは、perlref, perlsub, "Symbol Tables" in perlmod を参照してください。