perl 学习笔记,关于哈希相关的知识点

回复 收藏
本章内容主要围绕哈希展开讨论,我把所有内容串在一起,编写了一个长长的perl脚本,用来练习其中的知识点,希望以后自己在复习这章内容的时候,能快速回忆起都有哪些知识点。
本例中用到的 ./hash.txt内容如下:
1
2
3
4
5
6
7
8
a
b
c
d
e
f
g
h
  1. #! /usr/bin/perl
  2. open TEST, "./hash.txt";
  3. while () {
  4.         chomp;
  5.         push (@a, $_);
  6. }
  7. close TEST;
  8. %h = @a;
  9. %h2 = reverse %h;
  10. print "Array \@a = (@a)\n";
  11. print "Hash \%h = ",(%h),"\n";
  12. print "The reverse of hash \%h (\%h2) = ",(%h2),"\n";
  13. print "The value of key(1) in hash '%h' is $h{1}\n";
  14. print "The value of key(2) in hash '%h2' is $h2{2}\n";
  15. @k = keys %h;
  16. @v = values %h;
  17. $n = keys %h;
  18. $m = values %h;
  19. print "The keys of hash '%h' = (@k), the values of hash = (@v)\n";
  20. print "The count of keys is $n, the count of values is $m\n";
  21. ## The each function of hash.
  22. while ( @a = each %h ) {
  23.         print "@a\n";
  24. }
  25. while ( ($key, $value) = each %h) {
  26.         print "$key => $value\n";
  27. }
  28. ## Sort in hash.
  29. for $key (sort keys %h) {
  30.         $value = $h{$key};
  31.         print "$key => $value\n";
  32. }
  33. ## Function exists
  34. if (exists $h{5}) {
  35.         print "The value of key 5 in hash %h is $h{5}.\n";
  36. }
  37. if ( ! exists $h{10}) {
  38.         print "There is no key 10 in hash %h.\n";
  39. }
  40. ## Function delete
  41. my $key = "e";
  42. delete $h{$key};
  43. print "Now hash %h = ",%h,"\n";
  44. ## %ENV
  45. print %ENV,"\n";
  46. print "\$ENV{PATH} = $ENV{PATH}\n";
  47. print "\$ENV{USER} = $ENV{USER}\n";
  48. my $count = keys %ENV;
  49. my @env = keys %ENV;
  50. print "The count of keys for hash %ENV is $count\n";
  51. print "The keys of %ENV is (@env)\n";
2012-11-15 15:24 举报
已邀请:

回复帖子,请先登录注册

退出全屏模式 全屏模式 回复
评分
可选评分理由: