收益与收益之间有什么区别?并返回undef;在Perl [英] What's the difference between return; and return undef; in Perl

查看:76
本文介绍了收益与收益之间有什么区别?并返回undef;在Perl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

子程序之间有区别吗

return;

还有一个呢?

return undef;

推荐答案

return;将在列表上下文中返回空列表,而在标量上下文中返回undef.即使在列表上下文中,return undef;也将始终返回单个值undef.

return; will return an empty list in list context but undef in scalar context. return undef; will always return a single value undef even in list context.

通常,从列表上下文中通常使用的子例程中return undef;通常不是一个好主意:

In general, it's usually not a good idea to return undef; from a subroutine normally used in list context:

sub foo { return undef }
if ( my @x = foo() ) {
    print "oops, we think we got a result";
}

通常,从标量上下文中通常使用的子例程中return;通常不是一个好主意,因为它在列表上下文中的行为不如用户期望的那样:

In general, it's usually not a good idea to return; from a subroutine normally used in scalar context, because it won't behave as the user expects in list context:

sub foo { return }
%x = ( 'foo' => foo(), 'bar' => 'baz' );
if ( ! exists $x{'bar'} ) {
    print "oops, bar became a value, not a key";
}

这两种错误在实践中都会发生很多,后一种情况更是如此,这可能是因为期望返回标量的subs更常见.而且,如果期望返回标量,则最好返回标量.

Both of these errors happen quite a bit in practice, the latter more so, perhaps because subs that are expected to return a scalar are more common. And if it's expected to return a scalar, it had better return a scalar.

这篇关于收益与收益之间有什么区别?并返回undef;在Perl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆