明輝手游網(wǎng)中心:是一個(gè)免費(fèi)提供流行視頻軟件教程、在線學(xué)習(xí)分享的學(xué)習(xí)平臺(tái)!

Perl教學(xué) 第4篇 下文與數(shù)組變量之二

[摘要]4、數(shù)組的輸出: (1) @array = (1, 2, 3);print (@array, "\n");結(jié)果為:123(2) @array = (1, 2, 3);print ("@array\n");結(jié)果為:1 2 35、列表/數(shù)組的長(zhǎng)度 當(dāng)數(shù)組變量出現(xiàn)...
4、數(shù)組的輸出:
(1) @array = (1, 2, 3);
print (@array, "\n");
結(jié)果為:
123
(2) @array = (1, 2, 3);
print ("@array\n");
結(jié)果為:
1 2 3
5、列表/數(shù)組的長(zhǎng)度
當(dāng)數(shù)組變量出現(xiàn)在預(yù)期簡(jiǎn)單變量出現(xiàn)的地方,則PERL解釋器取其長(zhǎng)度。
@array = (1, 2, 3);
$scalar = @array; # $scalar = 3,即@array的長(zhǎng)度
($scalar) = @array; # $scalar = 1,即@array第一個(gè)元素的值
注:以數(shù)組的長(zhǎng)度為循環(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í)最后一個(gè)字符--換行符。而如果它作用到數(shù)組上,則將數(shù)組中每一個(gè)元素都做如此處理。
@list = ("rabbit", "12345","quartz");
chop (@list); # @list = ("rabbi", "1234","quart") now
( 4)join/split--連接/拆分
join的第一個(gè)參數(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