PDSC1:Perlデータ構造クックブック/
リストのリスト拡張版1
Tom Christiansen著
< tchrist@perl.com >
タイトル
perlLoL - Perlにおけるリストのリストの操作
宣言とアクセス
構築するのが最も簡単なのは、(時々配列の配列と呼ばれる)リストのリストで
す。それは適度に理解しやすく、またここで適用するほとんどすべてのことが、
後で出てくる、さらに変わり種のデータ構造でも同様に適用できるでしょう。
リストのリストは、あるいは配列の配列でも結構ですが、たとえば$LoL[3][2]
のような2つのサブスクリプトを持った、正規の旧式の配列@LoLにすぎません。
# 配列にリストのリスト参照を割当
@LoL = (
[ "fred", "barney" ],
[ "george", "jane", "elroy" ],
[ "homer", "marge", "bart" ],
);
print $LoL[2][2];
bart
さて、外側のブラケットの型が丸いもの、すなわち丸括弧であることに注意を
払わなければなりません。それは@listに割当を行ったからであり、したがって
丸括弧が必要となるのです。もし、@LoLではなく、むしろそれへの単なる参照を
望むのであれば、以下のようにもうちょっと多くの事柄を行うことになるでしょう。
# リストのリストの参照に参照を割当
$ref_to_LoL = [
[ "fred", "barney", "pebbles", "bambam", "dino", ],
[ "homer", "bart", "marge", "maggie", ],
[ "george", "jane", "alroy", "judy", ],
];
print $ref_to_LoL->[2][2];
外側のブラケットの型が変わったことに、そしてアクセス文法も変わったことに
注意して下さい。
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_LoL is a reference to an
array, whereas @LoL is an array proper. Likewise, $LoL[2] is not an
array, but an array ref. So how come you can write these:
$LoL[2][2]
$ref_to_LoL->[2][2]
instead of having to write these:
$LoL[2]->[2]
$ref_to_LoL->[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 array.
But you need not do so for the very first one if it's a scalar containing
a reference, which means that $ref_to_LoL always needs it.
=head1 Growing Your Own
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?
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
@LoL list containing all these, here's the right way to do that:
while (<>) {
@tmp = split;
push @LoL, [ @tmp ];
}
You might also have loaded that from a function:
for $i ( 1 .. 10 ) {
$LoL[$i] = [ somefunc($i) ];
}
Or you might have had a temporary variable sitting around with the
list in it.
for $i ( 1 .. 10 ) {
@tmp = somefunc($i);
$LoL[$i] = [ @tmp ];
}
It's very important that you make sure to use the C<[]> list reference
constructor. That's because this will be very wrong:
$LoL[$i] = @tmp;
You see, assigning a named list like that to a scalar just counts the
number of elements in @tmp, which probably isn't what you want.
If you are running under C
最終更新日
10月7日 19:35:26 MDT 1995
ご意見、ご要望は、
電子メールまたは
投稿にお願い致します。
ホームページへ戻る。