Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it kosher to assign to $! in Perl?

Is it OK to assign to $! on an error in Perl?

E.g.,

if( ! (-e $inputfile))
{
      $! = "Input file $inputfile appears to be non-existent\n";
      return undef;
}

This way I can handle all errors at the top-level.

Thanks.

like image 270
Paul Nathan Avatar asked Jun 25 '09 16:06

Paul Nathan


1 Answers

If you assign to $!, it is placed in the system errno variable, which only takes numbers. So you can in fact do:

use Errno "EEXIST";
$! = EEXIST;
print $!;

and get the string value for a defined system error number, but you can't do what you want - setting it to an arbitrary string. Such a string will get you a Argument "..." isn't numeric in scalar assignment warning and leave errno set to 0.

The other problem is that $! may be changed by any system call. So you can only trust it to have the value you set until you do a print or just about anything else. You probably want your very own error variable.

like image 160
ysth Avatar answered Oct 20 '22 16:10

ysth