perl中的shift和unshift使用
push和pop操作符处理的是数组的尾端,相似地,unshift和shift操作符则是对数组的开头进行相应的处理。SHIFT
$ITEM = shift(@ARRAY);Perl'sshift()functionis used to remove and return the first element from an array, which reduces the number of elements by one. Thefirstelementin the array is the one with the lowest index. It's easy to confuse this function withpop(),which removes thelastelementfrom an array.@myNames = ('Larry', 'Curly', 'Moe');
$oneName = shift(@myNames);If you think of an array as a row of numbered boxes, going from left to right, it would be the element on the far left. Theshift() function would cut the element off the left side of the array, return it, and reduce the elements by one. In the examples, the value of$oneNamebecomes'Larry',the first element, and @myNames is shortened to('Curly', 'Moe').The array can also be thought of as astack- picture of a stack of numbered boxes, starting with 0 on the top and increasing as it goes down. The shift() function would shift the element off the top of the stack, returnit, and reduce the size of the stack by one.
@myNames = ('Larry','Curly','Moe');
$oneName = shift(@myNames);UNSHIFT $TOTAL = unshift(@ARRAY, VALUES);
Perl'sunshift()functionis used to add a value or values onto the beginning of an array (prepend), which increases the number of elements. The new values then become thefirstelementsin the array. It returns the new total number of elements in the array. It's easy to confuse this functionwithpush(),which adds elements to theendofan array.
@myNames = ('Curly', 'Moe');
unshift(@myNames, 'Larry');Picture a row of numbered boxes, going from left to right. The unshift() function would add the new value or values on tothe left side of the array, and increase the elements. In the examples, the value of@myNamesbecomes('Larry','Curly', 'Moe').
The array can also be thought of as astack-picture of a stack of numbered boxes, starting with 0 on the top and increasing as it goes down. The unshift() function would add the value to the top of the stack, and increase the overall size of the stack.
@myNames = ('Curly','Moe');
unshift(@myNames, 'Larry');You can unshift() multiple values onto the array directly:@myNames = ('Moe', 'Shemp');
unshift(@myNames, ('Larry', 'Curly'));Or by unshift()-ing an array:@myNames = ('Moe', 'Shemp');
@moreNames = ('Larry', 'Curly');
unshift(@myNames, @moreNames); 转载自:http://perl.about.com/od/perltutorials/a/perlunshift.htm
页:
[1]