Friday, September 30, 2011

Perl -- Array

Array

1. 输入array

@array(1,2,3);
@array("one", "two", "three");
简单的array建立
@array = qw(red blue organ white);
qw相当于“”,

简单方法建立数字array
@numbers = (1..5); 这个相当于@numbers(1,2,3,4,5);


2. 从右边添加或减少

@array("one", "two", "three");
push(@array, "one"); 添加
结果("one", "two", "three", "one");

@array("one", "two", "three");
pop(@array); 减少
结果("one", "two");

@array("one", "two", "three");
如果是 $popresult = pop(@array);
$popresult是"three";

3. 从左边添加或减少

@array("one", "two", "three");
unshift(@array, "zero");
结果("zero", "one", "two", "three")

@array("one", "two", "three");
shift(@array);
结果("two", "three");


4. 合并array
@array1("one", "two", "three");
@array2("four", "five", "six");
@array3(@array1, @array2);
结果:@array3 is ("one", "two", "three", "four", "five", "six")

5. 反向排列reverse:
reverse(@array3);
结果: @array3 is ("six", "five", .....,"one");

6. 排序 sort
sort(@array);

sort{$a <=> $b)(@array);

7. 反向排序
sort{$b <=> $a}(@array);

$a and $b 变量是perl默认的排序的变量.
如果是string排序 <=> 换成 cmb

sort{$b cmb $a}(@array);

8. 输出100次array
@array = (1) x 100;
print @array;

9. count array number
$#array

No comments: