Perl 哈希学习笔记
什么是哈希?
哈希是Perl中的一种数据结构,也被称为关联数组。哈希由键(key)和值(value)组成,它们是一一对应的,其中键是唯一的。哈希通常用于存储和处理大量相关的信息。
如何创建和访问哈希?
我们可以用花括号({})来创建一个哈希:
perlCopy Codemy %hash = (
"apple" => 3,
"banana" => 2,
"orange" => 1,
);
其中,键和值之间用“=>”连接。注意,键是字符串类型的,需要用引号括起来。
访问哈希中的元素,可以用花括号加键名的方式:
perlCopy Codeprint $hash{"apple"}; # 输出 3
我们也可以使用foreach语句遍历哈希中的元素:
perlCopy Codeforeach my $key (keys %hash) {
print "$key => $hash{$key}\n";
}
常用哈希函数
keys函数
keys函数返回哈希中所有的键:
perlCopy Codemy @keys = keys %hash;
values函数
values函数返回哈希中所有的值:
perlCopy Codemy @values = values %hash;
each函数
each函数返回哈希中下一个键值对:
perlCopy Codewhile (my ($key, $value) = each %hash) {
print "$key => $value\n";
}
delete函数
delete函数删除哈希中的一个键值对:
perlCopy Codedelete $hash{"apple"};
实例
以下是一个使用哈希处理学生信息的例子:
perlCopy Codemy %students = (
"Tom" => {
"age" => 20,
"score" => 85,
},
"Jack" => {
"age" => 22,
"score" => 90,
},
"Mary" => {
"age" => 19,
"score" => 95,
},
);
foreach my $name (keys %students) {
my $info = $students{$name};
print "$name's age is $info->{'age'}, and score is $info->{'score'}\n";
}
输出结果为:
Copy CodeTom's age is 20, and score is 85
Jack's age is 22, and score is 90
Mary's age is 19, and score is 95