Perl 小骆驼 6章笔记 哈希

第六章 哈希
哈希和数组不同的是,其索引不是数字,而是任意的唯一的字符串。

哈希元素的访问
$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/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/11903161/viewspace-688672/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值