分類: Perl

精簡扼要的 Perl 課程講義(二):雜湊(Hash)與運算子

雜湊(Hash)

# 雜湊 (hash)

%hash1 = ("Bill", "boy", "Mary", "gril");
print $hash1{"Bill"};   # "boy"

%hash2 = ("Bill" => "boy","Mary" => "gril");    # The same

# %hash2 現在是 ("Bill" => "boy","Mary" => "gril","Joe" => "boy")
$hash2{"Joe"} = "boy";

%hash3 = ("Joe" => "man");

# 合併 %hash2 與 %hash3,有重複的元素,會以最後一個為準
%hash2 = (%hash2,%hash3);

keys %hash1;    # 傳回一陣列,內容為 %hash1 的 key

values %hash1;  # 傳回一陣列,內容為 %hash1 的 value

delete $hash1{"Bill"};  # 刪除元素


# exists 可測試元素是否存在
if(exists $hash1{"Bill"}) {
    print "exists";
}

運算子

# 運算子

# Arithmetic
#   +   addition
#   -   subtraction
#   *   multiplication
#   /   division
#   **  exponentiation

$val = 2**3;    # $val = 8

# Numeric comparison
#   ==  equality
#   !=  inequality
#   <   less than
#   >   greater than
#   <=  less than or equal
#   >=  greater than or equal
# String comparison
#   eq  equality
#   ne  inequality
#   lt  less than
#   gt  greater than
#   le  less than or equal
#   ge  greater than or equal

"abc" lt "bcd";     # true

# Boolean logic
#   &&  and
#   ||  or
#   !   not
# Miscellaneous
#   =   assignment
#   .   string concatenation
#   x   string multiplication
#   ..  range operator (creates a list of numbers)

@arr = 1 .. 5;          # @arr = (1,2,3,4,5);
$str = "Bill" x 3;      # $str = "BillBillBill";

# Many operators can be combined with a "=" as follows:
#   $a += 1;    same as $a = $a + 1
#   $a -= 1;    same as $a = $a - 1
#   $a .= "\n"; same as $a = $a . "\n";

# 註:其他運算子請參考 perlop(1)

繼續閱讀:Perl 程式設計教學

G. T. Wang

個人使用 Linux 經驗長達十餘年,樂於分享各種自由軟體技術與實作文章。

Share
Published by
G. T. Wang

Recent Posts

光陽 KYMCO GP 125 機車接電發動、更換電瓶記錄

本篇記錄我的光陽 KYMCO ...

2 年 ago

[開箱] YubiKey 5C NFC 實體金鑰

本篇是 YubiKey 5C ...

3 年 ago

[DIY] 自製竹火把

本篇記錄我拿竹子加上過期的苦茶...

3 年 ago