以下Function Compute某年份是否為閏年
#!/usr/bin/perl
$my_year = 2000;
if ( is_leap_year( $my_year ) )
{ # Call function with an argument
print "$my_year is a leap year\n";
}
else
{
print "$my_year is not a leap year";
}
sub is_leap_year { # Function definition
my $year = shift(@_); # Shift off the year from
# the parameter list, @_
return ((($year % 4 == 0) &;& ($year % 100 != 0)) ||
($year % 400 == 0)) ? 1 : 0; # What is returned from the function
}
上例中my $year = 2000; 此代碼中有一個關鍵字shift,給出相關解釋。
在閱讀別人別人的perll代碼的時候經常發現在頭部都是 ”
$變數=shift;”
首先我們查下看下perldoc中對於shift()的解釋
perldoc -f shiftshift ARRAYshift Shifts the first value of the array off and returns it, shortening the array by 1 and moving everything down. If there are no elements in the array, returns the undefined value. If ARRAY is omitted, shifts the @_ array within the lexical scope of subroutines and formats, and the @ARGV array outside a subroutine and also within the lexical scopes established by the "eval STRING", "BEGIN {}", "INIT {}", "CHECK {}", "UNITCHECK {}" and "END {}" constructs. See also "unshift", "push", and "pop". "shift" and "unshift" do the same thing to the left end of an array that "pop" and "push" do to the right end.
shift off(可以理解為移除)數組中第一個變數並返回
perl中預設如果不指明參數那麼就根據上下文擷取預設參數
所以當我們定義這樣一個pl檔案
1.pl$host = shift;
那麼顯然shift操作的參數為@_ 也就是 @ARGV
這句實現了直接擷取使用者傳遞的第一個參數。
總之就是shift沒有數組作為參數時,就是移動@_這個預設的參數。
perl裡經常用這種預設方法的。