13
votes

What is the difference between $@ and $! in Perl? Errors associated with eval are outputted using $@ . $! is also used for capturing the error. Then what is the difference between both of them?

3

3 Answers

20
votes

From perldoc perlvar:

The variables $@ , $! , $^E , and $? contain information about different types of error conditions that may appear during execution of a Perl program. The variables are shown ordered by the "distance" between the subsystem which reported the error and the Perl process. They correspond to errors detected by the Perl interpreter, C library, operating system, or an external program, respectively.

8
votes

$! is set when a system call fails.

open my $fh, '<', '/foobarbaz' or die $!

This will die outputting "No such file or directory".

$@ contains the argument that was passed to die. Therefore:

eval {
    open my $fh, '<', '/foobarbaz' or die $!
};
if ( $@ ) {
   warn "Caught exception: $@";
}

It make no sense to check $@ without using some form of eval and it makes no sense to check $! when you haven't called a function that can set it in the case of an error.

0
votes

based on perl_doc

$!; show C library\'s errno
$@; show compile error