When to use defined

前端 未结 3 944
礼貌的吻别
礼貌的吻别 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:27

    $sth->fetchrow_hashref will either return undef or a reference to a hash. As such

    if (defined($row))
    

    and

    if ($row)
    

    are equivalent here. (undef is false, and reference is always true.) I opt for the simpler alternative.

    Same idea for $dbh->prepare.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-14 19:36

    In the case of the code you posted, I would also do as ikegami said, and use the shorter form.

    There are occasions when that isn't suitable, however, for example if a variable could have a legitimate value that would be treated as false if simply used in a true/false test. For example:

    my $value = 0;
    print "defined\n" if defined $value;  # prints 'defined'
    print "true\n" if $value;  # does not print anything
    
    0 讨论(0)
提交回复
热议问题