When to use defined

前端 未结 3 943
礼貌的吻别
礼貌的吻别 2021-01-14 19:11

I am a little confused as which way to test parameters. Here are two examples from source code posted below. First is this

if(!defined($DBHdl) || !defined($ac

3条回答
  •  有刺的猬
    2021-01-14 19:32

    Well , in perl script language, defined($a) is just a sub routine to test if $a is "undef",nothing else. So ,you will ask ,what is undef?

    To be accurate, it is a perl subroutine ,the same as defined.But when it has no parameter, it can be considered as a perl-special scalar . For example , when you pop a value from an empty array ,it will return an undef.When you call subroutine "undef $b",then $b will become undef($b must be an left value),nothing else. Only in this case, defined($b) will return false.But if $c is an empty string like "" ,number zero ,or string "0" ,defined($c) will still return true;

    But if you use a simple boolean expression instead of defined,it becomes totally different. A simple Boolean test will not distinguish among undef, zero, the empty string, and "0" .So , it absolutely depends on your pratical requirement when determining using defined() or just a boolean test.

提交回复
热议问题