1. 題目
2. 代碼與輸出
ch6-family-name.pl
1 #-----------------------------------------------------------#
2 # Source: Learning Perl, chapter6, exercise-1
3 # Date: 2012-01-16
4 # Author: xiaodongrush
5 #-----------------------------------------------------------#
6 use 5.010;
7 %family_name_hash = (
8 "fred" => "flintstone",
9 "barney" => "rubble",
10 "wilma" => "flintstone", );
11
12 while(<>) {
13 chomp;
14 if(exists $family_name_hash{$_} ) {
15 say $_ . "'s family name is : " . $family_name_hash{$_};
16 } else {
17 say $_ . "'s family name not exist in hash";
18 }
19 }
20 #-----------------------------------------------------------#
ch6-wordcount.pl
1 #-----------------------------------------------------------#
2 # Source: Learning Perl, chapter6, exercise-2
3 # Date: 2012-01-16
4 # Author: xiaodongrush
5 #-----------------------------------------------------------#
6 use 5.010;
7 while(<>) {
8 chomp;
9 if(exists $word_hash{$_}) {
10 $word_hash{$_} += 1;
11 } else {
12 $word_hash{$_} = 1;
13 }
14 }
15 foreach(sort (keys %word_hash) ) {
16 say $_ . "\t\t" . $word_hash{$_};
17 }
18 #-----------------------------------------------------------#
ch6-ENV-hash.pl
1 #-----------------------------------------------------------#
2 # Source: Learning Perl, chapter6, exercise-3
3 # Date: 2012-01-16
4 # Author: xiaodongrush
5 #-----------------------------------------------------------#
6 use 5.010;
7
8 $max_key_len = 0;
9 $max_value_len = 0;
10 $len_limit = 35;
11 while(($key, $value) = each %ENV) {
12 if(length($key) < $len_limit && length($value) < $len_limit ) {
13 $max_key_len = $max_key_len > length($key) ? $max_key_len : length($key);
14 $max_value_len = $max_value_len > length($value) ? $max_value_len : length($value);
15 }
16 }
17 $format = "%-" . $max_key_len . "s , %-" . $max_value_len . "s\n";
18 printf $format, "key", "value";
19 foreach(sort(keys %ENV)) {
20 if( (length($_) < $len_limit ) && (length($ENV{$_}) < $len_limit )) {
21 printf $format, $_, $ENV{$_};
22 }
23 }
24 <STDIN>;
25 #-----------------------------------------------------------#
3. 檔案
/Files/pangxiaodong/LearningPerl/ch6-answer.rar