The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Perl::Critic::Policy::Subroutines::RequireFinalReturn

DESCRIPTION

Require all subroutines to terminate with a return (or a goto).

Subroutines without explicit return statements at their ends can be confusing. It can be challenging to deduce what the return value will be.

Furthermore, if the programmer did not mean for there to be a significant return value, and omits a return statement, some of the subroutine's inner data can leak to the outside. Consider this case:

   package Password;
   # every time the user guesses the password wrong, it's value
   # is rotated by one character
   my $password;
   sub set_password {
      $password = shift;
   }
   sub check_password {
      my $guess = shift;
      if ($guess eq $password) {
         unlock_secrets();
      } else {
         $password = (substr $password, 1).(substr $password, 0, 1);
      }
   }
   1;

In this case, the last statement in check_password() is the assignment. The result of that assignment is the implicit return value, so a wrong guess returns the right password! Adding a return; at the end of that subroutine solves the problem.

The only exception allowed is an empty subroutine.

LIMITATIONS

We do not look for returns inside ternary operators. That construction is too complicated to analyze right now. Besides, a better form is the return outside of the ternary like this: return foo ? 1 : bar ? 2 : 3

Also, this policy doesn't allow you to terminate a subroutine with die, exit, croak, or confess. We'll try and fix that in the future.

AUTHOR

Chris Dolan <cdolan@cpan.org>

COPYRIGHT

Copyright (c) 2005-2006 Chris Dolan. All rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. The full text of this license can be found in the LICENSE file included with this module.