arrays - 检查 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?
解决方案
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";
}
推荐阅读
- highcharts - Highcharts - 工具提示渲染性能下降
- javascript - jsPDF围绕自己的中心旋转图像
- objective-c - 为什么发布版本比调试更严格
- java - 局部变量未初始化
- amazon-cloudformation - Terraform 资源弹性负载均衡器 - 减少 ConnectionDrainingPolicy 超时
- excel - 优秀团队出勤率
- html - 同步融合时间表角度组件的动态视图
- vue.js - 进行简单的重新分配后数据属性不再反应?
- javascript - jQuery上一个按钮没有按预期工作
- arrays - VBA - 按数组中的文本值过滤,确定过滤器是否返回空白值,将非空白行复制到另一个命名表;环形