本章内容主要围绕哈希展开讨论,我把所有内容串在一起,编写了一个长长的perl脚本,用来练习其中的知识点,希望以后自己在复习这章内容的时候,能快速回忆起都有哪些知识点。
本例中用到的 ./hash.txt内容如下:
1
2
3
4
5
6
7
8
a
b
c
d
e
f
g
h
本例中用到的 ./hash.txt内容如下:
1
2
3
4
5
6
7
8
a
b
c
d
e
f
g
h
- #! /usr/bin/perl
- open TEST, "./hash.txt";
- while () {
- chomp;
- push (@a, $_);
- }
- close TEST;
- %h = @a;
- %h2 = reverse %h;
- print "Array \@a = (@a)\n";
- print "Hash \%h = ",(%h),"\n";
- print "The reverse of hash \%h (\%h2) = ",(%h2),"\n";
- print "The value of key(1) in hash '%h' is $h{1}\n";
- print "The value of key(2) in hash '%h2' is $h2{2}\n";
- @k = keys %h;
- @v = values %h;
- $n = keys %h;
- $m = values %h;
- print "The keys of hash '%h' = (@k), the values of hash = (@v)\n";
- print "The count of keys is $n, the count of values is $m\n";
- ## The each function of hash.
- while ( @a = each %h ) {
- print "@a\n";
- }
- while ( ($key, $value) = each %h) {
- print "$key => $value\n";
- }
- ## Sort in hash.
- for $key (sort keys %h) {
- $value = $h{$key};
- print "$key => $value\n";
- }
- ## Function exists
- if (exists $h{5}) {
- print "The value of key 5 in hash %h is $h{5}.\n";
- }
- if ( ! exists $h{10}) {
- print "There is no key 10 in hash %h.\n";
- }
- ## Function delete
- my $key = "e";
- delete $h{$key};
- print "Now hash %h = ",%h,"\n";
- ## %ENV
- print %ENV,"\n";
- print "\$ENV{PATH} = $ENV{PATH}\n";
- print "\$ENV{USER} = $ENV{USER}\n";
- my $count = keys %ENV;
- my @env = keys %ENV;
- print "The count of keys for hash %ENV is $count\n";
- print "The keys of %ENV is (@env)\n";
编辑回复