develooper Front page | perl.beginners | Postings from October 2009

Use of eval()

Steve Bertrand
October 14, 2009 16:46
Use of eval()
Message ID:
Hi all,

Although I've read the docs and have been practising with it, I'm a bit
confused on the use of eval().

For some reason, it took a few swings of the hammer to get past wanting
to look for array elements within $@ :P

I think I now understand the dangers of using eval() to trap errors,
which is why I'm only using it within tests, where each test has it's
own tight lexical scope. What I can't quite grasp for some reason, is
why the 'block eval' is preferred over the 'string eval'.

Can someone let me know if the code below has the characteristics of
proper use of $@ and eval, and perhaps an example of a showstopper use
of string eval?


use warnings;
use strict;

my $param = $ARGV[0];

if ( $param && $param eq 'fail' ) {
        eval { i_die(); };
        print "Past bad eval(), we've bypassed die()...\n";
        print $@ if $@;
	# ... do something else
else {
        eval { i_live(); };
        print "Past good eval()\n";
        print "***$@***... '$@' is the empty string.\n";

sub i_die {
        die "I'm dying";

sub i_live {
        print "I live!\n";

Stee Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About