第二章 实现复杂的数据结构

来源:互联网 发布:地理上的元数据是什么 编辑:程序博客网 时间:2024/06/03 19:20

在Perl中使用数组的数组是最为直观的一种矩阵表达方式,因为Perl不直接支持二维数组:

打印第2行,第三个元素

[root@master perl]# cat m7.pl
@matrix=([1,2,3],[4,5,6],[7,8,9]);
print $matrix[1][2];
[root@master perl]# perl m7.pl
6[root@master perl]#

注意 这里的@matrix 是一个简单的数组,它的元素为指向匿名数组的引用。也就是说

matrix[1][2]matrix[1]->[2]的简化表达形式。

散列的散列:

2 散列的散列:
1 构建一个散列的散列:

barney[root@master perl]# cat m8.pl
%HoH = ( flintstones => { husband => “fred”, pal => “barney”, }, jetsons => { husband => “george”, wife =>

“jane”, “his boy” => “elroy”, }, simpsons => { husband => “homer”, wife => “marge”, kid => “bart”, } );
print HoHflintstones;printHoH{flintstones}{pal};
print “\n”;
print “11111111\n”;
print $HoH{flintstones}->{pal};
[root@master perl]# perl m8.pl
HASH(0x1ea3178)barney
11111111
barney[root@master perl]#

教授,学生与课程:

这个例子将向你展示如何表示教授,学生和课程数据的分层记录结构,如何将它们联系起来,假设数据文件如下所示:

file:professor.dat

id :42343 ##雇员号
Name :E.F.Schumacher
Office Hours :Mon 3-4,Web 8-9
Courses :HS201,SS343

file:student.dat

id :52003
Name :Garibaldi
Course :H301,H302,M201

file:courses.dat

id :HS201
Description :Small is beautiful

格式化打印工具:

[root@master perl]# cat m9.pl
@sample=(11.233,{3=>4,”hello” =>[6,7]});
print “$sample[0] is sample[0]\n;print$sample[1]issample[1]\n”;
print “$sample[2] is sample[2]\n;print$sample[1]3issample[1]{3}\n”;
print “$sample[1]{hello} is sample[1]hello\n;print$sample[1]hello[1]issample[1]{hello}[1]\n”;

[root@master perl]# perl m9.pl
sample[0]is11.233sample[1] is HASH(0x2271450)
sample[2]issample[1]{3} is 4
sample[1]helloisARRAY(0x225d178)sample[1]{hello}[1] is 7

{} hash引用

[] 数组引用

0 0