doran has asked for the wisdom of the Perl Monks concerning the following question:

A quick beginner's question from a non-beginner:

Is it always okay to return a value from a routine that is sometimes called in a void context?

For example, take this classic from the cookbook:

sub name { my $self = shift; if (@_) { $self->{NAME} = shift } return $self->{NAME}; }
Is there a reason it would be better written as:
sub name { my $self = shift; if (@_) { $self->{NAME} = shift } return $self->{NAME} if defined wantarray; }
Of course there may be specific cases where I'd want to avoid returning a value in a void context, but this question is under the "general rule" category. Is there a problem with returning a value in a void context?

Replies are listed 'Best First'.
Re: OK to always return a value?
by davido (Cardinal) on May 09, 2005 at 02:04 UTC

    You can always return whatever you want in void context. It's unimportant. The one thing that might be smart, however, is that if your return value requires a lot of work to create, and you're just going to throw it away, it might be wise to not create it in the first place, in that context.

    Examples of this include the generation of a long list, when there are times that you don't use the list. Or times when the single scalar return value has taken a lot of work to generate. If you can detect early on that the return value isn't needed, you can save a few cycles by not generating it.

    Of course this discussion could already be construed as premature optimization. There's no need to complicate things unless you know that the creation of a return value in void context is specifically creating a bottleneck.


    Dave

      Excellent, that's what I had assumed, but it's good to hear it from others. Thanks both Zaxo and Dave.
Re: OK to always return a value?
by Zaxo (Archbishop) on May 09, 2005 at 01:54 UTC

    No, that's not a problem. You really only want the wantarray decision in a case like this if the result calculation is difficult and the side effect simple. That's not a common case.

    After Compline,
    Zaxo

Re: OK to always return a value?
by merlyn (Sage) on May 09, 2005 at 02:16 UTC
    You can return values from a subroutine invoked in a void context, but Perl shoves them into /dev/null, so be sure you perform regular maintenance on your machine to empty /dev/null.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.


    P.S. Kidding, of course.
      No prob, I have a crontab entry that already does this.

      1 * * * * perl -e "push(@b,glob) for @ARGV ;END{unlink $_ for @b}" /d +ev/null/*
      Of course this misses subdirectories. I just do them manually.

      :)