in reply to Re: When is 'eval' too inefficient?
in thread When is 'eval' too inefficient?

You're right about the floating numbers--it's never the case that one of the variables would be undefined. The use of "+0" is precisely the solution, but dare I say, an inelegant one. If I can say int $var1, I think there should be an equivalent counterpart for real numbers, as in real $var1 or float $var1.

Though the problem is solved, I'm still curious about the broader question of eval that I originally asked: is there a rule of thumb as to how inefficient it may be? Are there suggestions about when it's best to avoid it, and best to use it?

Replies are listed 'Best First'.
Re^3: When is 'eval' too inefficient?
by ikegami (Patriarch) on Oct 12, 2007 at 15:18 UTC

    To argue that Perl should provide a function to convert a scalar to a float because it provides a function to convert a scalar to an integer is a valid argument, but the premise is false. Perl doesn't have a function that converts a scalar to an integer.

    int implements the mathematical function. It doesn't necessarily return an integer in the C sense of the word. For example, here's an example where int returns a float (NV):

    >perl -MDevel::Peek -e"Dump int(2**32);" SV = NV(0x184ac1c) at 0x226be4 REFCNT = 1 FLAGS = (NOK,pNOK) NV = 4294967296

    Type conversion is always done implicitely in Perl.
    If Perl needs a string, the scalar will be coerced into a string.
    If Perl needs a number, the scalar will be coerced into a number.
    If Perl needs a boolean, the scalar will be coerced into a boolean.
    etc.

    Of course, you are free to produce your own conversion routines.

    sub to_string { "$_[0]" } sub to_num { 0+$_[0] } sub to_bool { !!$_[0] } etc.
Re^3: When is 'eval' too inefficient?
by ikegami (Patriarch) on Oct 12, 2007 at 15:34 UTC

    Person 1: This is my favorite horse.
    Person 2: Isn't that your only horse?

    In the general sense, eval is the most efficient function. There's simply no alternative.

    In specific situations where there is an alternative, the alternative is probably more efficient (and safer and more maintainable). You'll have to benchmark the two for more details.