...
Returning the value undef
is a common convention for a function to indicate it has no return value. This It is often used to indicate that an error occurred or that a function could not successfully complete an operation. When used as the conditional in a conditional expression (such as in an if
statement), undef
evaluates to false. Therefore, a function that is evaluated only in scalar context may safely return undef
to indicate failure.
...
Code Block | ||||
---|---|---|---|---|
| ||||
sub read_users {
open( my $filehandle, "<", "/etc/shadow")
or return undef;
my @users = <$filehandle>;
return @users;
}
# ...
if (my @users = read_users($filename)) {
print "Your system has $#users users\n";
# process users
} else {
croak "Cannot read shadow file";
}
|
The read_users()
subroutine returns undef
if it cannot open /etc/shadow
, but it returns a list of user data entries if it succeeds. Because its output is used in list context, a return value of undef
is converted to a list of a single element: (undef)
. Consequently, the if
condition returns true, and the system incorrectly prints out the following:
Code Block |
---|
Your system has 0 users
|
Compliant Solution
...
Code Block | ||||
---|---|---|---|---|
| ||||
sub read_users {
open( my $filehandle, "<", "/etc/shadow")
or return;
my @users = <$filehandle>;
return @users;
}
|
Exceptions
EXP00-PL-EX1: This recommendation applies specifically to functions called in a list context. If you can guarantee that some function will never be called in a list context, then that function may return undef
.
...
Tool | Diagnostic |
---|---|
Perl::Critic | Subroutines::ProhibitExplicitReturnUndef |
Bibliography
[Conway 2005] | "Returning Failure," p. 199 |
[CPAN] | Elliot Shank, Perl-Critic-1.116 ProhibitOneArgSelect |
---|
[Conway 2005] pg. 199
...