I want to return a different value in string context and numeric context like $!
does. I know I can find out whether I am in list or scalar context with wantarray, but is there any way in pure Perl to determine which scalar context I am in? I assume there is an answer in XS as well and I am willing to take that answer if there is no way do it in pure Perl.
Asked
Active
Viewed 211 times
4

Brian Tompsett - 汤莱恩
- 5,753
- 72
- 57
- 129

Chas. Owens
- 64,182
- 22
- 135
- 226
2 Answers
13
Check out the Scalar::Util
module, specifically 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 avaliable anywhere you have Perl.

Chris Lutz
- 73,191
- 16
- 130
- 183
-
Thanks, that does exactly what I need. I really need to go through the Core again. There are too many good things I have forgotten/never knew. – Chas. Owens Apr 29 '09 at 01:50
3
While I can propose cases when this would be useful (maybe Roman Numerals), you would be better off creating an object with an integer and a string attribute. Use the appropriate attribute in the appropriate context.
This gives you the added flexibility of being able to overload operations with 'use overload'. In a Roman Numerals example, dualvar will work until you want to add 2 roman numerals together.

Craig Lewis
- 331
- 2
- 3