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

I'm pretty new to perl and haven't ever had the need to use eval until I wanted to reconstruct data back into perl using Data::Dumper, which it seems perfectly suited for and works perfectly well.

What my problem is is that I don't exactly understand how this works. From what I've read of eval, its basic use is that it's a good way to trap errors without blowing up your program, yet I can't seem to bridge this in my mind with its function in Data::Dumper. Could someone help me or point me to somewhere where I could better understand this? Thanks for any help..

  • Comment on Exactly HOW eval works (with Data::Dumper)

Replies are listed 'Best First'.
Re: Exactly HOW eval works (with Data::Dumper)
by moritz (Cardinal) on Dec 12, 2007 at 17:00 UTC
    It's pretty much in the documentation for eval, but I try to explain a bit nonetheless.

    There are two completely different usages of eval. The first:

    eval { # code here that might throw exceptions # this is the form that you described }

    And the second:

    my $string = '4 + 5'; my $answer = eval $string;

    This second form is what you need. It takes a string, and compiles and runs it like a little Perl program.

    There are other serialization formats that you might want to use instead of Data::Dumper like Storable, YAML, JSON and XML. They have the advantage that you don't have to eval your code, which is a security risk if you don't trust your data source.

      Ah thanks, I wasn't quite getting that second distinction, and after looking at the output again it makes perfect sense.