將一個或多個元素新增到陣列的開頭。這與 shift
相反。
my @animals = ("cat");
unshift(@animals, "mouse"); # ("mouse", "cat")
my @colors = ("red");
unshift(@colors, ("blue", "green")); # ("blue", "green", "red")
傳回更新後陣列的新元素數。
# Return value is the number of items in the updated array
my $color_count = unshift(@colors, ("yellow", "purple"));
say "There are $color_count colors in the updated array";
請注意,LIST 會整體插入,而不是一次一個元素,因此插入的元素會保持相同的順序。請使用 reverse
執行相反的動作。
從 Perl 5.14 開始,一個實驗性功能允許 unshift
採用標量表達式。此實驗已被視為不成功,並從 Perl 5.24 中移除。