明辉手游网中心:是一个免费提供流行视频软件教程、在线学习分享的学习平台!

perl案例区分图文说明教程之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) .用于实数 (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)

.用于实数

(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);
其结果为:
Hello, Fred!
Hello, Fred!

4、数组的输出:

(1) @array = (1, 2, 3);
print (@array, "n");
结果为:
123
(2) @array = (1, 2, 3);
print ("@arrayn");
结果为:
1 2 3

5、列表/数组的长度

当数组变量出现在预期简单变量出现的地方,则PERL解释器取其长度。
@array = (1, 2, 3);
$scalar = @array; # $scalar = 3,即@array的长度
($scalar) = @array; # $scalar = 1,即@array第一个元素的值
注:以数组的长度为循环次数可如下编程:
$count = 1;
while ($count <= @array) {
print ("element $count: $array[$count-1]n");
$count++;
}

6、子数组

@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
可以用子数组形式来交换元素:
@array[1,2] = @array[2,1];

7、有关数组的库函数

(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--反转数组

@array2 = reverse(@array);
@array2 = reverse sort (@array);

(3)chop--数组去尾

chop的意义是去掉STDIN(键盘)输入字符串时最后一个字符--换行符。而如果它作用到数组上,则将数组中每一个元素都做如此处理。
@list = ("rabbit", "12345","quartz");
chop (@list); # @list = ("rabbi", "1234","quart") now

(4)join/split--连接/拆分

join的第一个参数是连接所用的中间字符,其余则为待连接的字符数组。
$string = join(" ", "this", "is","a", "string"); # 结果为"this is a string"
@list = ("words","and");
$string = join("::", @list, "colons"); #结果为"words::and::colons"
@array = split(/::/,$string); # @array = ("words","and", "colons") now