mje has asked for the wisdom of the Perl Monks concerning the following question:
perlcritic complains about the following code:
use strict; use warnings; use Data::Dumper; sub one { return undef; } sub two { my @a = @_; print Dumper(\@a); return; } two(1,2,one(), 3);
The complaint is "return" statement with explicit "undef" at line 5, near 'return undef;'. However, if you follow perlcritic advise and remove the "undef" to make the return just "return;", the program fails to work as can been seen from the following output, the first with the undef and the second without
$VAR1 = [1,2,undef,3]; $VAR1 = [1,2,3];
Is the perlcritic advice questionable? Is this worth reporting for Perl::Critic?
The full perlcritic description of the problem is:
"return" statement with explicit "undef" at line 5, near 'return undef;'. Subroutines::ProhibitExplicitReturnUndef (Severity: 5) Returning `undef' upon failure from a subroutine is pretty common. But if the subroutine is called in list context, an explicit `return undef;' statement will return a one-element list containing `(undef)'. Now if that list is subsequently put in a boolean context to test for failure, then it evaluates to true. But you probably wanted it to be false.
sub read_file { my $file = shift; -f $file || return undef; #file doesn't exist! #Continue reading file... } #and later... if ( my @data = read_file($filename) ){ # if $filename doesn't exist, # @data will be (undef), # but I'll still be in here! process(@data); } else{ # This is my error handling code. # I probably want to be in here # if $filname doesn't exist. die "$filename not found"; }
The solution is to just use a bare `return' statement whenever you want to return failure. In list context, Perl will then give you an empty list (which is false), and `undef' in scalar context (which is also false).
sub read_file { my $file = shift; -f $file || return; #DWIM! #Continue reading file... }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Question perlcritic ProhibitExplicitReturnUndef
by JavaFan (Canon) on Feb 06, 2009 at 10:30 UTC | |
|
Re: Question perlcritic ProhibitExplicitReturnUndef
by moritz (Cardinal) on Feb 06, 2009 at 10:29 UTC | |
by mje (Curate) on Feb 06, 2009 at 10:35 UTC | |
|
Re: Question perlcritic ProhibitExplicitReturnUndef
by Herkum (Parson) on Feb 06, 2009 at 14:58 UTC | |
|
Re: Question perlcritic ProhibitExplicitReturnUndef
by dsheroh (Monsignor) on Feb 06, 2009 at 15:59 UTC | |
by mje (Curate) on Feb 06, 2009 at 16:57 UTC | |
|
Re: Question perlcritic ProhibitExplicitReturnUndef
by Anonymous Monk on Feb 06, 2009 at 11:16 UTC |