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

Use of eval()

From:
Steve Bertrand
Date:
October 14, 2009 16:46
Subject:
Use of eval()
Message ID:
4AD662DF.6090107@ibctech.ca
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?

#!/usr/bin/perl

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";
}
__END__

Stee






nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About