On Jan 13, 2011 2:24 AM, "Uri Guttman" <u...@stemsystems.com> wrote: > > >>>>> "sw" == shawn wilson <ag4ve...@gmail.com> writes: > > >> subs in perl ALWAYS return something, either the value from return or > >> the last evaluated expression. > > sw> What do you mean by this? > > sw> sub nothing { > sw> my $something = 5; > sw> if ( $something == 5) {} > sw> } > > sw> ... will return 'undef' and not 5 or anything else, right? > > from perldoc perlsub: > > A "return" statement may be used to exit a subroutine, optionally > specifying the returned value, which will be evaluated in the > appropriate context (list, scalar, or void) depending on the context of > the subroutine call. If you specify no return value, the subroutine > returns an empty list in list context, the undefined value in scalar > context, or nothing in void context. If you return one or more > aggregates (arrays and hashes), these will be flattened together into > one large indistinguishable list. > > If no "return" is found and if the last statement is an expression, its > value is returned. If the last statement is a loop control structure > like a "foreach" or a "while", the returned value is unspecified. The > empty sub returns the empty list. > > i never said subs return something useful but something is always > available to the caller on the stack. this is one (of many) reasons i > say to (almost) always use explicit returns. it guarantees you know what > you are returning, it tells the reader what is being returned and it > avoids bugs. one classic bug is some code that returns the last > expression and someone adds code after that breaking the return. another > bug is when the last statement is some compound thing like if/else and > it may return the right thing but it is hard to tell what is going > on. and as the docs say a loop control will be unspecified in what it > returns. so use explicit return statements to avoid all of these > issues. simple and important. > > there are some special cases where no return statement may be better. i > won't go into those now. >
I dig what you're saying about always using return. However I don't (have never used / seen) a case where a sub returns last expression. An example maybe?