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

Say I have variables $x and $y. If I want to do something to $x to get $y, I go (for example):

$x=7; $y=3*$x**3 - 2*$x + 4;

This is fairly straighforward, but if I want to change the operations I perform on $x, I have to actually change the code. Is there some way I can store "3*$x**3 - 2*$x + 4" in a string and then use that string as my expression?

Thanks in advance for any help.

Replies are listed 'Best First'.
Re: Recover a mathematical expression from a string.
by chromatic (Archbishop) on Oct 01, 2006 at 06:56 UTC

    How about storing it in a subroutine instead?

    my $func = sub { my $x = shift; return 3 * ( $x**3 ) - 2 * $x + 4 }; my $to_x = $func->( $x ); my $to_y = $func->( $y );

    eval is a big, dangerous stick to carry around.

Re: Recover a mathematical expression from a string.
by grep (Monsignor) on Oct 01, 2006 at 03:38 UTC
    Are you looking for eval?


    grep
    Mynd you, mønk bites Kan be pretti nasti...
      Yes, I am. Thanks a lot.