Perl 網頁程式設計課程目錄

Perl 單量陣列(Scalar Array)

在資料庫簡介一節簡單介紹過, 陣列可以用來儲存一大筆資料. 大大增加了資料的易讀性. 本章將討論陣列的應用方法.

陣列可分為單量陣列 (Scalar Array) 及關聯陣列 (Associate Array), 本節會先討論單量陣列, 稍後才討論比較複雜的關聯陣列.

再以先前的例子:

@family=("Kong","Wai","Keung","Yau")

@ 符號指示這是一個單量陣列. 而陣列內的資料稱之為元素.

這樣, @family 便可包含了四個資料元素了,當然, 一個陣列可以有任意個數的元素.

陣列設定後, 陣列內的資料元素的位置也跟著固定了, 如下:

而每個資料元素均可單獨取出使用.

請詳細參閱以下例子:

編寫及在瀏覽器執行以下 Perl 程式 :

#!/usr/bin/perl
print "Content-type: text/html\n\n";
#
### Set Scalar Array ########
#
@family=("Kong","Wai","Keung","Yau");
#
#
### Test Array #######
#
print "The members of this family are : @family";

Perl 程式解釋如下:

第 六 行 :

設定 @family 為一個單量陣列, 並有四個資料元素.

第 11 行 :

印出整個 @family 單量陣列內的資料元素.

瀏覽器應出現 :

The members of this family are : Kong Wai Keung Yau

實 例 View Example

接上例, 試試取出每個資料元素, 程式更改如下:

#!/usr/bin/perl
print "Content-type: text/html\n\n";
#
### Set Scalar Array ########
#
@family=("Kong","Wai","Keung","Yau");
#
#
### Test Array #######
#
print "The members of this family are : @family";
#
print "<P>";
#
### Test Elements #######
#
print "Name of member 1 is : $family[0]";
print "<BR>";
print "Name of member 2 is : $family[1]";
print "<BR>";
print "Name of member 3 is : $family[2]";
print "<BR>";
print "Name of member 4 is : $family[3]";

Perl 程式解釋如下:

@ 表示整個單量陣列 (如 @family), 而 $ 卻表示陣列內的每一個資料元素 (如 $family[0], $family[1], 等等).

第 17 行 :

印出 @family 單量陣列內的第一個資料元素, 即 $family[0].

第 19 行至 23 行印出 @family 單量陣列內的其他資料元素.

瀏覽器應出現 :

The members of this family are : Kong Wai Keung Yau

Name of member 1 is : Kong
Name of member 2 is : Wai
Name of member 3 is : Keung
Name of member 4 is : Yau

實 例 View Example

接上例, 因為 @family 單量陣列很細, 一看就知只有四個資料元素, 但當陣列的資料慢慢增加, 陣列變得很大的時候, 我們便需花一些時間來數數看才知道陣列有多少資料.

但非常幸運, Perl 提供一個方法, 使我們立刻知道陣列有多少資料. 看下例便明白了:

#!/usr/bin/perl
print "Content-type: text/html\n\n";
#
### Set Scalar Array ########
#
@family=("Kong","Wai","Keung","Yau");
#
#
### Test Array #######
#
print "The members of this family are : @family";
#
print "<P>";
#
### Test Elements #######
#
print "Name of member 1 is : $family[0]";
print "<BR>";
print "Name of member 2 is : $family[1]";
print "<BR>";
print "Name of member 3 is : $family[2]";
print "<BR>";
print "Name of member 4 is : $family[3]";
print "<P>";
#
### Count Total Elements in Array ###
#
print "There are ", scalar(@family), " members in this family";

Perl 程式解釋如下:

第 28 行 :

只需使用 scalar(@family) 便知道 @family 陣列內有多少資料元素.

執行程式後, 瀏覽器會印出 :

The members of this family are : Kong Wai Keung Yau

Name of member 1 is : Kong
Name of member 2 is : Wai
Name of member 3 is : Keung
Name of member 4 is : Yau

There are 4 members in this family

實 例 View Example