[英]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 ) = @_;
然后$possible
是undefined ,這意味着將其設置為特殊值undef
,在其他語言中類似於NULL
, None
, nil
等。
如您所見,您不能在沒有引起警告消息的情況下比較未定義的值,並且必須首先使用已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
$possible //= "default_value"
如果沒有定義, $possible //= "default_value"
將有條件地賦值。 或者完全做其他事情。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.