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

Dear Monks,

Is there any way to know if my sub was called in a "numerical" context or a "string" context?

use strict; sub sensible { return "one" if stringcontext(); return 1 if numericalcontext(); return; } print "Result = ".sensible()."\n"; # Result = one print "Result = ".0+sensible()."\n"; # Result = 1
A partial solution is to use dualvar from Scalar::Util but then I have to compute both the string and the number on each call.

Many thanks

Casiano

Replies are listed 'Best First'.
Re: Finding the context of a call: numerical or string
by kyle (Abbot) on Feb 29, 2008 at 16:35 UTC

    See Contextual::Return.

    Update: According to the synopsis, this should work for you:

    sub sensible { return STR { "one" } NUM { 1 } }
      Many thanks!

      It works!

      Casiano

        Hi Casiano,

        Take into account that Contextual::Return uses Want. Maybe you can manage to do what you need with Want alone. Is caching + dualvar an option?

        cheers --stephan p.d maybe you could visit madrid.pm one of these days? ;)
Re: Finding the context of a call: numerical or string
by ikegami (Patriarch) on Feb 29, 2008 at 17:19 UTC

    Or you can create a dualvar using dualvar in core module Scalar::Util. Then, the returned value with be *both* a string and a number.

    use Scalar::Util qw( dualvar ); sub sensible { return dualvar(1, "one"); } my $foo = sensible(); print "Result = ", ''.$foo, "\n"; # Result = one print "Result = ", 0+$foo, "\n"; # Result = 1

    Very fast too. Nothing special as far as Perl is concerned.

Re: Finding the context of a call: numerical or string
by leocharre (Priest) on Feb 29, 2008 at 16:56 UTC
    There's something called contextual return which sounds sexy, but... I understand this may be a performance hit.

    I would't use this kind of thing in anything that's supposed to go fast or do something crazy without user interaction.

    deserves looking into. (wow, Damian Conway sure does make a lot of juicy stuff..)

      Apparently, it's even one of his "safe" modules.


      TGI says moo