用%name来定义一个哈希表,用$name{key}来取值:
- %hash =
- ("a", 7,
- "ef", 9,
- 35, "hello");
- print $hash{"a"}."\n"; # 7
- $a = 35;
- print $hash{$a}."\n"; # "hello"
- print $hash{"notdefined"}."\n"; # null
更直观构建哈希表的方式是:
- %hash = (
- "a" => 7,
- "ef" => 9,
- 35 => "hello"
- );
增删哈希表的元素:
- $hash{"new"} = "added";
- delete $hash{"new"};
数组可以赋给一个哈希表:
- @array = ("a", 1, "b", 2);
- %hash = @array;
- print $hash{"b"}; # 2
- keys和values可以分别得到两个数组:
- %hash = (
- "a" => 7,
- "ef" => 9,
- 35 => "hello"
- );
- @keys = keys(%hash); # 35 ef a
- @values = values(%hash); # hello 9 7
- foreach $key (@keys) {
- print $hash{$key};
- }
上面通过keys遍历哈希表的方式太低效,Perl提供了一个更高效的方式:
- while (($key, $value) = each(%hash)) {
- print "$key=>$value\n";
- }
在each到达底部后并返回0后,下次再次调用each会从头开始遍历。在使用each的时候,不能添加或删除元素,否则会出现无法预料的结果。
阅读(1571) | 评论(0) | 转发(0) |