Eric Fossum
Eric Fossum

Reputation: 2472

Perl eval not catching exceptions

Why doesn't Perl catch this exception?

my $fh;
eval { close $fh };
warn('Caught') if &@;

with an output of:

Can't use an undefined value as a symbol reference at New_test.pl line 30.

UPDATE: same output without the warn line and eval { close $fh }; is line 30.

Upvotes: 1

Views: 1266

Answers (4)

ddoxey
ddoxey

Reputation: 2063

The eval block does catch the exception and prevents it from being fatal.

For example:

#!/usr/bin/perl -Tw

use strict;
use warnings;

my $fh;
close $fh;
print "done\n";

This program dies with the expected message when close executes. For comparison:

#!/usr/bin/perl -Tw

use strict;
use warnings;

my $fh;
eval { close $fh; };
print "done\n";

This program runs quietly and executes the print statement at the end.

Upvotes: 0

Galimov Albert
Galimov Albert

Reputation: 7357

The exception is not in eval, its on line below, &@ is wrong sequence, you meant $@

UPD: Note that close can die when you have strict on and $fh is undef which i think is not normal case (an algorithm bug).

Upvotes: 6

TJ B
TJ B

Reputation: 167

You should use $@ and not &@. Please refer this link to see what do all special variables Perl has.

$@ means The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.

Upvotes: 0

TLP
TLP

Reputation: 67910

Perhaps you meant $@ and not &@? The latter will be interpreted as a subroutine.

Upvotes: 4

Related Questions