Perl哈希学习

来源:互联网 发布:心知天气是什么公司 编辑:程序博客网 时间:2024/06/10 06:21

Hash是一种结构。

key/value.

访问hash元素

$hash{$some_key}

当给hash选择名字时,最好这样思考:hash元素的名字和key之间可以用for来连接。如 the family_name for fred is flintstone.

要引用整个hash,使用百分号(%)作为前缀。

 

#!/bin/perl

use warnings;
use strict;

my $person;
my %family_name;

$family_name{"fred"} = "flintstone";
$family_name{"barney"} = "rubble";

foreach $person(qw< barney fred>) {
 print "I've heard of $person $family_name{$person}./n";
}


my %some_hash = ("foo", 35, "bar", 12.4, 25, "hello", "wilma", 1.72e30, "betty", "bye/n");

my @array_array = %some_hash;
print "@array_array/n";

 

哈希赋值方法 大箭头符号 (=>)

 

my %last_name = (
 "fred" => "flintstion",
 "dino" => undef,
 "barney" => "rubble",
 "betty" => "rubble",
);

 

keys函数会返回此hash的所有keys, values含税将返回所有的values。如果hash中没有元素,则此函数将返回空列表。

 

my @k = keys %last_name;
my @v = values %last_name;
my $count = keys %last_name; #scalar-producing, key/value pairs

 

print "the key are @k./n";
print "the value are @v./n";
print "the count are $count./n";

 

each函数

如果想迭代得到hash中的每个元素,一个通常的方法是使用each函数,它将返回key/value对的元素对。当对同一个hash函数进行一次迭代时,将返回下一个key/value对,直到所有的元素均被访问。

my $key;
my $value;

 

while (($key, $value) = each %last_name) {

#foreach (($key, $value) = each %last_name) {
 print "$key => $value./n";
}

注意两种循环的结果,原因在于两种循环的设计机制不同。

 

foreach $key (sort keys %last_name) {
 $value = $last_name{$key};
 print "$key => $value./n";
 print "$key => $last_name{$key}./n";
}

原创粉丝点击