<pre name="code" class="sql">9.1 数组的数组:
有许多种类型的嵌套数据结构,最容易做的是制作一个数组的数组,也叫做两维数组或者矩阵。
9.1.1 创建和访问一个两维数组:
下面是如何把一个两维数组放在一起的方法:
##给一个数组赋予一个数组引用列表:
zjzc01:/root/big2# cat a17.pl
@Aoa = (
["fred", "barney" ],
["george", "jane", "elroy" ],
["homer", "marge", "bart" ],
);
print $Aoa[0][1]."
";
zjzc01:/root/big2# perl a17.pl
barney
整个列表都封装在圆括弧里,而不是花括弧里,因为你是给一个俩别哦复制而不是给引用赋值。
如果你想要一个指向数组的引用,那么你要使用方括弧:
##创建一个指向一个数组的数组的引用:
zjzc01:/root/big2# cat a18.pl
$ref_to_AoA = [
[ "fred", "barney", "pebbles", "bamm bamm", "dino", ],
[ "homer", "bart", "marge", "maggie", ],
[ "george", "jane", "elroy", "judy", ],
];
print $ref_to_AoA->[0][fred]."
";
print $$ref_to_AoA[0][fred]."
";
zjzc01:/root/big2# perl a18.pl
fred
fred
请记住在每一对相邻的花括弧或方括弧之间有一个隐含的-> ,因此下面两行:
$AoA[2][3]
$ref_to_AoA->[2][3]
等效于下面两行:
$AoA[2]->[3]
$ref_to_AoA->[2][3]
9.2 数组的散列的组成:
你可以用下面的方法创建一个匿名数组的散列:
##如果键字是标示符,我们通常省略引号:
zjzc01:/root/big2# cat a20.pl
%HoA = (
flintstones => [ "fred", "barney" ],
jetsons => [ "george", "jane", "elroy" ],
simpsons => [ "homer", "marge", "bart" ],
);
print %HoA;
print "
";
print $HoA{flintstones}[0]."
";
zjzc01:/root/big2# perl a20.pl
simpsonsARRAY(0x1c29560)jetsonsARRAY(0x1c292c0)flintstonesARRAY(0x1c0cd48)
fred
9.3 散列的数组:
如果你有一堆记录,你想顺序访问它们,并且每条记录本身包含一个键字/数值对,那么散列的数组就很有用。
在本章中,散列的数组比其他结构用得少一系。
9.3.1 组成一个散列的数组:
你可以用下面的方法创建一个匿名散列的数组:
zjzc01:/root/big2# cat a21.pl
@AoH = (
{
husband => "barney",
wife => "betty",
son => "bamm bamm",
},
{
husband => "george",
wife => "jane",
son => "elroy",
},
{
husband => "homer",
wife => "marge",
son => "bart",
},
);
print @AoH;
print "
";
print $AoH[0]{husband};
print "
";
zjzc01:/root/big2# perl a21.pl
HASH(0xb21d48)HASH(0xb3e590)HASH(0xb3e608)
barney
9.4 散列的散列:
多维的散列时Perl里面最灵活的嵌套结构。它就好像绑定一个记录,该记录本身包含其他记录。
在每个层次上,你都用一个字符(必要时引起)做该散列的索引。不过,你要记住散列里的键字/数值 对不会以任何特定的顺序出现,
你可以使用sort 函数以你喜欢的任何顺序检索这些配对。
9.4.1 构成一个散列的散列:
zjzc01:/root/big2# cat a22.pl
%HoH = (
flintstones => {
husband => "fred",
pal => "barney",
},
jetsons => {
husband => "george",
wife => "jane",
"his boy" => "elroy",
},
simpsons => {
husband => "homer",
wife => "marge",
kid => "bart",
}
);
print %HoH;
print "
";
print $HoH{flintstones}{husband};
print "
";
zjzc01:/root/big2# perl a22.pl
simpsonsHASH(0x1700608)jetsonsHASH(0x17002c0)flintstonesHASH(0x16e3d48)
fred
9.5 函数的散列:
if ($cmd =~ /^exit$/i) { exit }
elsif ($cmd =~ /^help$/i) { show_help() }
elsif ($cmd =~ /^watch$/i) { $watch = 1 }
elsif ($cmd =~ /^mail$/i) { mail_msg($msg) }
elsif ($cmd =~ /^edit$/i) { $edited++; editmsg($msg); }
elsif ($cmd =~ /^delete$/i) { confirm_kill() }
else {
warn "Unknown command: `$cmd'; Try `help' next time
";
}
你还可以在你的数据结构里保存指向函数的引用,就像你可以存储指向数组或者散列的引用一样:
my (@frames,@button);
my %sub_of = (
"日志查询" => &push_button2 ,
"温金短信查询" => &push_button3 ,
"中均短信查询" => &push_button4 ,
"机器信息查询" => &push_button5,
"IP信息查询" => &push_button6,
"设备信息维护" => &push_button7,
"test" => sub{ print "program 6" },
7 => sub{ print "program 7" },
8 => sub{ print "program 8" },
9 => sub{ print "program 9" },
);
~