The difference between $@ and $! in perl

What is the difference between $@ and $! in perl? Errors related to eval are printed using $@ . $! also used to capture errors. Then what is the difference between the two?

+6
source share
2 answers

From perldoc perlvar :

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

+14
source

$! set when a system call fails.

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

This will result in the output "There is no such file or directory."

$@ contains the argument passed to die . Therefore:

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

It makes no sense to check $@ without using any form of eval , and it makes no sense to check $! when you did not call a function that could set it in case of an error.

+3
source

Source: https://habr.com/ru/post/949638/


All Articles