Difference between $@ and $! in perl

$! 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.


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.

Tags:

Perl