雜湊(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 程式設計教學