5.12.1

名前

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 slightly archaic '); 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). 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 を参照してください)。 リファレンスを生成する式の単純な識別子を、実行に値に置き換えることも 可能です。 これはこの文書の後の部分と、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 and control 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 like 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 (i.e. a control character) 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.)

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

コンテキスト

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 演算子に渡します。 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 のルーチンに渡します。 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 righthand 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 TRUE in the Boolean sense if it is not the null string or the number 0 (or its string equivalent, "0"). The Boolean context is just a special kind of scalar context where no conversion to a string or a number is ever performed.

スカラ値は、その値が空文字列か数値の 0 (あるいは同値な文字列 "0") 以外の場合には、真偽値の真として扱われます。 真偽値コンテキストは、単に文字列や数値への変換が行われなかった 特別なスカラコンテキストとして扱われます。

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. (It used to do so in Perl 4, but we had to break this to make sure destructors were called when expected.)

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

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;

Version 5 of Perl changed the semantics of $[: files that don't set the value of $[ no longer need to worry about whether another file changed its value. (In other words, use of $[ is deprecated.) So in general you can assume that

Perl バージョン 5 では $[ の意味を変更しました: $[ を設定していないファイルにおいて、他のファイルがこの変数を 変更しているかどうかを心配する必要がなくなりました (言い換えると、$[ は使わないほうが良いと言うことです)。 ですから、普通は以下のようになります。

    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 false if the hash is empty. If there are any key/value pairs, it returns true; more precisely, the value returned is 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. If a tied hash is evaluated in scalar context, a fatal error will result, since this bucket usage information is currently not available for tied hashes.

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

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)
    0b011011            # binary

You are allowed to use underscores (underbars) in numeric literals between digits for legibility. 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.

数値リテラルを読みやすくするために、数字の間に下線を使えます。 例えば、(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 を参照してください。

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 to disambiguate it from following alphanumerics (and underscores). 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, an identifier within such curlies is forced to be a string, as is any simple identifier 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'}++ ではないということを意味します。

バージョン文字列

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. 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.

__FILE__, __LINE__, __PACKAGE__ という特殊なリテラルはそれぞれ、 カレントのファイル名、行番号、パッケージ名を表わします。 これらは独立したトークンとしてのみ用いられます; 文字列中に展開されることはありません。 (空の package; 指示子によって)カレントパッケージが存在しない場合、 __PACKAGE__ は未定義値となります。

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.

二つの制御文字 ^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 contents after __DATA__. It is the program's responsibility to close DATA when it is done reading from 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 でアクセス可能なままになります。

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.

文法的に別の解釈ができない単語は、クォート文字列であるかのように 扱われます。 これは“裸の単語”(barewords)と呼ばれます。 ファイルハンドルやラベルと同様に、小文字だけからなる裸の単語は将来、 予約語とぶつかる危険があります。 そのような単語があった場合、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:

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

    ($a, $b, $c) = (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);

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:

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

    ($a, $b, @rest) = split;
    my($a, $b, %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 を参照してください。

添え字

An array is subscripted 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";

スライス

A common way to access an array or a hash is one scalar element at a time. You can also subscript a list to get a single element from it.

配列やハッシュにアクセスする一般的な方法は、一度に一つのスカラ要素です。 リストから一つの要素を取り出すためにも、添え字を使えます。

    $whoami = $ENV{"USER"};             # one element from the hash
    $parent = $ISA[0];                  # one element from the array
    $dir    = (getpwnam("daemon"))[7];  # likewise, but with list

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/(\w+)/\u\L$1/g;   # "titlecase" words
    }

A slice of an empty list is still an empty list. Thus:

空リストのスライスはやはり空リストです。 従って:

    @a = ()[1,0];           # @a has no elements
    @b = (@a)[0,1];         # @b has no elements
    @c = (0,1)[2,3];        # @c has no elements

But:

しかし:

    @a = (1)[1,0];          # @a has two elements
    @b = (1,undef)[1,0,2];  # @b has three 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 になります。

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).

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

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

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 のエイリアスにはしません。 これは奇妙に思えるかもしれませんが、これが モジュールのインポート/エクスポートシステムの基盤となっているのです。

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 を参照してください。