in reply to OO design: returning string and/or special value

I'm with 1nickt's comment, in that using context to determine the result for this is somewhat fraught.

Assignment to an array or hash will need scalar context in some cases, which is as much typing as a method argument, and will lead to later programmers wondering what is going on.

my %hash1 = (some_key => $object->method); my %hash2 = (some_key => scalar $object->method);

More generally, though, wantarray works well for returning flat lists or references to lists (although this approach also needs explicit scalar context sometimes).

Replies are listed 'Best First'.
Re^2: OO design: returning string and/or special value
by wanna_code_perl (Friar) on Oct 07, 2019 at 22:51 UTC

    True, hash/array assignment and other such things can trip sleepy programmers up. It's very unlikely to ever be called in this manner in my case, but certainly not out of the question. What I do wonder though, is whether that necessarily means "don't use wantarray," or if it's reasonable to trust an experienced Perl programmer to understand list and scalar context in a documented method, to avoid other potential bugs and reduce the average cognitive load of the programmer in question. What do you think?

      I use wantarray in my code, but with the aim of doing so consistently, i.e. related methods all use it or all don't. Returning list refs is generally faster, especially if the list is large, so in some cases it is added as an optimisation that will not break (or will break less) code elsewhere in the system. This code is not on CPAN, though, so I have more freedom in doing so.