Reputation: 2708
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?
Upvotes: 17
Views: 17774
Reputation: 47829
$!
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.
Upvotes: 11
Reputation: 346
based on perl_doc
$!; show C library\'s errno
$@; show compile error
Upvotes: 2
Reputation: 943185
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.
Upvotes: 22