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

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

Is there a difference between a subroutine that does

return;

and one that does?

return undef;
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 16:22

    Given

    sub foo { return; }
    sub bar { return undef; }
    

    In scalar context, they behave the same.

    my $foo = foo();   # $foo is undef
    my $bar = bar();   # $bar is undef
    

    In list context, they behave differently

    my @foo = foo();   # @foo is ()  (an empty list)
    my @bar = bar();   # @bar is ( undef )  (a one-element list)
    

    Note that a one-element list is a true value in boolean context, even though the only element is undef.

    In general, it's usually not a good idea to return undef; from a subroutine, because of how it behaves in context.

提交回复
热议问题