在 Perl 陣列中新增和刪除元素
Perl 提供了大量有用的函式,以便在陣列中新增和刪除元素。你可能有一個問題,函式是什麼?到目前為止,你已經使用過 print 函式來列印不同值。類似地,還有不同的函式或有時稱為子例程,可用於其他不同功能。
| 序號 | 型別及描述 |
|---|---|
| 1 | push @ARRAY, LIST 將列表的值推送到陣列結尾。 |
| 2 | pop @ARRAY 彈出發出並返回陣列的最後一個值。 |
| 3 | shift @ARRAY 移出陣列的第一個值並返回它,使得陣列縮短 1,其他值向下移動。 |
| 4 | unshift @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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP