|Home » Faqs » Manipulating text » Eval|
You have a string that you wish to treat as code. In other words, you have a fragment of perl that you have built up into a string, or sourced externally, and you want perl to interpret it at run time. For example:
my $string = '$a + $b';
And you want to print the result of $a + $b.
If you are new to perl, then be aware that it's likely that you are
looking at this page in order to find out how to do something that is
more easily (and safely) done without using
Have a look at the following two perlfaq entries in particular:
perldoc -q 'How can I use a variable as a variable name'
perldoc -q 'How can I expand variables in text strings'
You can nearly always design things so that you do not have to resort to using eval in this fashion.
Perl has an 'eval' function. This function takes a string and treats it like code. So for the above example, you could use:
#!/usr/bin/perl use strict; use warnings; my $string = '$a + $b'; my $a = 4; my $b = 17; my $c = eval($string); die $@ if ($@); print "\$c = $c\n"; exit 0;
This would produce the following output:
$c = 21
Consider your design choices before using eval in this fashion. It goes without saying that executing code supplied to you from an outside source can be a very insecure thing to do. At the very least you should be conversant with perl's taint mechanism.
The Safe module provides a convenient mechanism for safely evaluating external code.
The eval function is also very useful for exception handling. For example, if you wanted to require a file or use a module that may not exist locally, you could eval the 'require' or 'use' statement, then check $@ for errors.
perldoc -f eval perldoc perlsec perldoc Safe