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

后端 未结 4 855
天涯浪人
天涯浪人 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:19

    The book "Perl Best Practices" recommends the use of return; instead of return undef; because the latter would return a one-element list in list context (the other answers already mention this). This would be a "nasty bug" according to the book.

    However, I think returning nothing can actually cause serious bugs (probably difficult to find), whereas calling a boolean function in list context seems rather simple to debug.

    So I always return something (that evaluates to) false in my boolean functions (usually 0 for false and 1 for true).
    (Yes, this would also return a one-element list in list context - so the comment in the book is technically right -, but then the actual error would be calling the boolean function in list context.)

    To be clear, I still recommend the book. It offers a lot of good advice.
    And I am referring to Chapter 9 (Subroutines), page 199/200 ("Use a bare return to return failure.") in the book "Perl Best Practices" by Damian Conway (O'Reilly Media, Inc.), ISBN 978-0-596-00173-5. Not sure if there's another/newer edition.

    Side note:
    Perl seems to return an empty string when negating something. my $foo = 5; return !$foo; returns q().

提交回复
热议问题