顯示具有 Perl 標籤的文章。 顯示所有文章
顯示具有 Perl 標籤的文章。 顯示所有文章

2012年10月22日 星期一

Javascript 與 Perl 合用

主從式架構



一個好的主從式的應用程式, 應該在使用者輸入時便立即確認其輸入值是否為 valid (可用 VBScript, JScript, JavaScript, PerlScript 等.), 然後才將 確認過的資料後傳至伺服器端處理程式 (如 CGI, ASP 等)。在以下範例中,使用者 可以在郵遞區號內輸入“aaa“,然後按”確定“,網頁會告訴你輸入的郵遞區號必須是數字。
範例:
郵遞區號: 傳真號碼:

2012年9月26日 星期三

Perl 教學 -- 表單處理

Perl 教學 -- 表單處理

This tutorial is copyrighted and provided as is. You are welcomed to use it for non-commercial purpose.
Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu

請勿轉貼
看其他教材

本範例參考並修改了 CGI 一日通: 使用 Perl 5 這本書中的一個範例。 在這個範例,我們設計了兩個表單元件的表單,並整合了之前所學的概念 (含 GET/POST 資料、字串處理),讓程式可以分別取得單一表單元件的資料。 讓我們以範例進行說明:
  1. 表單:
    E-mail:
    您的意見:
    表單的原始碼如下:

    <form method="POST" action="comments.pl">
    <strong>E-mail:</strong>
    <input type="text" name="address" size="30" maxlength="50">
    <br>您的意見:<br>
    <textarea name="comments" rows="8" cols="50">
    </textarea>
    <p><input type="submit" value="Sent Comments">
    </form>
    
    在表單中,總共有兩個分別名為 addresscomments 的資料會傳送給 comments.pl,其格式為 address=email@address 以及 comments=使用者輸入的意見
  2. 為了處理瀏覽器傳過來的 addresscomments 資料, comments.pl 利用了一些可以重複使用的方法,而這些方法定義在 forms-lib.pl,其原始碼如下:
    #!/usr/local/bin/perl
    # forms-lib.pl
    # Decodes URLs and unpacks from input.
    # Read the form contents into $input, decodes it, unpacks it,
    # and returns it as an associative array.
    sub GetFormInput
    {
      my(%input);
      $input = &ReadInput();
      %input = &ParseInput($input) if $input;
      return(%input);
    }
    
    sub ReadInput
    {
      my($method, $input, $length);
      $method = $ENV{'REQUEST_METHOD'};
      if($method eq 'GET')
      {
        $input = $ENV{'QUERY_STRING'};
      }
      elsif ($method eq 'POST')
      {
        $length = $ENV{'CONTENT_LENGTH'};
        read(STDIN, $input, $length);
      }
    
      return($input);
    }
    
    sub ParseInput
    {
      my($input) = @_;
      my(@pairs);
      my(%input);
      @pairs = split('&',$input);
      foreach $pair (@pairs)
      {
        # convert all plus signs to spaces.
        $pair =~ s/\+/ /g;
    
        # split into a key and a value.
        ($key, $value) = split('=', $pair, 2);
    
        # Convert hex numbers to alphanumeric.
        $key =~ s/%(..)/pack("c", hex($1))/ge;
        #$value =~ s/%(..)/pack("c", hex($1))/ge;
        $value =~ s/%([\da-fA-F][\da-fA-F])/pack("c", hex($1))/ge;
    
        # handle multiple values, separated by newlines.
        $input{$key} .= "\n" if defined($input{$key});
    
        # associate keys and values
        $input{$key} = $value;
      }
      return (%input);
    }
    
    return true;
    

    • comments.pl 首先呼叫 GetFormInput 來取得表單 資料;而其取得資料的方式,分成兩個步驟:第一個是呼叫 ReadInput, 第二個是呼叫 ParseInput
    • ReadInput 是一個可以處理 GET 以及 POST 的方法;它利用 環境變數 REQUEST_METHOD 來確認 GET 或者 POST,然後分別利用 相對應的方式(讀取環境變數 QUERY_STRING 或者標準輸入 STDIN)來取得 輸入的資料;請注意: 目前取得的資料其格式為 address=email@address&comments=使用者輸入的意見 的一個字串。
    • 因此,我們需要利用 ParseInput 將字串轉換成如下的格式:
      address    email@address
      comments   使用者輸入的意見
      
      這種資料結構稱之為 hash,而 hash 中的第一個欄位一般稱之為 key,第二個欄位稱之為 value。Perl 用來代表具有 hash 結構的變數,會在變數名稱之前加上 %;例如,在 ParseInput 內 第三行,就宣告了一個名為 %input 的 hash 區域變數。從程式中, 我們也可以觀察到 %input$input 被視為兩個不同的 變數。
      在 ParseInput 中,它首先利用 splitaddress=email@address&comments=使用者輸入的意見 分成一個具有兩個 元素的陣列 @pair;兩個元素分別是 address=email@addresscomments=使用者輸入的意見;然後,再利用 splitaddress 指定為 key,而 email@address 指定為 value; 同樣的方式也套用在 @pair 陣列中其他的元素。至於,將 + 和 url-encoded characters 轉換成適當的字元也在 ParseInput 內完成。最後,把 hash 的結果回傳給 GetFormInput,而 GetFormInput 再把 hash 的結果回傳給 comments.pl

  3. comments.pl 的原始碼如下:
    #!/usr/local/bin/perl
    require 'forms-lib.pl';
    
    print "content-type: text/html\n\n";
    %input = &GetFormInput();
    $recipient = $input{'address'} || "jllu\@nchu.edu.tw";
    $message = $input{'comments'};
    $sender = $ENV{'HTTP_FROM'} || "jllu\@nchu.edu.tw";
    print <<EndofMessage;
    <html>
    <head><title>Comment Tests<title><head>
    <body>
    <h3>Your Comment is to be sent<h3>
    <pre>
    To: $recipient
    From: $sender
    Subject: Comments on your web page
    $message
    </pre>
    </body>
    </html>
    EndofMessage
    
    在取得 hash 結構 %input 之後,分別取得 address 和 comments 的 值的方式分別為 $input{'address'} 以及 $input{'comments'}。 最後,程式中還有一個值得說明的部分是 print <<EndofMessage 指的是 出現在這一行之後,一直到出現 EndofMessage 之間的字串都會被輸出(print)。








Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu

Perl 教學 -- 函數與字串處理

Perl 教學 -- 函數與字串處理

This tutorial is copyrighted and provided as is. You are welcomed to use it for non-commercial purpose.
Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu

請勿轉貼
看其他教材

函數 (Function):

  1. 建立與使用函數: 執行
    • 這個範例用來說明如何宣告一個函數,並呼叫它。程式碼如下:
      #!/usr/bin/perl
      
      sub Footer
      {
         print "<h2>Perl Program Using Functions</h2>\n";
         print "\n</body>\n";
         print "</html>\n";
      }
      
      print "Content-type: text/html\n\n";
      print "<html>\n";
      print "<head>\n";
      print "<title>Perl Program Using Functions</title>\n";
      print "</head>\n\n";
      &Footer;
        
    • 在程式碼中,我們宣告了一個名為 Footer 的函數(綠色的部分);函數宣告 的基本語法是使用保留字 sub 並在其後加上函數名稱(這個範例中使用的 是 Footer),函數名稱之後加上一對大括號,在大括號中加入必要的程式碼。
    • 呼叫函數的語法是 &函數名稱,因此呼叫 Footer 的方式如程式碼 中紅色的部分。

  2. 函數間傳送資料 (I): 執行
    • 在前一個範例中,我們宣告了一個 Footer 的函數,但是該函數 並無法接收呼叫端傳送過來的參數,但是在大多數的程式中,能夠宣告一個能接受 參數的函數是必要的,這個範例就是用於說明該方式。
    • 程式碼如下:
      #!/usr/bin/perl
      
      sub Header
      {
        print "Content-type: text/html\n\n";
        print "<html>\n";
        print "<head>\n";
        print "<title>@_</title>\n";
        print "</head>\n\n";
      }
      
      sub Footer
      {
        print "<h2>Perl Program Using Functions</h2>\n";
        print "\n</body>\n";
        print "</html>\n";
      }
      
      &Header("Perl Program Using Functions");
      &Footer;
        
    • 在程式中,我們把前一個範例中的 print 敘述全部定義在一個名為 Header 的函數(如綠色部分),然後呼叫它(如紅色部分)。請注意,呼叫端在函數名稱 之後加上了一對括號,並在括號內加入了一個字串,這代表呼叫 Header 並將 字串 "Perl Programming Using Functions" 傳給 Header;如果 Header 需要取用 該參數內容,則使用 @_
    • 嚴謹的說,@_ 代表一個呼叫端傳送過來的陣列。在本範例中,由於 只傳遞了一個參數,因此該陣列只有一個元素,我們也可以單獨使用 $_[0] 來取得該參數的內容,請試試看!

  3. 函數間傳送資料 (II): 執行
    • 這個範例用於說明如何傳遞多個參數資料給函數,而且函數產生的結果 可以回傳給呼叫端。
    • 程式碼如下:
      #!/usr/bin/perl
      
      sub Root
      {
        my($a, $b, $c) = @_;
        my($tmp, $x1, $x2);
        $tmp = sqrt($b ** 2 - 4.0 * $a * $c);
        $x1 = (-$b + $tmp) / (2.0 * $a);
        $x2 = (-$b - $tmp) / (2.0 * $a);
        return ($x1,  $x2);
      }
      
      
      $a = 1.0;
      $b = -2.0;
      $c = 1.0;
      @x = &Root($a, $b, $c);
      print "Content-type: text/html\n\n";
      print "x1 = $x[0]; and x2 = $x[1]\n";
        

    • 呼叫 Root 函數的時候,程式也傳遞三個參數資料(分別是變數 a、b、c; 這三個是全域變數),函數接收到資料後,將陣列資料 @_ 分別指定給 $a, $b, $c,其中,由於 ($a, $b, $c) 前面有 my, 因此這些變數 a、b、c 代表區域變數,而且只能在 Root 函數內使用;另外,Root 函數 又宣告了區域變數 tmp, x1, 和 x2。
    • 等到 Root 函數計算出結果後,它以 return 將變數值 x1 和 x2 (嚴謹的說,將包含變數 x1 和 x2 的陣列)回傳給呼叫端。
    • 呼叫端(紅色部分)將 Root 函數回傳的結果指定給一個名為 x 的陣列, 而其內容就可以 $x[0]$x[1] 的方式將資料取出。
  4. 使用 require: 執行
    • require 類似 C 語言的 include;基本上,它用來將另一個檔案的 內容"包"進檔案。
    • 原始碼:
      #!/usr/bin/perl
      
      require "req.pl";
      
      &Header("Perl Program Using Functions");
      &Footer;
        
      在程式碼中,我們利用 require 將一個名為 req.pl 的檔案包進來; 如以下的說明,req.pl 包含之前定義的 Footer 和 Header 兩個函數。這樣的 作法有一個好處,那就是 req.pl 的內容可以在多個程式中被重複使用。
    • req.pl 的程式碼如下:
      #!/usr/bin/perl
      
      sub Header
      {
        print "Content-type: text/html\n\n";
        print "<html>\n";
        print "<head>\n";
        print "<title>@_</title>\n";
        print "</head>\n\n";
      }
      
      sub Footer
      {
        print "<h2>Perl Program Using Functions</h2>\n";
        print "\n</body>\n";
        print "</html>\n";
      }
      
      return 1;  # this is required.
        
      請注意,在程式碼的最後一行必須加上如紅色部分的 return 1;;也 就是說,所有被包進某個檔案的程式(如本例中的 req.pl),其最後一行必須 加上 return 1;



日期函數

在撰寫 CGI-Perl 程式的時候,經常我們需要抓取系統的時間或日期。 Perl 提供了幾個有用的時間函數,你可以命令提示字元的視窗內下 perldoc perlfunc 的指令,然後搜尋 localtimegmtime。 本範例我們介紹 localtime 的使用方式:
#!/usr/bin/perl
($sec, $min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)  = localtime(time);
print "秒: $sec\n";
print "分: $min\n";
print "時: $hour\n";
print "一個月的第幾天: $mday\n";
print "月: $mon 範圍是 0-11,而一月為 0\n";
print "距離 1900 年的第幾年: $year\n";
print "一周內的第幾天: $wday  範圍是 0-6,而星期日為 0\n";
print "一年內的第幾天: $yday\n";

# 如果我只想要當天的日期,
($_,$_,$_, $mday, $mon, $year, $_,$_,$_) = localtime(time);
$year = $year + 1900;
$mon = $mon + 1;
print "今天是西元 $year 年 $mon 月 $mday 日\n";
練習題: 試著將上列的程式改成顯示目前的時間? 或者 顯示民國年?

字串、搜尋、與取代

  1. 例題 I:
    #!/usr/local/bin/perl
    $url = 'www.nchu.edu.tw';
    
    # Usage: /pattern/[g][o][i]
    # g for global, o for only once, and i for case-insentitive
    # url 是否包含 nchu 字串
    if ( $url =~ /nchu/ )
    {
       print "$url is 國立中興大學.\n";
    }
    
    # 將 'edu' 取代為 EDU
    # Can you use tr? (ie. tr/edu/EDU/)
    $url =~ s/edu/EDU/;
    print "\$url is now $url.\n";
    
  2. 例題 II:
    1. 大寫變小寫
        #!/usr/local/bin/perl
        $names = "fred and mary";
        $names =~ tr/a-z/A-Z/;
        print "$names\n";
        
    2. 計算字串長度
        #!/usr/local/bin/perl
        $count = "fred and mary";
        #
        # 若不使用 =~, tr 傳回轉換的字元總數
        $count = tr/a-z //;
        print "$count\n";
        
  3. 例題 III: 在使用 GET 方法的 Form 例題中, 請在輸入欄內輸入多於 一個字並觀察其執行情形。 你應該可以看到網址輸入欄內的內容 (如果輸入的是 aaa bbb)為 input=aaa+bbb。 這是因為空格被 "+" 符號 (URL-encoded characters) 取代。常見的 URL-encoded characters 包含:
    CharacterURL-encoded characters
    Tab%09
    空格+
    !%21
    +%2B

    那麼當成是接收到 input=aaa+bbb 的時候,它要如何將 + 轉換成空格呢?以下我們利用 GET 和 POST 的範例,分別列出轉換的方式。

    • GET 的方式:
      • form 表單:
        請輸入文字(GET):
      • 該表單呼叫 sub.pl,而其程式碼如下:
        #!/usr/local/bin/perl
        print "Content-type: text/plain\n\n";
        $input = $ENV{'QUERY_STRING'};
        
        # translate + into space.
        $input =~ tr/+/ /;
        print "$input.\n";
        
        # s: substitute
        # \d: a number, A-F: A,B,C,D,E,F, a-f: a,b,c,d,e,f
        # [\dA-Fa-f]: either a number, A, B, ... , F, a, b, ..., or f.
        # pack("c", hex($1)): transform %[][] into a character ("c").
        # e: treat pack() as an expression instead of a string.
        # $input =~ s/%(..)/pack("c", hex($1))/eg;
        $input =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack("c", hex($1))/eg;
        print "$input.\n";
        
      • 程式碼中,除了第一段是進行之前說過的"將 + 轉換成空格",第二段我們 使用了更進階的方式將所有 URL-encoded characters 轉換成字串。為了容易說明, 請在表單中輸入一個中文字(例如),執行後,讀者應該可以從網頁或者 瀏覽器的 URL 欄位看到,(不含雙引號)這個字被轉換成的 URL-encoded characters 是 %AA%C5,這樣的內容程式必須加以處理才能轉換 成我們需要的。轉換的規則如下:我們需要從資料內找出所有的 URL-encoded characters,而這些字元都符合 %XX 格式,而 X 代表 16 進位的數字(也就是 0-9A-F);Perl 的搜尋規則即為 %([\dA-Fa-f][\dA-Fa-f]);找到字元之後,我們利用 pack() 方法,將其 16 進位的資料轉換成字串。 pack() 的第一個參數 "c" 就是指定轉換成字串的設定,我們也可以 轉換成其他資料型態,有興趣的讀者,可以參考 pack 的用法。


    • POST 的方式:
      • form 表單:
        請輸入文字(POST):
      • 該表單呼叫 subp.pl:因為該程式除了經由 POST 方式來讀取資料而跟 sub.pl 不同以外,其他部分相同,因此不再贅述。





Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu



Perl 教學 -- 簡單的 Perl 程式

Perl 教學 -- 簡單的 Perl 程式

This tutorial is copyrighted and provided as is and can be used as supplement to any CGI tutorial materials such as Common Gateway Interface, written by 網際工作室(Internet Studio). You are welcomed to use it for non-commercial purpose.
Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu

請勿轉貼
看其他教材

一些簡單的 Perl 程式

首先讓我們先了解一些簡單的 Perl 語法;讀者可以將下列程式碼 儲存成一個檔案,然後在"命令提示字元"內執行。
  • Hello World:將連結內的原始碼儲存為(例如) hello.pl,然後請在"命令提示字元"內輸入 perl hello.pl 來執行。執行後的畫面如下:
    這個程式碼中真正的 Perl 程式敘述只有一行,也就是包含 print 的 那一行敘述,它的目的就是將字串輸出到標準輸出裝置,也就是螢幕;如果 你把這個程式經由 mod_perl 處理,print 會將字串從 Apache 傳回給瀏覽器,並由瀏覽器呈現。
  • 解 ax2 + bx + c = 0 (I):在這個 程式,我們首先宣告了三個變數 a、b、和 c。經由 Perl 提供的方法函數 sqrt(),程式計算了 b2 - 4ac 的平方根,並將結果 指定給變數 tmp;最後,計算兩個解並將結果列印出來。
  • 解 ax2 + bx + c = 0 (II):這是 解方程式的另一個版本,由於使用了 <STDIN> 來讀取使用者 輸入的資料,因此這個程式不能經由 mod_perl 執行。除此之外,這個程式還有 一些值得說明的:
    • chomp():由於使用者輸入數字之後需要按"Enter"鍵,因此變數 a、b、和 c 內的字串最後都有"跳行"的控制字元;因此我們需要使用 chomp() 把"跳行"的控制字元去除。
    • 狀態 || 敘述:這個敘述的意思是"如果狀態為 false,則執行 || 後的敘述。
    • die 的用法是將其後面的字串顯示出來之後,把程式結束掉。




格式化輸出

#!/usr/local/bin/perl
$s = "My name is Eric.";
$n = 5400;
$r = 123.456;

// 結果是 "My Name is Eric ^5400 ^^^^123.46"
printf "%15s %5d %10.2f\n", $s, $n, $r;
如果希望把 123.46 這項結果指定給另一個變數呢?
$newr = sprintf("%.2f", $r);

資料結構

  1. 變數: $input 是一個變數。 一個變數可以包含數字或字串。 你可以利用適當的 operators 去處理變數, 試試看這個例子:
      #!/usr/local/bin/perl
      $str = "th Perl";
      $str .= " CGI program.\n";
      $num = 1;
      $num++;
      $num += 1;
      $num = $num + 1;
      print "My $num$str";
      
  2. 陣列 (array) 或 串列 (list): @addr 代表一個陣列。
      @addr = ("www.cyut.edu.tw", 80, "/~jlu/");
      print "http://$addr[0]$addr[2]\n";  # @addr and $addr
      
      常用的陣列函示:
    1. split(/pattern/, $line)
          $addr = "www.cyut.edu.tw";
          @tmp = split(/\./, $addr);   # 以後討論
          print '$tmp[2] is ', $tmp[2], "\n";
          
      練習: 若 $time = "18:30:32";, 請將結果 「下午6點30分32秒」印出。
  3. Hash (雜湊): 舊稱結合陣列 (associative array): %url 代表一個 Hash。 一>個 Hash 是一群 (key, value) 組合而成的陣列。 例如在前一個例子中, address 是 www.cyut.edu.tw, port 是 80, 而 path 是 /~jlu/, 因此 %url 可定義為
           $url{"address"} = "www.cyut.edu.tw";
           $url{"port"} = 80;
           $url{"path"} = "/~jlu/";
           
      常用的 Hash 函示:
    1. keys(%array): 傳回 %array 的所有鍵。
    2. values(%array): 傳回 %array 的所有值。
    3. each(%array): 一次傳回一對鍵與值。
  4. Hash and Array:
      # @url_list gets (key1, value1, key2, value2, ...)
      @url_list = %url;
    
      # create %newurl like %url
      %newurl = @url_list;
    
      # easier and faster.
      %newurl = %url;       # easier and faster.
      
  5. Name: $eric, @eric, %eric 雖然使用同樣的名稱, 但是對 Perl 而言, 他們代表完全不同的意義。 縱使 Perl 能分辨出他們的不同, 在寫程式 我們不鼓勵這樣做。
      $eric = "Eric";
      @eric = ("Hello", "Carol");
      %eric = ("Last Name", "Lu", "First Name", "Eric");
      @tmp = keys(%eric);
    
      print '$eric is ', $eric, "\n";;
      print '@eric[1] is ', $eric[1], "\n";
      print '$eric{"First Name"} is ',
            $eric{"First Name"}, "\n";
      print '$eric{$tmp[0]} is ',
            $eric{$tmp[0]}, "\n";
      

控制結構:

  1. if 敘述: if 敘述的括號 ({}) 不能省略。 如果 condition 是空字串, 0 (zero), 或 "0" (零字串), 則結果為偽。 其餘為真。
    1. if (condition) { statements; }
    2. if (condition) { statements; } else { statements; }
    3. if (condition) { statements; } elsif { statements; } else { statements; }
    字串比較的運算子有: eq, lt, gt, le, ge, and ne。 相對的數值運算子有: ==, <, >, <=, >=, !=。
  2. while 敘述: while (condition) { statements; }
  3. do-while 敘述: do { statements; } while (condition);
  4. for 敘述: for( initial_exp; test_exp; re-init_exp ) { statements; }
  5. foreach $i ( @array ) { statements; }

控制結構與資料結構的例題:

  1. 例題 I:
      if ($url{"address"} eq "www.cyut.edu.tw")
      {
        print "You're pointing to CYUT.\n";
      }
    
      if ($url{"port"} == 80)
      {
        print "Port is 80.\n";
      }
      else
      {
        print "Wrong port number.\n";
      }
      
  2. 例題 II:
      foreach $key (keys(%url))
      {
        print "key is $key.\n";
      }
      
  3. 例題 III:
      while (($key, $value) = each(%url))
      {
        print "$key is $value.\n";
      }
      
  4. 例題 IV:
      # if there are 6 elements in @url_list, when @url_list
      # compares with an integer, it will return 6.
      for ( $i = 0; $i < @url_list; $i++)
      {
        print "$url_list[$i] ";
      }
      print "\n";
    
      # $#addr: size of addr - 1
      for ( $i = 0; $i <= $#addr; $i++ )
      {
         print "$addr[$i]\n";
      }
      

Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu

Perl 教學 -- Perl 與 Form

Perl 教學 -- Perl 與 Form

This tutorial is copyrighted and provided as is. You are welcomed to use it for non-commercial purpose.
Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu

請勿轉貼
看其他教材

Perl 與 Form (I)

說明事項:
  1. 這個範例用來說明如何經由網頁上的 HTML form 表單元件來呼叫伺服器端的 perl 程式。
  2. 首先在網頁上設計表單元件,這個範例是設計一個按鈕,其原始碼如下:
    <form action="1st.pl">
    <input type="submit" value="Hello World">
    </form>
    
    基本上,該表單使得使用者在按鈕上點一下的話,它會呼叫伺服器端名為 1st.pl 的程式。如果讀者對於表單元件不熟悉的話,可以參考 Form Pages
  3. 1st.pl 的內容跟之前的 hello.pl 類似,其程式碼如下:
    #!/usr/bin/perl
    print "Content-type: text/html\n\n";
    print "<html><head><title>My First Perl Program</title></head>\n";
    print "<body><h1>Hello World</h1></body></html>\n";
    

    • Perl 的註解符號是 "#"。
    • print "string"; 也可寫成 print("string");
    • "Content-type: text/html" 是所謂的 MIME header;它的功能在於告訴瀏覽器 即將傳送過來的資料是 HTML 網頁。
    • "\n" 代表 newline。依據規定,在 MIME header 後, 必須要有兩個 "\n"。
    • 在 Perl 中, 字串 (string) 可以以雙括號 " 或單括號 ' 表示。 如 "string" 與 'string' 都代表同一個字串。 不過, "string\n" 與 'string\n' 便不同。 試試看!
    • 函數 substr(string, offset) 會將 string 位於 offset 位置之後 的子字串回傳;string 的索引位置從零開始。
      1. print substr("Hello World", 6); 會回傳 World。
      2. print substr("Hello World", -2); 會回傳字串的最後兩個字元,也就 是 ld。



Perl 與 Form 結合 (II, GET)

請輸入文字:
說明事項:
  1. 在這個範例中,我們說明如何將使用者在網頁上輸入的資料傳送到伺服器端的 程式。在 HTTP 的協定中,資料傳送的方式有兩種,一種是 GET,另一種是 POST; 在這個範例我們先說明 GET。
  2. 表單元件的原始碼如下:
    01: <form method="GET" action="2nd.pl">
    02: 請輸入文字:<input type="text" name="input">
    03: <input type="submit" value="Submit">
    04: <input type="reset" value="Clear">
    05: </form>
    
    第 01 行說明,如果使用者輸入資料之後,瀏覽器會以 GET 的方式將資料傳送給 2nd.pl;第 02 行說明,這是一個文字欄位,而使用者輸入的資料在 傳送給伺服器的程式時,該程式可以格式為 input=資料 方式來取得資料。 如果你在文字欄位上輸入 Eric,並按下 Submit,你會看到如下的畫面:

    在畫面中,請留意兩件事情:第一,在 URL 欄位中,它在程式名稱(2nd.pl)後面 加上了 ?input=Eric,它代表它利用了 GET 的方式將 input=Eric 傳送給 2nd.pl;第二,2nd.pl 將 URL 中的資料擷取出來,並顯示在網頁上, 擷取的方式如以下說明。
  3. 2nd.pl 的原始碼如下:
    #!/usr/local/bin/perl
    print "Content-type: text/plain\n\n";
    $input = $ENV{'QUERY_STRING'};
    print "$input\n";
    
    GET 的傳送方式是將資料傳送到伺服器的環境變數內,而其中代表 input=Eric 的環境變數名稱為 QUERY_STRING,所以 Perl 經由 $ENV{'QUERY_STRING'} 將名為 QUERY_STRING 的內容取出,並指定給變數 input。
  4. 除了 QUERY_STRING 的環境變數,是否還有其他的環境變數?我們 可以經由以下程式得到答案,你也可以點一下按鈕來觀察。

    #!/usr/bin/perl
    print "Content-type: text/html\n\n";
    print "AUTH_TYPE is $ENV{'AUTH_TYPE'} <br>";
    print "CONTENT_LENGTH is $ENV{'CONTENT_LENGTH'} <br>";
    print "GATEWAY_INTERFACE is $ENV{'GATEWAY_INTERFACE'} <br>";
    print "HTTP_USER_AGENT is $ENV{'HTTP_USER_AGENT'} <br>";
    print "HTTP_REFERER is $ENV{'HTTP_REFERER'} <br>";
    print "QUERY_STRING is $ENV{'QUERY_STRING'} <br>";
    print "REMOTE_ADDR is $ENV{'REMOTE_ADDR'} <br>";
    print "REMOTE_HOST is $ENV{'REMOTE_HOST'} <br>";
    print "REMOTE_IDENT is $ENV{'REMOTE_IDENT'} <br>";
    print "REMOTE_USER is $ENV{'REMOTE_USER'} <br>";
    print "REQUEST_METHOD is $ENV{'REQUEST_METHOD'} <br>";
    print "SCRIPT_NAME is $ENV{'SCRIPT_NAME'} <br>";
    print "SERVER_SOFTWARE is $ENV{'SERVER_SOFTWARE'} <br>";
    print "SERVER_NAME is $ENV{'SERVER_NAME'} <br>";
    print "SERVER_PROTOCOL is $ENV{'SERVER_PROTOCOL'} <br>";
    







Perl 與 Form 結合 (III, POST)

請輸入文字:
說明事項:
  1. 這個範例用於說明如何利用 POST 的方式傳送使用者輸入的資料,以及 perl 程式如何擷取這些資料。我們使用的表單跟前一個範例非常類似,差別只在 method 設定為 POST,而程式名稱改成 3rd.pl
  2. 若跟之前一樣,在文字欄位內輸入 Eric,則執行的畫面如下:
    其中,請特別注意畫面中 URL 欄位,並不像之前會出現 ?input=Eric 的 訊息,而且由於這個特色,許多系統的設計都採用 POST,而不採用 GET。 當然,POST 的優點不僅如此,如以下程式中所顯示的,POST 傳送給程式的資料 是經由標準輸入裝置(STDIN),因此沒有資料量的上限;反之,GET 是經由 環境變數而傳遞,因此有資料量的限制。
  3. 3rd.pl 的原始碼如下:
    #!/usr/local/bin/perl
    print "Content-type: text/plain\n\n";
    $length=$ENV{'CONTENT_LENGTH'};
    read(STDIN, $input, $length);
    print "$input\n";
    
    • 程式先經由環境變數 CONTENT_LENGTH 得知資料的總量,然後經由 標準輸入裝置讀取資料,並存放於變數 input 內。
    • 跟所有程式一樣,Perl 也內建三個標準裝置: STDIN, STDOUT, STDERR 分別 代表標準輸入、標準輸出、以及標準錯誤。




Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu

Perl 教學 -- 前言

Perl 教學 -- 前言

This tutorial is copyrighted and provided as is and can be used as supplement to any CGI tutorial materials such as Common Gateway Interface, written by 網際工作室(Internet Studio). You are welcomed to use it for non-commercial purpose.
Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu

請勿轉貼
看其他教材

前言

本文假設你已經具備有下列條件:
  1. 你瞭解 HTML 語法並且會寫程式 (最好是 C)。
  2. 你的系統已安裝 Perl 5.x。
  3. 你的 Web 伺服器支援 CGI 且你能從你的網頁執行 CGI 程式。
註: 下列 Perl 程式的第一列皆包含 #!/usr/local/bin/perl。 這一列指令對 Win32 版的 Perl 不重要, 但是對 Unix 系統卻是必要的。 有些系統的 Perl 安裝在其他目錄, 請詢問系統管理人員並適當的更改路徑。

什麼是 Perl?

Perl 是一個功能非常強大的 script language。 它的全名是 Practical Extraction and Report Language。 Larry Wall 是它的創 造者。 從 1988 年 1 月發行第一版至今日的第五版, Perl 已經過了十幾年的歲月。

誰需要 Perl?

  1. 系統管理員。
  2. 網頁開發人員。

為什麼?

  1. Perl 易於學習。
  2. Perl 擁有超強的文字處理功能。
  3. Perl 包括了豐富的封裝群組 (packages) 與模組 (modules), 使得它 非常適合於做檔案輸出與輸入, 以及存取幾乎所有常用的資料庫系統 (如 Oracle, Sybex, SQL Server, ODBC, etc.)

Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu

Perl 教學 -- 安裝

Perl 教學 -- 安裝

This tutorial is copyrighted and provided as is and can be used as supplement to any CGI tutorial materials such as Common Gateway Interface, written by 網際工作室(Internet Studio). You are welcomed to use it for non-commercial purpose.
Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu
請勿轉貼
看其他教材

我的電腦可以安裝 Perl 嗎?

目前已知可以安裝 Perl 的系統有 Unix(含各式各樣的 Linux 版本;如 FreeBSD、 Debian、Ubuntu 等), OS/2, Mac, Amiga, Win32, etc. DOS 不行。

何處可以取得 Perl?

你可以從所有的 CPAN 網站取得免費的 Perl 軟體。 在台灣, 你可以到 Perl 資源 網站以 取得更進一步的消息。另外,在 Win32 的系統上,本人推薦安裝 ActivePerl,讀者可以 下載其免費的 ActivePerl Community Edition 版。

安裝 Apache 與 Perl 在你的 PC

由於我們希望能藉由 Web 伺服器來執行 perl 程式,因此我們需要先安裝一個 Web 伺服器。目前市佔率最高的 Web 伺服器是 Apache 的 HTTP Server,所以 我們先安裝 Apache 2.2.x 版; 本文假設你的 PC 安裝的作業系統是 Win32 系列(含 XP/Server/Vista/Win7 等), 請至 下載網頁 下載 Win32 Binary including OpenSSL 0.9.8m (MSI Installer);如果你使用的是 其他類的作業系統,請依據必要的程序安裝。基本上,本文介紹的 Perl 語法以及 用法與你使用的作業系統應該無關。 安裝 Apache 的過程中,有幾個地方要注意的:第一,先確認你安裝 Apache 的 電腦是否已經有了註冊過的 hostname(例如,www.nchu.edu.tw);如果有,請 在以下的畫面中的 "Network Domain" 填入 nchu.edu.tw,"Server Name" 填入 www.nchu.edu.tw,以及 "Administrator's Email Address" 填入 一個可以聯絡的到你的 email 帳號。



如果讀者沒有 hostname 的話(大多只是為了學習或者測試的人都沒有),請在 "Network Domain" 填入任意值(不能留空白),在 "Server Name" 填入 localhost,然後就可以按 "Next" 繼續安裝。另外,由於我不太喜歡 預設的安裝位置(路徑名稱太長,而且名稱中含有空格,容易造成不必要的麻煩), 我將其安裝於 e:\apache22,在之後的解說中,我們也是以這個路徑 為主;如果讀者安裝在其他的路徑,請作適當修改。 如果讀者的安裝環境跟我的差不多(沒有 hostname 又安裝了防毒軟體 Kaspersky), 安裝的結果是無法正常的啟動 Apache 的,畫面大概如下所示:



這個畫面說明了兩個問題;第一個是 Apache 無法從剛才輸入的 "Network Domain" 和 "Server Name" 找到適當的 IP。這個問題的解決方式就是手動的修改 Apache 的設定檔 httpd.conf;請再修改前先備份設定檔,以便於改錯的時候, 還可以再來一次。設定檔的鎖在位置在 e:\apache22\conf\httpd.conf, 請依據以下畫面



請將畫面中 #ServerName localhost:80 前的井字號(#)刪除,變成 ServerName localhost:80。第二個問題在於 Apache 試圖跟 IP 位置 0.0.0.0:80 連結卻失敗了;為了解決這個問題,我需要明確在 httpd.conf 中明確告訴 Apache 連結上一個特定的 IP;另外,我也 必須確定防毒軟體是否阻擋了該項連結(Kaspersky 會阻擋,你必須在防火牆的 設定中,在"封包篩選規則"中允許"Localhost Loopback TCP Activity")。 設定檔的修改畫面如下:



請將畫面中 Listen 80 修改成 Listen IP:80,在 IP 的地方放入你電腦的 IP 位置即可。一切修改完成之後,你就可以啟動 Apache 了。啟動的方式可以經由 ApacheMonitor (出現在 XP 右下角) 或者在"命令提示字元"輸入 e:\apache22\bin\httpd -k start 來啟動。在 Apache 成功啟動後,請在瀏覽器內輸入 http://yourip (也就是剛才輸入 Listen 後面的 IP) 你就可以看到如下的畫面;如果沒有,你必須重來一次。
就像之前的建議,我們安裝 ActivePerl Community Edition。ActivePerl 的安裝非常簡單,我們就不再贅述。最後, 為了能讓 Apache 更有效率的執行 perl 程式,我們建議安裝一個 Apache 的 perl 模組 mod_perl。根據 mod_perl 2.0 Win32 Installation Instructions 的說法, 由於我們安裝的 ActivePerl 是 10xx 版(或者 perl 5.10 版),安裝的方式是在 "命令提示字元"內輸入

set PATH=c:\perl\bin;%PATH%
ppm install http://cpan.uwinnipeg.ca/PPMPackages/10xx/mod_perl.ppd


兩行指令;第一個指令在於設定 PATH 環境變數,第二個指令在於安裝 mod_perl 2.0 版。執行後,你會看到如下的畫面:



在安裝的過程中,我們只需要如紅色框框中所顯示的,輸入 mod_perl 的安裝位置; 在我們的範例中,安裝位置在 e:/apache22/modules。安裝完成後, 我們需要對 httpd.conf 進行修改,請將下列兩行敘述加入設定檔:

LoadFile "c:/perl/bin/perl510.dll"
LoadModule perl_module modules/mod_perl.so


另外,為了告訴 Apache 什麼時候需要載入 mod_perl 來處理 perl 程式, 我們必須在 httpd.conf 的最後,加入以下設定:

    <Files ~ "\.(pl)$">
    SetHandler perl-script
    PerlResponseHandler ModPerl::Registry
    Options +ExecCGI
    PerlOptions +ParseHeaders
</Files>


這項設定明確的告訴 Apache,當使用者要求的 URL 中,最後的副檔名是 .pl, 則該檔案就交給 mod_perl 來處理。 設定檔修改完成後,我們需要重新啟動 Apache。由於安裝的過程,我們安裝 了一些套件,而這些套件又需要某些環境變數的配合,所以如果安裝後,無法正常 使用 Apache + Perl,這時候你可能需要重新開機。

確認你的 Apache + Perl 的安裝

按一下執行看看。如果你依據我們的說明,你應該會看到 一個相同的執行結果。以下是我們第一個 Perl 程式,其程式碼如下:

#!/usr/local/bin/perl
print "Content-type: text/html\n\n";
print "<html><head><title>My First Perl Program</title></head>\n";
print "<body><h1>Hello World</h1></body></html>\n";


請將該程式碼儲存成一個名為 test.pl 的檔案,並將其放置於 e:/apache22/htdocs 目錄內,然後請在瀏覽器內輸入 http://yourip/test.pl 即可正確執行。

Perl 教學

Perl 教學

This tutorial is copyrighted and provided as is. You are welcomed to use it for non-commercial purpose.
Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu

請勿轉貼
看其他教材

目錄

  1. 前言
  2. 安裝
  3. 一些簡單的 Perl 程式
  4. Perl 與 Form
  5. 函數與字串處理
  6. 表單處理
  7. 檔案處理
  8. Server-Side Includes
  9. 資料庫查詢 (ODBC)
  10. 資料庫查詢 (DBI)
  11. 我還想更瞭解 Perl, 有哪些書可以參考?

檔案處理:

範例: 學生成績查詢
  1. 檔案格式: 檔案的第一列包含各欄位的標題如代碼, 第一個作業, 期末考 等。 第二裂開始為實際資料。 在本例中, 我們規定學生代碼必為一連續字, 例如:
    代碼  作業一(50)  作業二(50) 作業三(75)  專題   期中考(128) 成績
    ABC           25      30       45        75          74       70
    Kevin_C       30      40       45        70         103       79
    Tina          40      25       60        80         105       85
    totoro        30      30       57        85          95       83
    wei-jen       30      25       62        70          85       74
    
  2. 表單格式: 完整原始碼
    Grades
    請選擇班別: 四技二A 四技二B
    請輸入代碼:
  3. Perl 檔案函數: 打開檔案並計算欄位數。
    #!/usr/local/bin/perl
    
    require 'req.pl';
    require 'forms-lib.pl';
    
    # open a file called "sa4a.txt" and assign it 
    # a filehandler called INP.
    # if file cannot open, execute die().
    open(INP, "sa4a.txt") || die("Cannot open sa4a.txt.\n");
    @recs = <INP>;
    
    # get the first record
    $record = $recs[0];
    
    # get rid of consecutive whitespaces
    # \s: whitespace, +: one or more.
    @fields = split(/\s+/, $record);
    $num_field = @fields;
    
    # a way of printing what we got.
    #print "Record is @fields.\n";
    #print "Number of field is $num_field.\n";
    
    &Header("Grades");
    
    # print table header
    print "$record\n";
    
    # read data till the end of the file
    for($row=1; $row < @recs; $row++)
    {
       $record = $recs[$row];
       print "$record\n";
    }
    
    &Footer;
    
  4. 寫資料到檔案:
    #!/usr/bin/perl
    
    $a1 = "Eric";
    $a2 = 80;
    $a3 = 75;
    
    # ">sa4a.txt" 產生輸出檔
    # ">>sa4a.txt" 產生附加式的輸出檔
    open(OUTP, ">sa4a.txt") || die "Cannot open file\n";
    print OUTP "$a1 $a2 $a3\n";
    close OUTP;
    

Server-Side Includes

常常看到計數器嗎﹖ 想想看,我們似乎可以將已經拜訪的次數放在一個檔案中, 而每一次有訪客到的時候,便執行一個簡單的 CGI 程式來更改檔案內的數字。 可是我們所學的都需要經過 form 的元件才能執行,我們要如何才能使得 訪客一到這個網頁就能自動執行這個計數器呢﹖ 請參考 SSIs

資料庫查詢 (ODBC)

Perl 也提供與各種資料庫 (如 mSQL, Oracle, Sybase, Xbase 等) 的連結。 在本例中, 我們僅討論如何利用 ODBC 的方式與資料庫連結。 (ODBC 僅適用於 Win32 的系統. 其他 的連結方法,再下例中有進一步的說明.) 連結 ODBC 資料庫的方式有兩種方法。 在以下 的說明中, 我們使用的是一個 Microsoft Access 的資料庫 -- samples.mdb。 這個資料庫中包含一個 Table, 其名稱為 Product。 Product 有四個欄位 (ID, Name, Price, Qty)。 請於下載後, 利用 ODBC 將其設定為 Samples. 其過程為:
「開始」 --> 「設定」 --> 「控制台」 -->  「ODBC」 -->  
「系統資料來源名稱」 -->  「新增」 --> 
「Microsoft Access Driver (*.mdb)」  --> 「完成」 
在 "資料來源名稱" 欄, 輸入 Samples, 並 「選擇」 samples.mdb 後按 OK。
  1. 幾個簡單的 SQL 範例:
    1. 新增 (insert): 將一筆資料加入 Product.
          insert into Product values ('5','燒錄器', 15000, 10)
          
    2. 查詢 (select):
      1. 查詢全部資料:
              select * from Product
              
      2. 查詢名稱為'燒錄器'的相關資料:
              select * from Product where Name='燒錄器'
              
      3. 查詢名稱為'燒錄器'的目前存量:
              select Name, Qty from Product where Name='燒錄器'
              
      4. 查詢單價低於 2500 元的產品:
              select * from Product where Price < 2500
              
      5. 查詢單價介於 300 與 10000 元間的產品:
              select * from Product where Price >= 300 and Price < 10000
              
    3. 更改 (update): 將燒錄器的存量改為 20.
          update Product set Qty=20 where Name='燒錄器'
          
    4. 刪除 (delete): 刪除燒錄器的產品資料
          delete from Product where Name='燒錄器' 
          
  2. 你可使用 Win32::OLE。 原始碼如下:
    use Win32::OLE;
    
    # setup the names of DSN and Table.
    $DSN = "Samples";
    $Table = "Product";
    
    # Connect and open the database
    $Conn = new Win32::OLE "ADODB.Connection";
    $Conn->Open("DSN=$DSN;UID=;PWD=");
    #$Conn->Open("$DSN", "",  "");
    #$Conn->Open("$DSN");
    
    # The followings don't work well.
    #$Conn->Open("DSN=Samples;UID=;PWD=") || die "Cannot connect";
    #$Conn or die "Cannot connect";
    
    # Execute the SQL statement
    $RS = $Conn->Execute("SELECT * FROM $Table");
    
    if(!$RS) {
            $Errors = $Conn->Errors();
            print "Errors:\n";
            foreach $error (keys %$Errors) {
                    print $error->{Description}, "\n";
            }
            die;
    }
    
    # Retrieving records from Table.
    while ( !$RS->EOF ) {
            my($ID, $Name, $Price, $Qty) = (
                    $RS->Fields('ID')->value,
                    $RS->Fields('Name')->value,
                    $RS->Fields('Price')->value,
                    $RS->Fields('Qty')->value );
    
            print $ID, " : ", $Name, " : ", $Price, " : ", $Qty, "\n";
            $RS->MoveNext;
    }
    
    # Close the connection.
    $RS->Close;
    $Conn->Close;
    
  3. 若你使用 Win32::ODBC, 原始碼如下:
    use Win32::ODBC;
    
    # set Data Source Name
    $DSN = "Samples";
    
    # Open connection to DSN
    if (!($O = new Win32::ODBC($DSN))){
        print "Failure. \n\n";
        exit();
    }
    
    # set Table name
    $Table = Product;
    
    # Get the content of the table.
    if (! $O->Sql("SELECT * FROM $Table"))
    {
    
        # print out the field names.
        @FieldNames = $O->FieldNames();
        $Cols = $#FieldNames + 1;
    
        for ($iTemp = 0; $iTemp < $Cols; $iTemp++){
            $FmH2 .= "$FieldNames[$iTemp] ";
        }
        chop $FmH2;
        print "$FmH2\n";
    
        # Fetch the next rowset
        while($O->FetchRow()){
            undef %Data;
            %Data = $O->DataHash();
            print $Data{'ID'}, " ", $Data{'Name'}, " ", 
                  $Data{'Price'}, " ", $Data{'Qty'}, "\n";
        }
    }
    
    # Close Connection.
    $O->Close();
    

資料庫查詢 (DBI)

前例中, 作者曾提及 Perl 可與各種資料庫連結。 其中, DBI 是一類似 ODBC 的介面。 只要安裝適當的資料庫驅動程式 (DBD), Perl 便可經由它使用相同的 function calls 與許多資料庫連結。 (DBI 也有 ODBC 的驅動程式, 這裡提供了一個範例。) 如果想對 DBI 作更進一步的了解,請於安裝 DBI 的電腦上執行 perldoc DBI 已獲得更詳細的說明。若你需要經過 ODBC 來連結 資料庫(如 MS SQL Server),你可以使用 perldoc DBD::ODBC 獲得更詳細的說明。 在本例中, 我們以 mSQL 為例。 作者假設你可存取任一 mSQL 資料庫。 我們使用的是一個名為 db_test 的資料庫, 它位於 penguin.im.cyut.edu.tw。 這個資料庫中包含一個 Table, 其名稱為 Product。 Product 有四個欄位 (ID, Name, Price, Qty)。 原始碼如下:
#!/usr/bin/perl

use DBI;

# initialize datasourcename. for details, perldoc DBD::mSQL.
# to connect to a DB server on another host such as sun20,
#$dsn = 'db_test:sun20';
$dsn = 'db_test';

# 1. to connect to other DB such as Oracle, all you need to
#    do is to replace "mSQL" with "Oracle". (assume that
#    Oracle driver has been installed.)
# 
# 2. to connect to MS Access, simply change DSN to 'dbi:ODBC:Samples'
#
$dbh = DBI->connect("dbi:mSQL:$dsn", "", "")
             || die "Can't connect to $data_source: $DBI::errstr";

$sth = $dbh->prepare("SELECT * FROM Product")
             || die "Can't prepare statement: $DBI::errstr";

$rc = $sth->execute
             || die "Can't execute statement: $DBI::errstr";

print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n";
print "Field names: @{ $sth->{NAME} }\n";

while (($ID, $Name, $Price, $Qty) = $sth->fetchrow_array) 
{
  print "$ID, $Name, $Price, $Qty\n";
}

# check for problems which may have terminated the fetch early
die $sth->errstr if $sth->err;

$sth->finish;
另外, 你也可以安裝 mSQL 專用的模組 (如 Msql), 使用以下程式 也可以達到上述範例的結果。 欲知 Msql 的細節, 請執行 perldoc Msql。 [註: 安裝 Msql 模組前, 需先安裝 DBI]
#!/usr/bin/perl

use Msql;

# Connect to DB, db_test, located at the local host.
# mSQL is also available on sun20.im.cyut.edu.tw. Therefore, you
# can also connect to db_test on sun20 by
#   $db = Msql->connect("sun20","db_test") or 
#         die "Cannot connect to db_test on sun20.";
# When using with CGI, it is a perfect example of 3-tier architecture.
#
$db = Msql->connect("","db_test") or die "Cannot connect to db_test";

# you can insert a row
#$db->query("insert into Product values('11', '數據機', 5000, 10)");
# or you can delete what you just inserted
#$db->query("delete from Product where ID='11'");

# submit the query.
$sth = $db->query("select * from Product") or die "Cannot Quety.";

# obtain various info about this table.
print "Number of rows: ", $sth->numrows, "\n";
print "Number of columns: ", $sth->numfields, "\n";
print "\n";

# obtain field names
@fnames = $sth->name;
@ftypes = $sth->type;
for($i=0; $i<$sth->numfields; $i++)
{
  print $fnames[$i], " is of type ", $ftypes[$i], "\n";
}
print "\n";

# fetch records from the table
#
# Case 1: fetch a row at a time.
#while(@arr = $sth->fetchrow)
#{
#  # print out field values of each row.
#  foreach $arr (@arr)
#  {
#    print $arr, " ";
#  }
#  print "\n";
#}

#
# Case 2: fetch entire row, including field names, into a hash
while(%hash = $sth->fetchhash)
{
  print $hash{'ID'}, " ", $hash{'Name'}, " ", $hash{'Price'},
        " ", $hash{'Qty'}, "\n";
}

我還想更瞭解 Perl, 有哪些書可以參考?

除了一開始推薦的 The Developer COM 的線上書外, 一般公認的好書有:
  1. Larry Wall, Tom Christiansen, and Randal Schwartz, Prorgamming Perl, 2nd edition, O'Reilly & Associates, 1996.
  2. Randal Schwartz, Learning Perl, 2nd edition, O'Reilly & Associates, 1997. (Unix Systems)
  3. Randal Schwartz, Erik Olson, and Tom Christiansen, Learning Perl on Win32 Systems, O'Reilly & Associates, 1997. (Win32 Systems) [松崗代理]

Written by: 國立中興大學資管系呂瑞麟 Eric Jui-Lin Lu