1. 題目
2. 代碼
1 #-----------------------------------------------------------#
2 # Source: Learning Perl, chapter3
3 # Date: 2012-01-13
4 # Author: xiaodongrush
5 #-----------------------------------------------------------#
6 # code-1 #
7 #-----------------------------------------------------------#
8 $split = "-------------------------------------------------";
9 $code1 = 'chomp(@strs = <STDIN>);' . "\n" .
10 'foreach(reverse(@strs)) {' . "\n" .
11 ' print $_ . "\n";' . "\n" .
12 '}';
13 print "code-1\n" . $code1 . "\n" . $split;
14 #-----------------------------------------------------------#
15 # execute-1 #
16 #-----------------------------------------------------------#
17 print "\nexecute-1\n";
18 chomp(@strs = <STDIN>);
19 foreach(reverse(@strs)) {
20 print $_ . "\n";
21 }
22 #-----------------------------------------------------------#
23 # code-2 #
24 #-----------------------------------------------------------#
25 $code2 = '@names = qw { fred betty barney dino wilma pebbles bamm-bamm };' . "\n" .
26 'chomp(@indexes=<STDIN>);' . "\n" .
27 'foreach(@indexes) {' . "\n" .
28 ' print @names[($_-1)%7] . "\n";' . "\n" .
29 '}';
30 print $split . "\ncode-2\n" . $code2 . "\n" . $split;
31 #-----------------------------------------------------------#
32 # execute-2 #
33 #-----------------------------------------------------------#
34 print "\nexecute-2\n";
35 @names = qw { fred betty barney dino wilma pebbles bamm-bamm };
36 chomp(@indexes=<STDIN>);
37 foreach(@indexes) {
38 print @names[($_-1)%7] . "\n";
39 }
40 #-----------------------------------------------------------#
41 # code-3 #
42 #-----------------------------------------------------------#
43 $code3 = 'chomp(@strs=<STDIN>);' . "\n" .
44 'foreach(sort(@strs)) {' . "\n" .
45 ' print $_ . " ";' . "\n" .
46 '}' . "\n" .
47 'print "\n";' . "\n" .
48 'foreach(sort(@strs)) {' . "\n" .
49 ' print $_ . "\n";' . "\n" .
50 '}';
51 print $split . "\ncode-3\n" . $code3 . "\n" . $split;
52 #-----------------------------------------------------------#
53 # execute-3 #
54 #-----------------------------------------------------------#
55 print "\nexecute-3\n";
56 chomp(@strs=<STDIN>);
57 foreach(sort(@strs)) {
58 print $_ . " ";
59 }
60 print "\n";
61 foreach(sort(@strs)) {
62 print $_ . "\n";
63 }
64 #-----------------------------------------------------------#
65 print "END!!!";
66 <STDIN>
67 #-----------------------------------------------------------#
68 # 總結
69 # 1. @str_array = <STDIN>; 每次讀入一行,數組增加一個元素,
70 # 直到讀入檔案為空白或者輸入Control+Z(Windows),Control+D(Unix)
71 # 2. $_表示一些省略參數的變數,比如foreach()省略,print的省略。
72 # 3. reverse,sort,這些函數與chomp不同,更像傳回值,而chomp直接修改了原數組,或者原變數
3. 輸出
4. 檔案
/Files/pangxiaodong/LearningPerl/ch3-answer.rar