在 Perl 陣列中新增和刪除元素


Perl 提供了大量有用的函式,以便在陣列中新增和刪除元素。你可能有一個問題,函式是什麼?到目前為止,你已經使用過 print 函式來列印不同值。類似地,還有不同的函式或有時稱為子例程,可用於其他不同功能。

序號型別及描述
1push @ARRAY, LIST
將列表的值推送到陣列結尾。
2pop @ARRAY
彈出發出並返回陣列的最後一個值。
3shift @ARRAY
移出陣列的第一個值並返回它,使得陣列縮短 1,其他值向下移動。
4unshift @ARRAY, LIST
在前置列表中新增陣列,並返回新陣列中的元素數量。

示例

 演示

#!/usr/bin/perl
# create a simple array
@coins = ("Quarter","Dime","Nickel");
print "1. \@coins = @coins\n";

# add one element at the end of the array
push(@coins, "Penny");
print "2. \@coins = @coins\n";

# add one element at the beginning of the array
unshift(@coins, "Dollar");
print "3. \@coins = @coins\n";

# remove one element from the last of the array.
pop(@coins);
print "4. \@coins = @coins\n";

# remove one element from the beginning of the array.
shift(@coins);
print "5. \@coins = @coins\n";

輸出

將產生以下結果 −

1. @coins = Quarter Dime Nickel
2. @coins = Quarter Dime Nickel Penny
3. @coins = Dollar Quarter Dime Nickel Penny
4. @coins = Dollar Quarter Dime Nickel
5. @coins = Quarter Dime Nickel

更新時間:2019 年 11 月 28 日

2K+ 瀏覽量

開啟你的 職業

完成課程並獲得認證

開始
廣告