#!/usr/bin/perl
use warnings;
#use strict强制所有变量必须用my来声明,
#当试图使用不是用my声明的裸单词(变量或函数名)时,编译无法通过
use strict;
#创建简单的hash表
my %student = (
"name" => "HuiDong",
"id" => 1021400001,
"age" => 25,
);
#对hash表进行操作
#返回hash表中的所有keys
print my @key = keys%student;
#返回hash表中的所有values
print my @values = values%student;
#迭代hash的每一个元素
while ((my $key, my $value) = each %student) {
print "$key=>$value\n";
}
#查看hash表中是否存在某个key
if (exists$student{'name'}) {
print "exist\n";
}
#根据变量自动创建hash
my $string = "name HuiDong";
my ($name_t, $name) = split(/\s/, $string);
my %dich = ();
$dich{$name_t} = $name;
while ((my $key, my $value) = each%dich) {
print "$key=>$value\n";
}
#创建多层hash表并实现访问
my %students;
%students = (
"student1" => {"name" => "name1",
"id" => 10214,
"mark" => 100,
},
"student2" => {"name" => "name2",
"id" => 10215,
"mark" => 50,
},
);
#访问方式一
print $students{"student1"}{"name"}."\n";
#访问方式二
my $studentreport = $students{"student2"};
print ${$studentreport}{"name"}."\n";
#hash表中内嵌数组
my %game = (
"武器店" => [123,35],
"魔法店" => [85, 196],
);
print $game{"武器店"}->[0]."\t";
print $game{"武器店"}->[1]."\n";
#清空和删除hash表
undef %student;#清空整个hash表
foreach my $key(keys %student) {
delete $student{$key}; #删除hash
}