多个变量可以用圆括号组合成列表,并可以赋给数组变量。数组变量用@varname表示。下面是数组的一些基本操作:
- @array = (32, "hello", 82.1);
- $value = @array[0]; # 32
- @array[2] = 12.8; # 32 hello 12.8
- $value = @array[4]; # null
- @array[5] = "ok"; # 32 hello 12.8 "" ok
- @array_copy = @array;
- @array_new = (1, @array, 5); # 1 32 hello 12.8 "" ok 5
列表和数组之间可以相互赋值:
- @array = (1, 2, 3);
- ($var1, $var2) = @array; # $var1=1, $var2=2
- ($var1, $var2, $var3, $var4) = @array; # $var4=null
- ($var1, @array2) = @array; #$var1=1, @array2=(2,3)
- (@array1, $var2) = @array; #@array1=(1,2,3), $var2=null
字符串中的数组变量:
- @array = (1, 2, 3);
- $array = "a";
- print "@array[0]\n"; # 1
- print "\@array[0]\n"; # @array[0]
- print "$array[0]\n"; # 1
- print "$array\[0]\n"; # a[0] 等价于$array . "[0]"
- print "${array}[0]\n"; # a[0] 等价于$array . "[0]"
- print "$\{array}[0]\n"; # 输出两个空行。
列表范围:
- (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")
可包含变量或表达式
数组的长度:
- $length = @array; 或 $length = scalar(@array)
子数组:
- @array = (1, 2, 3, 4, 5);
- @sub_array = @array[1,2,4]; # (2, 3, 5)
- @array[2..4] = ("x", "y", "z"); # (1, 2, "x", "y", "z")
- @array[1, 0] = @array[4,3]; # ("y", "z", "x", "y", "z")
数组函数:
sort用来(以字母序)排序,reverse用来反转数组,chop用来清除数组内所有元素字符串的最后一个字符,join用来把数组连接为字符串,split用来把字符串拆分为数组:
- @array = ("ax", "zb", "ac", "xhh", "dxy");
- @array2 = sort @array; # ("ac" "ax" "dxy" "xhh" "zb")
- @array2 = reverse @array; # (dxy xhh ac zb ax)
- @array2 = reverse sort @array; # (zb xhh dxy ax ac)
- @array = (83, 76, 102, 908);
- @array2 = sort @array; # (102 76 83 908) 按字母序排序
- @array = ("abc", "def", 123, 456, 7.89);
- chop @array; # (ab de 12 45 7,8)
- $string = join(" ", "joined", "by", "space"); # joined by space
- $string = join("-", "joined", "by", "hyphen"); # joined-by-hyphen
- @array = ("two", "three");
- $string = join("::", "one", @array, "four"); # one::two::three::four
- @array = split(/~/, "1~2~3~4"); # 1 2 3 4
阅读(548) | 评论(0) | 转发(0) |