Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1814632
  • 博文数量: 438
  • 博客积分: 9799
  • 博客等级: 中将
  • 技术积分: 6092
  • 用 户 组: 普通用户
  • 注册时间: 2012-03-25 17:25
文章分类

全部博文(438)

文章存档

2019年(1)

2013年(8)

2012年(429)

分类: Python/Ruby

2012-03-26 09:24:38

多个变量可以用圆括号组合成列表,并可以赋给数组变量。数组变量用@varname表示。下面是数组的一些基本操作:



  1. @array = (32, "hello", 82.1);

  2. $value = @array[0]; # 32
  3. @array[2] = 12.8; # 32 hello 12.8
  4. $value = @array[4]; # null
  5. @array[5] = "ok"; # 32 hello 12.8 "" ok

  6. @array_copy = @array;
  7. @array_new = (1, @array, 5); # 1 32 hello 12.8 "" ok 5


列表和数组之间可以相互赋值:



  1. @array = (1, 2, 3);
  2. ($var1, $var2) = @array; # $var1=1, $var2=2
  3. ($var1, $var2, $var3, $var4) = @array; # $var4=null
  4. ($var1, @array2) = @array; #$var1=1, @array2=(2,3)
  5. (@array1, $var2) = @array; #@array1=(1,2,3), $var2=null


字符串中的数组变量:

  1. @array = (1, 2, 3);
  2. $array = "a";
  3. print "@array[0]\n"; # 1
  4. print "\@array[0]\n"; # @array[0]
  5. print "$array[0]\n"; # 1
  6. print "$array\[0]\n"; # a[0] 等价于$array . "[0]"
  7. print "${array}[0]\n"; # a[0] 等价于$array . "[0]"
  8. print "$\{array}[0]\n"; # 输出两个空行。

 

列表范围


  1. (1..10) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
  2.     (2, 5..7, 11) = (2, 5, 6, 7, 11)
  3.     (3..3) = (3)
  4.     (2.1..5.3) = (2.1, 3.1 ,4.1, 5.1)
  5.     (4.5..1.6) = ()
  6.     ("aaa".."aad") =("aaa","aab", "aac","aad")
  7.     @day_of_month =("01".."31")


可包含变量或表达式

  1. ($var1..$var2+5)


数组的长度

   

  1. $length = @array; 或 $length = scalar(@array)

子数组


  1. @array = (1, 2, 3, 4, 5);
  2. @sub_array = @array[1,2,4]; # (2, 3, 5)
  3. @array[2..4] = ("x", "y", "z"); # (1, 2, "x", "y", "z")
  4. @array[1, 0] = @array[4,3]; # ("y", "z", "x", "y", "z")

数组函数
sort用来(以字母序)排序,reverse用来反转数组,chop用来清除数组内所有元素字符串的最后一个字符,join用来把数组连接为字符串,split用来把字符串拆分为数组:


  1. @array = ("ax", "zb", "ac", "xhh", "dxy");
  2. @array2 = sort @array; # ("ac" "ax" "dxy" "xhh" "zb")
  3. @array2 = reverse @array; # (dxy xhh ac zb ax)
  4. @array2 = reverse sort @array; # (zb xhh dxy ax ac)

  5. @array = (83, 76, 102, 908);
  6. @array2 = sort @array; # (102 76 83 908) 按字母序排序

  7. @array = ("abc", "def", 123, 456, 7.89);
  8. chop @array; # (ab de 12 45 7,8)

  9. $string = join(" ", "joined", "by", "space"); # joined by space
  10. $string = join("-", "joined", "by", "hyphen"); # joined-by-hyphen
  11. @array = ("two", "three");
  12. $string = join("::", "one", @array, "four"); # one::two::three::four

  13. @array = split(/~/, "1~2~3~4"); # 1 2 3 4

阅读(552) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~