Sunday, December 21, 2008

Power of Eval

The power of shell script/scripting language/dynamic language, whatever you want it call it, is the ability to create and execute arbitrary commands on the fly. This feature is not available in other statically-typed programming languages.

These dynamic languages is able to do variable substitution before execution. With the built-in eval command, they are able to do two parses before submitting its content to the interpreter for final evaluation.

Here I am showing you an example of how we can make use of eval. In Bourne Shell, we need to do the following for number counting. It is almost a standard template you will see in script.

count=`expr $count + 1`

With eval, we are able to generalise the above template into a re-usable function. The function incr is able to take variable name as first argument and optional second argument as the step for increment (default is 1). Below shows how the function incr can apply to variables "counter1" and "counter2":

$ incr() { eval $1=\`expr \$\{$1:-0\} + ${2:-1}\`; }

$ echo $counter1

$ incr counter1

$ echo $counter1

$ incr counter1 5

$ echo $counter1

$ incr counter2 4

$ incr counter2 5

$ echo $counter2

When you run incr counter1, the incr function will change the definition to
incr() { counter1=`expr $counter1 + 1`; }.
Similar for counter2 and other variables. Now we are able to increment any variable without having to use the standard template. I hope you can see the power of eval from this simple example.



Post a Comment

<< Home