Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between $@ and $! in perl

Tags:

perl

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?

like image 253
Newbie Avatar asked Jul 17 '13 10:07

Newbie


2 Answers

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.

like image 63
Quentin Avatar answered Sep 21 '22 09:09

Quentin


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

like image 24
innaM Avatar answered Sep 22 '22 09:09

innaM