2013-12-20 232 views
1

我在Perl新手,我在另一頁我打電話的是頁面定義的函數函數調用如果第二個參數爲空,第三個參數爲第二個參數?

sub ex_arg($_) 
{ 
    print "$_[0]\n"; 
    print "$_[1]\n"; 
    print "$_[2]\n"; 
} 
1; 

require "ex_arg.pl"; 
ex_arg(1,2,3); 
ex_arg(1,,3); #in the second function i want the second parameter to be null 
1; 

是否可以這樣做。我沒有得到第二個參數,而是第三個參數作爲第二個參數。

我做錯了什麼。請糾正我。

在此先感謝。

回答

8

問題是,在將參數列表傳遞給子例程之前,您的參數列表不會爲第二個參數保留一個空值。列表1,,3將擴展到與1,3相同的列表。

您需要傳遞一些實際存在的值,例如undef或空字符串。

ex_arg(1, undef, 3); 

那麼也許像

sub ex_arg { 
    my ($arg1, $arg2, $arg3) = @_; 
    if (! defined($arg2)) {   # checking if arg2 is empty 
     # do something 
    } 
} 

在一個相關的說明,您應該不會,除非你知道它的使用在你的子程序中聲明原型。它們用於在子例程中創建特定的行爲,並且與其他語言的工作方式無關,就子例程中的變量而言。

sub foo (...) { 
     #^^^^^^^----- prototypes 

sub foo {  # this is the standard way to declare 
+0

非常感謝您的信息。 –

+0

不客氣。 – TLP

5

試試這個,

ex_arg(1, undef, 3); 

ex_arg(1, , 3) Perl的是同樣的事情ex_arg(1, 3)

​​

旁註;如果你不想使用prototypes那麼sub ex_arg {..}就是你想要的。

優選my ($x,$y) = @_;優於$_[0]$_[1]

相關問題