Can you provide any examples where using eval EXPR
is really necessary?
I'm asking because its generally discouraged.
views:
198answers:
4Quite a few years ago, I wrote a static web site generator which used Perl (<-- interesting that my spell checker suggests "Peril" as a replacement for that) as its scripting language. It allowed the user to enter information about different levels of a hierarchy - the first to market was for a cemetery where you had clients (paying customers) who owned memorials (for the deceased, obviously).
It had a GUI where you entered variables such as (tremble at my graphical skills here):
+------------+----------------------------+
| ClientName | Pax Diablo |
+------------+----------------------------+
| Address | 666 Hades St, Washinton DC |
+------------+----------------------------+
and picture variables as well.
In addition, for each market (such as the afore-mentioned cemetery), there was a controlling script which basically ran and processed each record at multiple hierarchy levels to generate the static content. Before then, the program had turned all those variables into things like:
$Var{"ClientName"} = "Pax Diablo";
(I think that syntax is right, I haven't done any Perl development for a while). The end result was a full web site with lots of clients, lots of memorials, search pages and a nice little money earner while it lasted (I was blown out of the market by funeral directors providing the same thing as a 'free' service within their regular packages).
But the whole thing was basically written in minimal Perl which only did two things:
- turned the variables into Perl assignment statements; and
- ran the market-specific Perl code.
Both the execution of the assignment statements and the market-specific Perl code was done with eval.
So it's not as useless as you may think. It was a cheap way to introduce scripting into an application.
String eval is the only way to make new code out of strings. This is rarely necessary, but there are a few valid use cases, for example when converting templates to runnable code. Other than that, there are very few valid uses for it. eval "require $module_name"
is a well known idiom, but using for example Module::Load is a better idea than that IMO.
String eval is the only way to:
- execute new code in a runtime decided package
- add overloading to a package at runtime (at least according to overload.pm)
- execute arbitrary strings of Perl
- compile macro type substitutions
String eval should not be used to:
- evaluate symbolic references
- execute any code from the user
- trap errors
- if there is any other way to do it
eval can also be used to create ad-hoc communication protocols between different systems or different languages that also have eval (provided that everything is secure of course. JSON can be seen as a more secure, but limited subset of this method)