How to create an object that returns different values ​​in different scalar contexts?

I want to return a different value in the context of the string and the numeric context, for example $! . I know that I can find out if I am in a list or a scalar context with wantarray, but is there a way in pure Perl to determine which scalar context I am in? I assume that there is an answer in XS as well, and I am ready to accept this answer if there is no way to do it in pure Perl.

+4
source share
2 answers

Check the Scalar::Util module, in particular the dualvar() function:

 use Scalar::Util qw(dualvar); my $scalar = dualvar 10, "Hello"; my $twelve = $scalar + 2; # $twelve = 12 my $greeting = $scalar . " world"; # $greeting = "Hello world" 

Scalar::Util is part of the core distribution and should be available wherever you have Perl.

+13
source

While I can suggest cases where this would be useful (perhaps Roman Numerals), you better create an object with an integer and string attribute. Use the appropriate attribute in the appropriate context.

This gives you extra flexibility to overload operations using overload. In the Roman Numerals example example, the dualvar function will work until you want to add 2 Roman numerals together.

+2
source

All Articles