第六章 哈希
哈希和数组不同的是,其索引不是数字,而是任意的唯一的字符串。
哈希元素的访问
$hash{$some_key}
$family_name{"fred"}="flintstone";
$family_name{"barney"}="rubble";
foreach $person(qw/barney fred/){
print "I've heard of $person $family_name{$person}.\n":
}
要引用整个hash %family_name
用列表赋值:
%some_hash=("foo", 35, "bar", 12.4, 2.5, "hello");
赋值给列表:
@array=%some_hash;不按照赋值的顺序打印
hash之间也可以拷贝:
%new_hash=%old_hash;会将哈希展开成列表,在赋值给新的哈希
%inverse_hash=reverse %some_hash;反转value和key,这种要确保value的唯一性
my %last_name=(
"fred" => "flints",
"dino" => undef,
"barney" => "rubble",
"betty" => "rubble",
)
对哈希的各种函数
1. keys, values
my @k=keys %hash;
my @v=values %hash;
而且两个列表的每个元素是对应顺序的。
my $count=keys %hash; 返回个数
2.each
迭代每一对元素
while (($key,$value)=each %hash){
print "$key => $value\n";
}
排序:
foreach $key (sort keys %hash){
$value=$hash($key);
print "$key =>$value\n"; 或者 print "$key => $hash{key}\n";
}
3.exists
if (exists $book{$dino}){
print "hey, there's a library card for dino!\n";
}
也就是keys的列表中存在dino时,exists返回true.
4.delete
delete $books{$alice};
如果
$books{"alice"}=undef; 有key,但value值undef
如果delete $books{$alice};则alice这个key都没有了
if (exists $book{"alice"})为true表示有alice这个key,即alice是不是有借书卡
if ($book{"alice"}) 为true表示alice这个key对应的value不是undef,即alice的借书卡是不是从来没用过。没用过就是undef
foreach $person(sort keys %books){
if ($books{$person}){
print "$person has $books{$person} items\n";
}
}
习题:
1.#!c:\perl\bin\perl
$hash{"fred"}="flintstone";
$hash{"barney"}="rubble";
$hash{"wilma"}="flintstone";
$hash{"alice"}=undef;
print "Please input given name:\n";
while ($line=<>) {
chomp($line);
if (exists $hash{$line}) {
if ($hash{$line}) {
print "family name:$hash{$line}\n";
}else{
print "family name undef\n";
}
}else{
print "given name not exist\n";
}
print "Please input given name:\n";
}
2.
#!c:\perl\bin\perl -w
foreach $name(<>){
chomp($name);
if (exists $count{$name}){
$count{$name}+=1;
}else {
$count{$name}=1;
}
}
while (($key,$value)=each %count){
print "$key => $value\n";
}
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/11903161/viewspace-688672/,如需转载,请注明出处,否则将追究法律责任。