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

Howdy my fellow monks... I'm having some eval trouble this afternoon. My eval isn't eval-ing, but returning the string of code instead. What is it I am doing wrong?

A typical value for $code is the following string (shown as if Dumped by Data::Dumper)
$VAR1 = '@sorted = sort { warn "in sort"; $result->{$b}->{year} <=> $result->{$a}-> +{year} || lc $result->{$a}->{species} cmp lc $re +sult->{$b}->{species} } keys %{$result};';

This is the snippet of code where I try running the eval. The eval doesn't throw an error at all. It just doesn't seem to eval.

my $code = qq( \@sorted = sort { $table{$sort1} || $table{$sort2} } keys \%{\$result} ); warn "code is $code"; @sorted = eval{ $code } ; warn Dumper [@sorted];

@sorted contains one item, the code string shown earlier. thanks!

Replies are listed 'Best First'.
Re: seeking eval enlightenment
by runrig (Abbot) on May 03, 2004 at 23:00 UTC
    eval can either eval a block of (already compiled) code, or a string of code (that's not compiled yet). You seem to want to eval a string, but you are using the eval block syntax. Use parens "()" instead of curly braces "{}".
      Thank you!
      I changed it to:
      eval $code;
        Don't forget to check $@ afterwards. As pointed out in eval, in addition to evaluating code, eval traps errors and puts them into $@. So minor typos etc will get trapped, and can cause puzzling failures.