$[ Perl 中的特殊變數


Perl 提供許多具有預定義含義的特殊變數。

我們有一個特殊變數,寫為 $[。此特殊變數是一個標量,包含所有陣列的第一個索引。由於 Perl 陣列基於零的索引,因此 $[ 幾乎總是 0。但是,如果您將 $[ 設定為 1,則所有陣列將使用基於一的索引。建議不要使用除零之外的任何其他索引。不過,我們舉一個示例來說明 $[ 變數的使用方式 −

示例

 即時演示

#!/usr/bin/perl
# define an array
@foods = qw(pizza steak chicken burgers);
print "Foods: @foods\n";
# Let's reset first index of all the arrays.
$[ = 1;
print "Food at \@foods[1]: $foods[1]\n";
print "Food at \@foods[2]: $foods[2]\n";

輸出

這將產生以下結果 −

Foods: pizza steak chicken burgers
Food at @foods[1]: pizza
Food at @foods[2]: steak

更新於:2019 年 11 月 29 日

299 次瀏覽

開啟您的職業生涯

透過完成課程獲得認證

快速入門
廣告
© . All rights reserved.