[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: expressions vs. statements



kragen@pobox.com writes:

[...]

> The particular problem I brought up, which Pixel corroborated, is that
> a function in Perl or C whose primary purpose is to have side effects
> nevertheless returns a value, the value of the last expression it
> evaluates.  So you need to be careful about changing the last
> expression a Perl or C function evaluates, because you might break
> things accidentally.
> 
> I don't think that's debatable, and I don't think it's debatable that
> that's a problem.  It's debatable how big a problem it is; I think
> it's not a very big problem.  In fact, I don't know where I'd look for
> a piece of code that exhibits it.  But I know I've run into it in the
> past.

there are quite a few traps in perl, so how big the problem is is relative ;)

in any case, i've run into this far too many times for my liking.

[...]

> sub frotz {
>    my ($wibble, $gurble) = @_;
>    $wibble->frob('frotzed', $gurble);
>    return;
> }
> 
> But that's verbose and ugly, extra work to write and to read, so
> people don't do that.  It's not usually worth the effort for the tiny
> advantage it provides.

agreed. And worse, in bigger functions, it may fool the caller of the function
that checking the return value is needed. At least without checking that there
is no other "return" in the function.

i think i'm going to use the following noreturn function in some cases:
----------------------------------------
sub noreturn { die if defined wantarray }

sub f { noreturn }

eval { $a = f() }; $@ and warn "wanting a scalar fails";
eval { @a = f() }; $@ and warn "wanting an array fails";
eval {      f() }; $@ and warn "wanting nothing fails";
----------------------------------------
(note that "noreturn" has the same "wantarray" has "f" }