从Perl子例程返回错误消息 [英] Returning error messages from perl subroutines

查看:71
本文介绍了从Perl子例程返回错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是从perl的子例程中返回错误消息的好方法吗?

Is this a good way of returning an error messages from a subroutine in perl?

sub some_subroutine{
    # do something
    $something = 14;

    if(1 == 2){
        $_ = "This should not be happening!";
        return undef;
    }
    return $something;
}

my $ret=some_subroutine();
print "ERROR: $_" unless(defined $ret);

代码运行正常(在并行世界中,在1 == 2所在的位置),但是使用$_返回错误消息是一种好方法吗?我没有找到有关$_用于这种目的的任何文档.

The code runs OK (in a parallel world, where 1 == 2), but using $_ to return the error message is a good way? I didn't found any documentation regarding the usage of $_ for this kind of purposes.

谢谢!

推荐答案

$_并不是一种好的机制,因为许多其他事物都在使用和设置它.

$_ is not a good mechanism as so many other things use and set it.

您可以设置其他一些全局变量,例如$ Error,但是最好的方法是引发异常.这样,用户不必总是检查并忘记它只是发生了.在Perl中,使用" die "生成异常. die将接受一个字符串或一个对象.有很多模块可以使抛出异常变得更容易,包括 Exception :: Class Exception :: Simple autodie .

You could set some other global variable, like $Error, but the best way is to throw an exception. Then the user doesn't have to always check, and forget, it just happens. In Perl, exceptions are generated with "die". die will take a string or an object. There's a number of modules to make throwing exceptions easier including Exception::Class, Exception::Simple, Ouch and autodie.

您可以使用 eval {} 捕获异常,但是有与此相关的许多问题,因此您应该使用

You can catch the exception with eval {}, but there are a number of problems with that so you should use something like Try::Tiny.

这篇关于从Perl子例程返回错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆