簡體   English   中英

Perl,將數組傳遞給子例程,處理未聲明的變量

[英]Perl, passing array into subroutine, dealing with undeclared variables

我有一個帶有一些確定變量的子程序,並且我在子程序中聲明和使用了這些變量,但是當我調用此子程序時,無法聲明它們。

例如:

sub func{
my ($firm1, $firm2, $possible) = @_;
...
if($possible eq "smth"){ # in case i passed this scalar
}
elsif($possible eq ("smth else" or undef/i_don_t_know)){ # in case i didn't passed this var, but i need it as at least undef or smth like that
}

func(bla, bla, bla); # ok
func(bla, bla); # not ok

當我嘗試時,出現錯誤

“在test.pl行的字符串eq中使用未初始化的值$ possible ...”

我該如何糾正?

這不是聲明的問題。 如果您僅將兩個參數傳遞給以開頭的子例程

    my ( $firm1, $firm2, $possible ) = @_;

然后$possibleundefined ,這意味着將其設置為特殊值undef ,在其他語言中類似於NULLNonenil等。

如您所見,您不能在沒有引起警告消息的情況下比較未定義的值,並且必須首先使用已defined運算符來檢查是否已定義變量

認為您想測試$possible是否已定義並設置為字符串smth 你可以這樣

sub func {

    my ( $firm1, $firm2, $possible ) = @_;

    if ( defined $possible and $possible eq 'smth' ) {

        # Do something
    }
}

func( qw/ bla bla bla / );    # ok
func( qw/ bla bla / );        # now also ok

聲明不是問題,而是傳遞未定義的值。

有幾種處理方法:

  • 測試變量上的defined
  • 設置一個'default' $possible //= "default_value"如果沒有定義, $possible //= "default_value"將有條件地賦值。

或者完全做其他事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM