The difference of "return;" and "return undef;"
"Perl Best Practices" recommends to use "return;"*1 to return nothing, but it might be wrong in some cases. If you use this idiom for those functions which are expected to return a scalar value, e.g. searching functions, the user of those functions will be surprised at what they return in list context, an empty list - note that many functions and all the methods evaluate their arguments in list context. You'd better to use "return undef;" for such scalar functions.
『Perlベストプラクティス』は名著だが,中には奨励できないプラクティスもある。「無効値を示すためには"return;"を使用せよ」というのもその一つだ。"return;"を使うと,そのサブルーチンはリストコンテキストでは空リストを返すのだが,下記のコードのように,スカラーを返すべきサブルーチンで空リストを返すと予想外の振る舞いをとることがある。このようなことを避けるため,スカラー値を返すべきサブルーチンでは,"return;"ではなく"return undef;"を使ったほうがよい。
sub search_something { my($arg) = @_; # search_something... if(defined $found){ return $found; } return; # XXX: you'd better to "return undef;" } # ... # you'll get what you want, but ... my $something = search_something($source); # you won't get what you want here. # @_ for doit() is (-foo => $opt), not (undef, -foo => $opt). $obj->doit(search_something($source), -option=> $optval); # you have to use the "scalar" operator in such a case. $obj->doit(scalar search_something($source), ...);
*1:it returns an empty list in list context, or returns undef in scalar context