Just another Perl shrine | |
PerlMonks |
Re: Return statement in subroutine(s) is necessary when not returning anything?by Anonymous Monk |
on Nov 02, 2015 at 22:56 UTC ( [id://1146769]=note: print w/replies, xml ) | Need Help?? |
There is nothing returning by the subroutine Yes, in your first example there is - it's the return value of the print, as per the piece of documentation you quoted ("If no return is found and if the last statement is an expression, its value is returned."). Note that Perl::Critic / PBP has this to say about the issue:
The example is a little contrived, but another argument I have read about implicit returns is this: If you don't specify an explicit return, the users of your module's API may get used to your sub returning a value, for example they may assume that like many Perl functions a true value indicates success, and if their code starts relying on that, they may be surprised when your code, which never intended to return any value, suddenly changes its behavior. Another viewpoint: An explicit return tells whomever is reading your code that yes, you did intend to return exactly that value. A common counter-argument is "but I know I'm only ever calling this sub in void context", which certainly can be true - until someone else starts working with your code :-) Having said all that, I've used the implicit return plenty of times, but usually only for brevity, as in when I'm writing a 1-to-3 line sub that I want to keep short. Otherwise I tend to agree with Perl::Critic that it's better to be explicit, and that includes return; for when I don't want my sub to return anything; I can always update the API later and add a useful return value.
In Section
Seekers of Perl Wisdom
|
|