首页 > 解决方案 > 检查 sub 是否返回 undef

问题描述

人为的例子:

use strict;
use warnings;

my $myval = 'a';
my @result = my_sub($myval);
if (@result) {
        print "DEFINED\n";
}
my ($res1, $res2, $res3) = @result;
print "res1=$res1, res2=$res2, res3=$res3\n";
sub my_sub {
         my $myval = shift;
        if ($myval eq 'a') {
                return undef;
        }
        return ("a","b","c");
}

如何检查 sub 是否返回 undef?

或者

如何检查 sub 是否没有返回 undef?

标签: arrayslistperlundefined

解决方案


return undef在列表上下文中返回一个元素的列表,即undef.

 @result = my_sub($myval);
 if (@result == 1 && !defined($result[0])) {
     warn "my_sub() returned undef";
 } else {
     print "my_sub() returned data\n";
 }

也就是说,包含一个undef元素的列表几乎永远不是您想要的。请参阅如何从子例程中不返回任何内容?您通常只想不return带任何参数。在标量上下文中,它返回undef,而在列表上下文中,它返回一个空列表。

sub my_other_sub {
     my $myval = shift;
    if ($myval eq 'a') {
            return;
    }
    return ("a","b","c");
}
...
@result = my_other_sub($arg1);
$result = my_other_sub($arg2);
if (@result == 0) {     # or: if (!@result) ...  or: unless (@result) ...
    warn "my_other_sub(arg1) did not return any data";
} else {
    print "my_other_sub(arg1) returned data\n";
}
if (!defined($result)) {
    warn "my_other_sub(arg2) did not return any data";
} else {
    print "my_other_sub(arg2) returned data\n";
}

推荐阅读