|
push 和 pop 两个操作符处理数组的尾端,而 shift 与 unshift 则处理数组的开头。
下面代码演示这种情况:
[code=perl]#!/usr/bin/perl
@array = qw/welcome to groad net/;
$var = shift(@array);
$val = shift(@array);
print "$var $val \n";
shift(@array);
#到这里数组里只剩下一个元素
foreach (@array) {
print "$_ ";
}
print "\n";
#为数组添加元素(复原原来的内容)
unshift(@array, groad);
unshift(@array, to);
unshift(@array, welcome);
foreach (@array) {
print "$_ ";
}
print "\n";[/mw_shl_code]
运行输出:./shift.pl
welcome to
net
welcome to groad net 如果数组为空时再用 shift 那么返回的是 undef 。
另外,shift 还常用在函数参数的移位上,比如下面的代码:
[code=perl]#!/usr/bin/perl
sub test {
local($firstname) = shift;
print "$firstname\n";
local($secname) = shift;
print "$secname\n";
}
&test("groad", "beyes");[/mw_shl_code]
运行输出: |
|