in reply to What should be returned in scalar context?

When the function is localtime-ish, I make it work like that. I have several that return a human readable string in scalar context, but a list of (numeric) elements in list context.

If the function returns a list that has a logical order and a variable number of elements, I return wantarray ? @array : \@array. But not when the function has a prototype of (&@).

I find return @array; annoying, unless the function warns or dies in scalar context. Again, an exception is made for map-ish functions.

I often use void context for mutating values: (Or: The function becomes a procedure in void context)

my @bar = encode @foo; # mutated copy in @bar my $bar = encode @foo; # mutated copy in @$bar encode @foo; # @foo's elements are now encoded
This is great when working with a hash of things that are about to be displayed, transmitted, etc:
my $row = $db->query('select ...')->hash; encode values %$row;

Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }

Replies are listed 'Best First'.
Re: Re: What should be returned in scalar context?
by tilly (Archbishop) on Dec 02, 2003 at 15:40 UTC
    I guess that I have been indoctrinated enough into the concept that side-effects in functions are a bad thing that I strongly avoid writing a function that causes side-effects. (Particularly if it only does it in one context.)

    As for return @array; - that made sense to me when I was writing a function that I needed in list context and didn't want to think through scalar context. So I left it with the easiest behaviour to implement, knowing full well that it wouldn't do anything useful in scalar context, meaning that if I ever called it in scalar context then I would have motivation to fix it with some supposition about what it should do in scalar context.

      I guess that I have been indoctrinated enough into the concept that side-effects in functions are a bad thing that I strongly avoid writing a function that causes side-effects. (Particularly if it only does it in one context.)

      Side effects are okay, as long as they're documented clearly. The efficiency that you get by mutating values instead without copying them first is worth it, in my opinion. I usually document the functions exactly as in my post: a piece of code that calls the function/procedure in all three contexts, each with a useful comment.

      As for return @array; - (...) So I left it with the easiest behaviour to implement, knowing full well that it wouldn't do anything useful in scalar context, (...).

      Of course, there isn't always a good scalar value. Hence the "unless the function warns or dies in scalar context." in my post. I tend to carp +(caller 0)[3] . ' used in non-list context' unless wantarray;.

      Juerd # { site => 'juerd.nl', plp_site => 'plp.juerd.nl', do_not_use => 'spamtrap' }