If the eval succeeds, that is, no compilation errors, and
no fatal errors or dies, $@ will be *empty*. Furthermore,
what you print in an eval, you can't capture easily. By
default, it'll go to stdout. What you probably want is
something like:
#!/usr/bin/perl
use strict;
use warnings;
while (<DATA>) {
s/<# \{(.*?)\} #>/$1/eeg;
print;
}
__DATA__
<# { $a = 3; $b = 3; if ($a == $b) { "a=b"; } } #>
<# { 4*3; } #>
Which prints:
a=b
12
Note the differences:
- In the pattern, the parens are inside the braces.
- The replacement part is just $1.
- There are two /e modifiers.
- The data doesn't have prints.
Abigail | [reply] [d/l] [select] |
Although the "eeg" trick of Abigail-II is nice, I don't think it gives you enough flexibility. I would use a sub, like so:
sub process {
my $src = shift;
# possibly do some pre-processing on $src here
my $value = eval $src;
# possibly extra external logging if something went wrong
return $@ ? "<B>Error in '$src': $@</B>" : $value;
}
and then have:
$data =~ s/<# (\{.*?\}) #>/process($1)/eg;
Liz | [reply] [d/l] [select] |
use IO::String;
...
$data =~ s/<# (\{.*?\}) #>/evalCap($1)/eg;
sub evalCap
{
my $code = shift;
my $str;
my $str_fh = IO::String->new($str);
my $old_fh = select $str_fh;
eval $code;
select $old_fh;
$str;
}
Update:
The regular expression can be simplified: s/<# {(.*?)} #>/....
As Abigail implies, the braces aren't needed in the eval. Nor in this case do they need to be escaped.
- nashdj | [reply] [d/l] [select] |
I just want to say "security problem". The implications are a bit scary, aren't they?
($_='kkvvttuubbooppuuiiffssqqffssmmiibbddllffss')
=~y~b-v~a-z~s; print
| [reply] [d/l] |