perl學習(1)子函數

來源:互聯網
上載者:User

以下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裡經常用這種預設方法的。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.