How can both be true: $! == 10 && $! eq 'No child processes'?

  • Thread starter Peter Valdemar Morch
  • Start date
P

Peter Valdemar Morch

I can see from perldoc perlvar about $!:

"If used numerically, yields ..."
and
"If used as a string, yields ..."

Is there any way I can do this for my own variables, say $a - to let
it have one value if used numerically, and another if used as a
string? It tastes a little like wantarray for subs, but... Is this
very, very special for $!?

Peter
 
J

Jeff 'japhy' Pinyan

Is there any way I can do this for my own variables, say $a - to let
it have one value if used numerically, and another if used as a
string? It tastes a little like wantarray for subs, but... Is this
very, very special for $!?

There are two ways to have it done, generally speaking:

1. make $foo an object of a class that overloads stringification and
numification

2. muck with the internal representation of $foo so that Perl thinks it
has a PV (string value) and an unrelated NV (numeric value)

Here's a brief example of the first:

package StrNum;
use overload ( '""' => 'str', '0+' => 'num', fallback => 1 );
sub new {
my $class = shift;
bless [ @_ ], $class;
}
sub str { $_[0][0] }
sub num { $_[0][1] }
1;

It's used thus:

use StrNum;
my $both = StrNum->new("string", 100);
if ($both eq "string" and $both == 100) { print "ooh!" }

There is probably already a module on CPAN that employs this mechanism.

The second way is faster to employ because it has nothing to do with
objects and overloading, and works by fiddling with Perl's representation
of your scalar. The Scalar::Util module includes a dualvar() function
that does just that:

dualvar NUM, STRING
Returns a scalar that has the value NUM in a numeric context and
the value STRING in a string context.

$foo = dualvar 10, "Hello";
$num = $foo + 2; # 12
$str = $foo . " world"; # Hello world

(Ok, so I had the order the other way around in my sample module above.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top