in reply to subroutines & functions

You're asking what context the function is being called in. There are (basically) three contexts in Perl - void, scalar and list. You can use the wantarray function to determine how your function has been called.

sub how { my $how = wantarray; if (defined $how) { if ($how) { print "list\n"; } else { print "scalar\n"; } } else { print "void\n"; } } how; my $s = how; my @a = how;

For your question I think you just need to check if the return value from wantarray is defined.

--
<http://www.dave.org.uk>

"The first rule of Perl club is you do not talk about Perl club."
-- Chip Salzenberg

Replies are listed 'Best First'.
Re: Re: subroutines & functions
by bart (Canon) on Jun 23, 2003 at 02:07 UTC
    For your question I think you just need to check if the return value from wantarray is defined.
    I rarely, if ever, care about the difference between scalar and void context. To me, and I think to perl, too, void context is a special case of scalar context. Hence, undef is false, too. I definitely don't care about the difference between returning a scalar or not returning anything, and most certainly not for "efficiency reasons": that extra test likely wastes more time than returning and wasting a scalar value ever would.

    I do care about the difference between list context and scalar context.

      I definitely don't care about the difference between returning a scalar or not returning anything, and most certainly not for "efficiency reasons": that extra test likely wastes more time

      Um, if you are doing it for efficiency reasons, then you don't do all of the work and then, just at the end, check whether they want a value back or not. You note that they don't need a value back and avoid the whole computation. For example, in Win32::TieRegistry, you can use delete to delete a key/value from the registry. Just like when using delete on a regular hash, delete returns what the key (that was just deleted) contained. But if you use delete in a void context, then all of this making of copies is avoided.

      Then there is the whole 'failures in a void context should resort to die' concept that I rather like.

                      - tye