...
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;
}
|
...
Tool | Diagnostic |
|---|---|
Perl::Critic | Subroutines::ProhibitExplicitReturnUndef |
Bibliography
...
| Chapter 9, "Subroutines," p. 199 |
...