http://www.perlmonks.org?node_id=1019365


in reply to Is this reliable?

It should work reliably (but I couldn't find any links about it, besides Truth and Falsehood, Scalar values). You can force any true value to be 1 by adding !! before it. You can also use $r += $temp > 100 ? 250 : 0; if you are still in doubt.

Update: as pointed out above, it usually works and should work further, but the ternary operator is safer.

Sorry if my advice was wrong.

Replies are listed 'Best First'.
Re^2: Is this reliable way to cast from BOOL to NUMBER?
by misterperl (Pilgrim) on Feb 18, 2013 at 16:57 UTC
    Many thanks Monks (and a bow)- your knowledge of internals is awe-inspiriing, and in my case perhaps a bit of a consolation. For now based on your findings, I'll go with 0 and 1 will be my cast-value from bool to int.

    I also tried it with a regex and that ALSO yielded 0 and 1 (yay).

    I'd actually considered using ? : construct, and may end up with that, but I'm hoping I don't have to.

    Here my issue- I'm sort of allowing web users to *write psuedo-perl* , which I convert into actual Perl, then eval. I want to only yield them a very tiny subset of commands- mostly along the lines of doing math, or setting values on values in only one hash. So I didn't want to let them deviate too far even into conditionals. All of course for obvious security reasons..

    Thanks * 10 !

      Personally I'd get them to write an entirely different scripting language and then either write a parser/interpreter for that scripting language, or use an off the shelf one (like JE for Javascript).

      package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
      Oh yeah, did something similar a few years ago and line input '<>' and Here-doc '<<' operators were the obvious trouble makers. Since I only allowed simple arithemtic constructs I could get by with regexes to police the code but I never trusted that completely.
      ... for obvious security reasons..

      Ah, the ever-reliable "Security Through Obscurity" strategy!

      You can try Safe for restricting string eval but remember that there is no warranty of 100% safety. A bug in Perl or in this module can lead to a security hole.
      Sorry if my advice was wrong.