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

Greetings,
I need to write a perl script to evaluate a formula based on the contents specified in a configuration file using comma separated value format. For instance, a formula to calculate free swap space in a window system. For the sake of discussion, lets assume there are 3 lines in this file: 127.0.0.1,data,Win32_OperatingSystem,FreeSpaceInPagingFiles,,FreeSpaceInPagingFiles 127.0.0.1,data,Win32_PageFile,FileSize,,PageFileSize 127.0.0.1,formula,SwapUsage,,(FreeSpaceInPagingFiles/PageFileSize)*100

The first two lines define two data points, FreeSpaceInPagingFiles and PageFileSize. The third line defines a formula, SwapUsage and the formula is (FreeSpaceInPagingFiles/PageFileSize)*100.
The formulas are specified by the users so it can be different for each type of data point. My question is that when we retrievd data for one data, such as FreeSpaceInPagingFiles and I stored it in a hash, such as $hash(FreeSpaceInPagingFiles) = 732448;
How do I evaluate the formula dynamically? In other words, how to replace the formula with real data and get the result?
Thanks for your help,
tmy05

Replies are listed 'Best First'.
Re: How to evaluate a formula?
by dragonchild (Archbishop) on Jun 01, 2005 at 14:35 UTC
    Build a string of executable code and use the eval function.

    Note - you had better trust your source. eval will do anything and everything that string says. Including things like "system 'rm -rf /';" ... You have been warned.


    • In general, if you think something isn't in Perl, try it out, because it usually is. :-)
    • "What is the sound of Perl? Is it not the sound of a wall that people have stopped banging their heads against?"
      Thanks
Re: How to evaluate a formula?
by Limbic~Region (Chancellor) on Jun 01, 2005 at 14:58 UTC
    tmy05,
    Well, you might be able to adapt a ready made solution if you forced a grammar that already had a pre-existing parser (like Reverse Polish Notation). Other than that, you will need to define your own parser (perhaps using Parse::RecDescent). Of course, there is always the dangerous method of s/// and eval.

    Cheers - L~R

Re: How to evaluate a formula?
by Anonymous Monk on Jun 01, 2005 at 16:46 UTC