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

Hi Wise monks.

I've got one question about scalar polymorphism:

How do I do to set up a scalar value eg '$foo' which has a numeric value in a numeric context and has a string value in a string context ?

For instance, I'd like to do something like that:

my $err = ???? ; my $num = $err + 0 ; print $num ; # Will print lets say the number '1' ; print $err ; # Will print the string 'ERROR 1' ;

I saw this type of behaviour in BerkeleyDB module and I wonder how it works.

Thanks for your precious help.

-- Nice photos of naked perl sources here !

Replies are listed 'Best First'.
Re: scalar polymorphism
by gellyfish (Monsignor) on Aug 02, 2006 at 15:20 UTC
Re: scalar polymorphism
by davorg (Chancellor) on Aug 02, 2006 at 15:21 UTC
Re: scalar polymorphism
by perrin (Chancellor) on Aug 02, 2006 at 16:22 UTC
    I have a suggestion: use an object instead. It's a lot less sneaky. If you want an error object, try Exception::Class.

      ++

      Absolutely. I'm not a fan of doing funky things that you can't immediately see in code. It's a maintenance headache. Sometimes it's fun to do, but if you can avoid it, that's a good thing. It's one of the reasons I rarely use tied variables.

      Cheers,
      Ovid

      New address of my CGI Course.