我想在perl中编写一些设置$的函数!以类似于内置perl函数的方式.当我尝试这样做时,它会抱怨"参数"无法创建管理员用户"在标量赋值中不是数字".我试过谷歌搜索这个但不幸的是谷歌不会看$!所以结果很难得到.
if(!createUser('admin')) { print $!; }
sub createUser
{
my ($user) = @_;
if($user eq "admin")
{
$! = "Cannot create admin user";
return 0;
}
#create user here
return 1;
}
Run Code Online (Sandbox Code Playgroud)
PS.我知道Try :: Tiny等,但我想保持与脚本其余部分的一致性,如果我切换到try/catch我想移动整个脚本,我还没准备好.
mob*_*mob 12
$!是对应于您的操作系统的数字错误代码的魔术变量(errno在Unix-Y libc库,别的好像GetLastError()从kernel32.dllWindows中).
您只能将其设置为数字.当Perl想要在字符串上下文中使用它时,它会将其转换为适当的文本错误消息.
例:
$! = 4;
print $!, "\n";
print 0+$!, "\n";
Run Code Online (Sandbox Code Playgroud)
产生(在我的系统上,无论如何):
Interrupted system call
4
Run Code Online (Sandbox Code Playgroud)
它是完全合适的(如果不可移植,因为不同的系统可以自由地使用不同的整数值来表示标准错误代码),以设置$!为对应于系统上的某些标准错误:
sub my_do_something_with_file {
my $file = shift;
if (! -f $file) {
$! = 2; # "No such file or directory" on my system
return;
}
...
}
Run Code Online (Sandbox Code Playgroud)
但是没有工具可以创建自己的自定义错误消息$!.