Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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.

In list context, things are slightly more complicated. An empty list, when evaluated in a Boolean boolean condition, evaluates to false. But the value undef, when evaluated in list context, evaluates to true because it is converted to a list with the singleton value undef. Therefore, a function should not return undef if it might ever be invoked in list context.

...

Code Block
bgColor#ffcccc
langperl

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 class condition returns true, and the system incorrectly prints out the following:

Code Block

Your system has 0 users

Compliant Solution

...

Code Block
bgColor#ccccff
langperl

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.

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

EXP00-PL

low Low

unlikely Unlikely

low Low

P3

L1 L3

Automated Detection

Tool

Diagnostic

Perl::Critic

Subroutines::ProhibitExplicitReturnUndef

Bibliography

...

 

...

Image Added Image Added |http://search.cpan.org/~elliotjs/Perl-Critic-1.116/] [ProhibitOneArgSelect|http://search.cpan.org/dist/Perl-Critic/lib/Perl/Critic/Policy/Subroutines/ProhibitExplicitReturnUndef.pm] \[[Conway 2005|AA. Bibliography#Conway 2005]\], pg 19902. Expressions      02. Expressions      Image Modified