($fred, $barney, $dino) = ("fiintstone", "rubble", "undef");
($fred, $barney) = ($barney, $fred); #互换两者的值
($betty[0], $betty[1] = ($betty[1], $betty[0]);
pop和push操作
pop操作符可用来去除数组中最后一个元素,同时返回该元素值
@array = 5..9;
$fred = pop(@array); #fred变成9,@array现在是(5, 6, 7, 8)
$barney = pop(@array); #$barney变成8,@array现在是(5, 6, 7)
pop @array; #@array现在是(5, 6),7被抛弃了
push (@array, 0); #@array现在是(5, 6, 0)
push @array, 8; #@array现在是(5, 6, 0,8)
push @array, 1..10; #@array得到了10个新元素
@others = qw/ 9 0 2 1 0 /;
push @array, @others; #@array又得到了5个新元素 (共19个)
shift和unshift操作符
unshift和shift操作符则是对数组的"开头"操作,也就是最数组的左边操作
@array = qw# dino fred barney #;
$m = shift(@array); #$m变成"dino", @array现在是("fred", "barney")
$n = shift(@array); #$n变成"fred", @array现在是("barney")
shift @array; #现在@array变空了
$o = shift @array; #$o变成undef,@array还是空的
unshift (@array, 5); #@array现在仅包含一个元素的列表
unshift @array, 4; #@array现在是(4, 5)
@others = 1..3; #
unshift @array, @others; #array又变成了(1, 2, 3, 4, 5)
foreach控制结构
对整个数组或者列表进行处理,将是很方便的
foreach $rock (qw / bedrock slate lava/){
print "One rock is $rock.\n";
}
[root@db2 home]# ./each.pl
One rock is bedrock.
One rock is slate.
One rock is lava.
[root@db2 home]# cat each.pl
#!/usr/bin/perl
foreach $rock (qw / bedrock slate lava/){
print "One rock is $rock.\n"
}
$_操作符
[root@db2 home]# ./foreach.pl
I can count to 1!
I can count to 2!
I can count to 3!
I can count to 4!
I can count to 5!
I can count to 6!
I can count to 7!
I can count to 8!
I can count to 9!
I can count to 10!
[root@db2 home]# cat foreach.pl
#!/usr/bin/perl
foreach (1..10){
print "I can count to $_!\n";
}
当未告知Perl使用哪个变量或者数组的时候,Perl都会自动使用$_,print在没有参数时,会打印$_的值
[root@db2 home]# ./foreach.pl
Yamaidie
[root@db2 home]# cat foreach.pl
#!/usr/bin/perl
$_ = "Yamaidie\n";
print;
reverse操作符
@fred = 6..10;
@barney = reverse{@fred}; #得10, 9, 8, 7, 6
@wilma = reverse 6..10; #同上,但不需要额外的数组
@fred = reverse @fred; #将逆序的结果放回原来哪个数组
sort 操作符
@rocks =qw/ bedrock slate rubble granite /;
@sorted = sort (@rocks); #得bedrock, granite, rubble,slate
@back = reverse sort @rocks; #逆序后从slate到bedrock排序
@rocks = sort @rocks; #将排序后的结果存辉至@rocks
@numbers = sort 97..102 #得100, 101, 102, 97, 98, 99
阅读(1623) | 评论(0) | 转发(0) |