"Perl for Perl Newbies" - Part 4Exceptionsdie and eval

6.1. die and eval

The statement die throws an exception which can be any Perl scalar. The statement eval { ... } catches an excpetion that was given inside it, and after it sets the special variable $@ to be the value of the exception or undef if none was caught.

Here's an example:


use strict;
use warnings;

sub read_text
    my $filename = "../hello/there.txt" ;
    open I, "<$filename"
        or die "Could not open $filename";
    my $text = join("",<I>);

    return $text;

sub write_text
    my $text = shift;
    my $filename = "../there/hello.txt";
    open O, ">$filename"
        or die "Could not open $filename for writing";
    print O $text;

sub read_and_write
    my $text = read_text();


sub perform_transaction
    eval {
    if ($@)
        print "Could not perform the transaction. Reason is:\n$@\n";


Written by Shlomi Fish