名前¶
perllol - Manipulating Arrays of Arrays in Perl
perllol - Perl で配列の配列を操作する
説明¶
配列の配列の定義とアクセス¶
The simplest two-level data structure to build in Perl is an array of arrays, sometimes casually called a list of lists. It's reasonably easy to understand, and almost everything that applies here will also be applicable later on with the fancier data structures.
Perl で構築する一番簡単なデータ構造は、配列の配列(カジュアルに リストのリストとも呼ばれることがあります)です。 これは理解しやすく、そしてより複雑なデータ構造に対しても 適用することのできるものです。
An array of an array is just a regular old array @AoA that you can get at with two subscripts, like $AoA[3][2]. Here's a declaration of the array:
配列の配列は、あなたが望めば通常の古い配列 @AoA のようなものです。 これは $AoA[3][2] のように、二つの添え字で要素を取得することができます。 配列の宣言の例を挙げましょう。
use 5.010; # so we can use say()
# assign to our array, an array of array references
@AoA = (
[ "fred", "barney", "pebbles", "bambam", "dino", ],
[ "george", "jane", "elroy", "judy", ],
[ "homer", "bart", "marge", "maggie", ],
);
say $AoA[2][1];
bart
# 配列に配列へのリファレンスの配列を代入する
@AoA = (
[ "fred", "barney", "pebbles", "bambam", "dino", ],
[ "george", "jane", "elroy", "judy", ],
[ "homer", "bart", "marge", "maggie", ],
);
say $AoA[2][1];
bart
Now you should be very careful that the outer bracket type is a round one, that is, a parenthesis. That's because you're assigning to an @array, so you need parentheses. If you wanted there not to be an @AoA, but rather just a reference to it, you could do something more like this:
このとき、外側の括弧が丸括弧であったことに注意すべきです。 これは、上の例では@配列に代入するので丸括弧を使う必要があったためなのです。 もし @AoA ではなくて、単にリファレンスを代入したかったというのであれば、 次のように書くことができます:
# assign a reference to array of array references
$ref_to_AoA = [
[ "fred", "barney", "pebbles", "bambam", "dino", ],
[ "george", "jane", "elroy", "judy", ],
[ "homer", "bart", "marge", "maggie", ],
];
say $ref_to_AoA->[2][1];
bart
# 配列へのリファレンスの配列へのリファレンスを代入する
$ref_to_AoA = [
[ "fred", "barney", "pebbles", "bambam", "dino", ],
[ "george", "jane", "elroy", "judy", ],
[ "homer", "bart", "marge", "maggie", ],
];
say $ref_to_AoA->[2][1];
bart
Notice that the outer bracket type has changed, and so our access syntax has also changed. That's because unlike C, in perl you can't freely interchange arrays and references thereto. $ref_to_AoA is a reference to an array, whereas @AoA is an array proper. Likewise, $AoA[2] is not an array, but an array ref. So how come you can write these:
外側の括弧が変わったことと、アクセスの構文が変わっているということに 注目してください。 これは C とは違って、Perl では配列と参照とを自由に交換できないからです。 $ref_to_AoA は配列への参照です。 その配列は @AoA で、これがまた配列です。 同様に、$AoA[2] は配列ではなく配列への参照です。 ですから:
$AoA[2][2]
$ref_to_AoA->[2][2]
instead of having to write these:
これは、以下のような書き方でも同じことになります:
$AoA[2]->[2]
$ref_to_AoA->[2]->[2]
Well, that's because the rule is that on adjacent brackets only (whether square or curly), you are free to omit the pointer dereferencing arrow. But you cannot do so for the very first one if it's a scalar containing a reference, which means that $ref_to_AoA always needs it.
この規則は隣り合ったかっこ(それが大かっこだろうが中かっこだろうが) だけのものなので、参照外しをする矢印を自由に省略できます。 けれども一番最初にある矢印だけは、それがリファレンスを保持する スカラであるために省略することはできません。 これは $ref_to_AoA が常に必要とするものです。
大きくする¶
That's all well and good for declaration of a fixed data structure, but what if you wanted to add new elements on the fly, or build it up entirely from scratch?
固定的なデータ構造の宣言は良いのですが、その場で新しい要素を 追加したいとき、あるいは完全に 0 から作り上げたいときにはどうするのでしょう?
First, let's look at reading it in from a file. This is something like adding a row at a time. We'll assume that there's a flat file in which each line is a row and each word an element. If you're trying to develop an @AoA array containing all these, here's the right way to do that:
まず最初に、ファイルから読み込むことを見てみましょう。 これは一度に一つの行を追加していくようなものです。 私たちはここで、読み込んでいるファイルが、一行(line)が一つの行(row)に 対応し、各単語が要素に対応しているようなフラットなファイルであると 仮定しています。 もし配列 @AoA にそういった物を設定しようとするのであれば、 それは以下のようなやり方になります:
while (<>) {
@tmp = split;
push @AoA, [ @tmp ];
}
You might also have loaded that from a function:
関数を使って読み込むこともできます:
for $i ( 1 .. 10 ) {
$AoA[$i] = [ somefunc($i) ];
}
Or you might have had a temporary variable sitting around with the array in it.
あるいは、配列に設定するために使う一時変数を使うこともできます。
for $i ( 1 .. 10 ) {
@tmp = somefunc($i);
$AoA[$i] = [ @tmp ];
}
It's important you make sure to use the [ ] array reference constructor. That's because this wouldn't work:
配列への参照のコンストラクタである [ ] を使うことが重要です。 次のように書いてしまうのはとてもまずいやりかたです:
$AoA[$i] = @tmp; # WRONG!
The reason that doesn't do what you want is because assigning a named array like that to a scalar is taking an array in scalar context, which means just counts the number of elements in @tmp.
あなたが望んでいることをしない理由は、スカラに対するような名前付き配列の 代入は、配列をスカラコンテキストとして扱い、これは単に @tmp の要素の数を 数えることになるからです。
If you are running under use strict (and if you aren't, why in the world aren't you?), you'll have to add some declarations to make it happy:
use strict の元で実行するのであれば、(そしてもししていないのなら、 どうしてしていないの?) 以下の様にちょっと宣言を付け加えるとよいでしょう:
use strict;
my(@AoA, @tmp);
while (<>) {
@tmp = split;
push @AoA, [ @tmp ];
}
Of course, you don't need the temporary array to have a name at all:
もちろん、一時的な配列もなければならないというものではありません:
while (<>) {
push @AoA, [ split ];
}
You also don't have to use push(). You could just make a direct assignment if you knew where you wanted to put it:
また、push() を使わなくてもできます。 どこに押し込めたいかと言うことがわかっているのなら、直接 代入させることもできます:
my (@AoA, $i, $line);
for $i ( 0 .. 10 ) {
$line = <>;
$AoA[$i] = [ split " ", $line ];
}
or even just
あるいはこういう風にもできます:
my (@AoA, $i);
for $i ( 0 .. 10 ) {
$AoA[$i] = [ split " ", <> ];
}
You should in general be leery of using functions that could potentially return lists in scalar context without explicitly stating such. This would be clearer to the casual reader:
本当にそうしたいときを除き、スカラコンテキストでリストを返すかもしれない 関数を使ってしまう可能性に気をつけるべきです。 これは普通の読み手には明らかでしょう:
my (@AoA, $i);
for $i ( 0 .. 10 ) {
$AoA[$i] = [ split " ", scalar(<>) ];
}
If you wanted to have a $ref_to_AoA variable as a reference to an array, you'd have to do something like this:
配列へのリファレンスとして変数 $ref_to_AoA を使いたいというのであれば、 以下の様にする必要があるでしょう:
while (<>) {
push @$ref_to_AoA, [ split ];
}
Now you can add new rows. What about adding new columns? If you're dealing with just matrices, it's often easiest to use simple assignment:
これで新しい行を追加することができます。 新しいカラムを追加するのは? あなたがまさに行列を扱っているのなら、大概は単純な代入となります:
for $x (1 .. 10) {
for $y (1 .. 10) {
$AoA[$x][$y] = func($x, $y);
}
}
for $x ( 3, 7, 9 ) {
$AoA[$x][20] += func2($x);
}
It doesn't matter whether those elements are already there or not: it'll gladly create them for you, setting intervening elements to undef as need be.
これは対象となる要素が既に存在しているかどうかには影響されません: (ない場合でも)喜んであなたのためにその要素を作り出し、必要に応じて 間にある要素に undef をセットします。
If you wanted just to append to a row, you'd have to do something a bit funnier looking:
あなたは、単に行に追加したいだけという場合であっても、 ちょっと妙に見えることをしなければならないでしょう:
# add new columns to an existing row
push @{ $AoA[0] }, "wilma", "betty"; # explicit deref
# add new columns to an existing row
push @{ $AoA[0] }, "wilma", "betty"; # 明示的デリファレンス
Prior to Perl 5.14, this wouldn't even compile:
Perl 5.14 以前では、これはコンパイルも出来ませんでした:
push $AoA[0], "wilma", "betty"; # implicit deref
push $AoA[0], "wilma", "betty"; # 暗黙的デリファレンス
How come? Because once upon a time, the argument to push() had to be be a real array, not just a reference to one. That's no longer true. In fact, the line marked "implicit deref" above works just fine--in this instance--to do what the one that says explicit deref did.
なぜでしょうか? それは以前は push() の引数は参照ではなく、実際の配列である必要が あったからです。 これはもはや正しくはありません。 実際、上述の「暗黙的デリファレンス」と書かれた行は -- この場合は -- 正しく動作します; デリファレンスが行われます。
The reason I said "in this instance" is because that only works because $AoA[0] already held an array reference. If you try that on an undefined variable, you'll take an exception. That's because the implicit derefererence will never autovivify an undefined variable the way @{ } always will:
「この場合は」と言った理由は、$AoA[0] が既に配列リファレンスを 保持している場合 にのみ 動作するからです。 未定義値に対して行おうとすると、例外が発生します。 これは、暗黙的デリファレンスは、@{ } が常に行うような未定義値の 自動有効化を行わないからです:
my $aref = undef;
push $aref, qw(some more values); # WRONG!
push @$aref, qw(a few more); # ok
If you want to take advantage of this new implicit dereferencing behavior, go right ahead: it makes code easier on the eye and wrist. Just understand that older releases will choke on it during compilation. Whenever you make use of something that works only in some given release of Perl and later, but not earlier, you should place a prominent
この新しい暗黙的デリファレンスの振る舞いの利点を使いたいなら、正しく 前に進んでください: これにより目と手に優しいコードになります。 単に古いリリースではコンパイル中にエラーが出ることを理解してください。 特定のリリース以降の Perl 以降でのみ動作し、それより前では動作しないような ものを使う時はいつでも、以下のように目立つように:
use v5.14; # needed for implicit deref of array refs by array ops
directive at the top of the file that needs it. That way when somebody tries to run the new code under an old perl, rather than getting an error like
ファイルの先頭にこの指示子を書くべきです。 これにより、誰かが新しいコードを古い perl で実行しようとしたときに、 次のようなエラーではなく:
Type of arg 1 to push must be array (not array element) at /tmp/a line 8, near ""betty";"
Execution of /tmp/a aborted due to compilation errors.
they'll be politely informed that
次のように親切な情報が出力されます:
Perl v5.14.0 required--this is only v5.12.3, stopped at /tmp/a line 1.
BEGIN failed--compilation aborted at /tmp/a line 1.
アクセスと表示¶
Now it's time to print your data structure out. How are you going to do that? Well, if you want only one of the elements, it's trivial:
こんどはこのデータ構造を出力する番です。 あなたはどうやろうと考えてますか? そうですね、簡単に要素を一つだけ出力したいとするとこうなります:
print $AoA[0][0];
If you want to print the whole thing, though, you can't say
配列の内容全部を出力したいとき、次のようには書けません。
print @AoA; # WRONG