What's the difference between return; and return undef; in Perl

后端 未结 4 832
天涯浪人
天涯浪人 2020-12-09 15:55

Is there a difference between a subroutine that does

return;

and one that does?

return undef;
4条回答
  •  無奈伤痛
    2020-12-09 16:02

    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.

    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";
    }
    

    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";
    }
    

    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.

提交回复
热议问题