in reply to Scalar and void subroutines

There must be something more here eff_i_g for it to be important to distinguish between void and scalar context.

Your sample code doesn't distinguish between void and scalar context of course. It simply provides a (somewhat hacky) way of signaling to the sub that you don't want a value returned. You could do something similar in a rather more up front way by:

do_something_to(\$this_var, 'No return required'); sub do_something_to { if (! $#_) { $$_[0] = 'x'; return; } return 'x'; }

but that's pretty ugle really :).


Perl is Huffman encoded by design.

Replies are listed 'Best First'.
Re^2: Scalar and void subroutines
by eff_i_g (Curate) on Nov 10, 2005 at 21:29 UTC
    You're right; my description was iffy. What I meant was:

    If called in void context, I am expecting a reference to be passed.
    If called in scalar context, I am expecting... either, actually, but there must be a reference in void.

    Sorry about that.

      So you could:

      sub name { die 'ref arg required in void context' if ! defined wantarray and ! +ref $_[0]; my ($arg) = @_; if (ref $arg) { $$arg = 'x'; return; } return 'x'; }

      as a check that you've got a ref param in void context.


      Perl is Huffman encoded by design.