Scroll to navigation

Perl::Critic::Policy::Community::EmptyReturn(3pm) User Contributed Perl Documentation Perl::Critic::Policy::Community::EmptyReturn(3pm)

NAME

Perl::Critic::Policy::Community::EmptyReturn - Don't use return with no arguments

DESCRIPTION

Context-sensitive functions, while one way to write functions that DWIM (Do What I Mean), tend to instead lead to unexpected behavior when the function is accidentally used in a different context, especially if the function's behavior changes significantly based on context. This also can lead to vulnerabilities when a function is intended to be used as a scalar, but is used in a list, such as a hash constructor or function parameter list. "return" with no arguments will return either "undef" or an empty list depending on context. Instead, return the appropriate value explicitly.

  return;       # not ok
  return ();    # ok
  return undef; # ok
  sub get_stuff {
    return unless @things;
    return join(' ', @things);
  }
  my %stuff = (
    one => 1,
    two => get_stuff(), # oops! function returns empty list if @things is empty
    three => 3,
  );

Empty returns are permitted by this policy if the subroutine contains no explicit return values, indicating it is intended to be used in void context.

CAVEATS

This policy currently only checks return statements in named subroutines, anonymous subroutines are not checked. Also, return statements within blocks, other than compound statements like "if" and "foreach", are not considered when determining if a function is intended to be used in void context.

Any non-empty return will cause empty returns within the same subroutine to report violations, even though in list context, "return" and "return ()" are functionally equivalent. It is recommended to explicitly specify an empty list return with "return ()" in a function that intends to return list context.

AFFILIATION

This policy is part of Perl::Critic::Community.

CONFIGURATION

This policy is not configurable except for the standard options.

AUTHOR

Dan Book, "dbook@cpan.org"

COPYRIGHT AND LICENSE

Copyright 2015, Dan Book.

This library is free software; you may redistribute it and/or modify it under the terms of the Artistic License version 2.0.

SEE ALSO

Perl::Critic

2022-07-25 perl v5.38.2