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?
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.
$!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With