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

Or, how to make this work in Perl: create a function x() that can return an unblessed scalar, or an object if it is tried to be called as an object. For example:

print makeupname(); # prints "John Smith" print makeupname()->first; # prints "John"

Is it possible?

Replies are listed 'Best First'.
Re: Is there a wantobject like wantarray?
by choroba (Cardinal) on Sep 25, 2014 at 15:45 UTC
    You can solve the problem the other way round: always return an object, but let it overload stringification:
    #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; { package MyObj; use overload '""' => \&both, fallback => 1; sub new { my ($class, $first, $last) = @_; bless { first => $first, last => $last }, $class } sub first { $_[0]->{first} } sub both { "@{ $_[0] }{qw{first last}}" } } sub makeupname { 'MyObj'->new(qw(John Smith)); } say makeupname(); say makeupname()->first;
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      I think that's more or less how want works , it returns an object¹ which unfolds according to the context.

      But I have to admit I never delved too deep into this area of Damian's creativity. :)

      Cheers Rolf

      (addicted to the Perl Programming Language and ☆☆☆☆ :)

      ¹) or tied value? (which is actually not very different)

      update

      should be mentioned that this comes with a performance penalty, because even simple scalars need to be "unfolded".

        No, Want isn't even Damian's module. I think you may be thinking of Contextual::Return. Want is far more spooky than that. It examines the OP tree to figure out how the return value is going to be used.

Re: Is there a wantobject like wantarray?
by Anonymous Monk on Sep 25, 2014 at 15:39 UTC
    OK, I just found out the CPAN module Want which does exactly this.

      FWIW, choroba’s approach, stringification through overload is easy, somewhat popular, and though it has a gotcha here and there, I appreciate it much more than I am irritated by it.

      Want is a bit magical, has a handful of segfault tickets open on it, and I’ve never seen it used anywhere in the wild.

        > somewhat popular ...

        may I ask where? :)

        Cheers Rolf

        (addicted to the Perl Programming Language and ☆☆☆☆ :)

Re: Is there a wantobject like wantarray?
by Anonymous Monk on Sep 26, 2014 at 01:15 UTC

    Is it possible?

    A better question: is this a good idea?

    autobox does this by making everything an object, and overloading stringification...