perl案例區(qū)分圖文說明教程之6
發(fā)表時間:2024-06-10 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]3、列表范圍: (1..10) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) (2, 5..7, 11) = (2, 5, 6, 7, 11) (3..3) = (3) .用于實數(shù) (2.1..5.3) = (2.1, 3.1 ,4.1, 5.1) (4.5..1.6) = ...
3、列表范圍:
(1..10) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
(2, 5..7, 11) = (2, 5, 6, 7, 11)
(3..3) = (3)
.用于實數(shù)
(2.1..5.3) = (2.1, 3.1 ,4.1, 5.1)
(4.5..1.6) = ()
.用于字符串
("aaa".."aad") = ("aaa","aab", "aac", "aad")
@day_of_month = ("01".."31")
.可包含變量或表達式
($var1..$var2+5)
.小技巧:
$fred = "Fred";
print (("Hello, " . $fred . "!n") x 2);
其結(jié)果為:
Hello, Fred!
Hello, Fred!
4、數(shù)組的輸出:
(1) @array = (1, 2, 3);
print (@array, "n");
結(jié)果為:
123
(2) @array = (1, 2, 3);
print ("@arrayn");
結(jié)果為:
1 2 3
5、列表/數(shù)組的長度
當數(shù)組變量出現(xiàn)在預(yù)期簡單變量出現(xiàn)的地方,則PERL解釋器取其長度。
@array = (1, 2, 3);
$scalar = @array; # $scalar = 3,即@array的長度
($scalar) = @array; # $scalar = 1,即@array第一個元素的值
注:以數(shù)組的長度為循環(huán)次數(shù)可如下編程:
$count = 1;
while ($count <= @array) {
print ("element $count: $array[$count-1]n");
$count++;
}
6、子數(shù)組
@array = (1, 2, 3, 4, 5);
@subarray = @array[0,1]; # @subarray = (1, 2)
@subarray2 = @array[1..3]; # @subarray2 = (2,3,4)
@array[0,1] = ("string", 46); # @array =("string",46,3,4,5) now
@array[0..3] = (11, 22, 33, 44); # @array = (11,22,33,44,5) now
@array[1,2,3] = @array[3,2,4]; # @array = (11,44,33,5,5) now
@array[0..2] = @array[3,4]; # @array = (5,5,"",5,5) now
可以用子數(shù)組形式來交換元素:
@array[1,2] = @array[2,1];
7、有關(guān)數(shù)組的庫函數(shù)
(1)sort--按字符順序排序
@array = ("this", "is", "a","test");
@array2 = sort(@array); # @array2 = ("a","is", "test", "this")
@array = (70, 100, 8);
@array = sort(@array); # @array = (100, 70, 8) now
(2)reverse--反轉(zhuǎn)數(shù)組
@array2 = reverse(@array);
@array2 = reverse sort (@array);
(3)chop--數(shù)組去尾
chop的意義是去掉STDIN(鍵盤)輸入字符串時最后一個字符--換行符。而如果它作用到數(shù)組上,則將數(shù)組中每一個元素都做如此處理。
@list = ("rabbit", "12345","quartz");
chop (@list); # @list = ("rabbi", "1234","quart") now
(4)join/split--連接/拆分
join的第一個參數(shù)是連接所用的中間字符,其余則為待連接的字符數(shù)組。
$string = join(" ", "this", "is","a", "string"); # 結(jié)果為"this is a string"
@list = ("words","and");
$string = join("::", @list, "colons"); #結(jié)果為"words::and::colons"
@array = split(/::/,$string); # @array = ("words","and", "colons") now