您的位置:首页 > 理论基础 > 数据结构算法

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

2015-10-09 10:26 495 查看
在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] 就是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};
print HoH{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[0]\n”;
print “\$sample[1] is sample[1]\n”;

print “$sample[2] is sample[2]\n”;print“$sample[1]3issample[2]\n”;
print “\$sample[1]{3} is sample[1]{3}\n”;

print “$sample[1]{hello} is sample[1]hello\n”;print“$sample[1]hello[1]issample[1]{hello}\n”;
print “\$sample[1]{hello}[1] is sample[1]{hello}[1]\n”;

[root@master perl]# perl m9.pl

sample[0]is11.233sample[0] is 11.233
sample[1] is HASH(0x2271450)

sample[2]issample[2] is
sample[1]{3} is 4

sample[1]helloisARRAY(0x225d178)sample[1]{hello} is ARRAY(0x225d178)
sample[1]{hello}[1] is 7

{} hash引用

[] 数组引用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: