简体   繁体   English

我应该如何处理Perl模块内部或外部的错误?

[英]How should I handle errors inside or outside a Perl module?

I started learning how to make a module in perl with perltoot : 我开始学习如何使用perltoot在perl中制作模块:

 package Person;
 use strict;

 my($NAME, $AGE, $PEERS) = ( 0 .. 2 );

 sub new {
    my $self = [];
    $self->[$NAME] = undef;
    $self->[$AGE] = undef;
    $self->[$PEERS] = [];
    bless($self);
    return $self;
 }

 sub name {
    my $self = shift;
    if (@_) { $self->[$NAME] = shift }
    return $self->[$NAME];
 }

 sub age {
    my $self = shift;
    if (@_) { $self->[$AGE] = shift }
    return $self->[$AGE];
 }

 sub peers {
    my $self = shift;
    if (@_) { @{ $self->[$PEERS] } = @_ }
    return @{ $self->[$PEERS] };
 }

 1;
  • I would like to know how, if possible with sample code should I threat any errors within the module and outside it ? 我想知道如何在可能的情况下通过示例代码威胁模块内部及其外部的任何错误?

For example: 例如:

 use Person;
 $test= Person->new() or die Person->Error;

or 要么

sub new {
   my $self = [];
   $self->[$NAME] = undef;
   $self->[$AGE] = undef;
   $self->[$PEERS] = [];
   bless($self);
   #########
   # some error happened here and I need to say something
   #########
   return $self;
}
  • If I call anything else within the module that had a error, problem, missing argument how is the correct way to tell there was an error ? 如果我在模块中调用了其他任何有错误,有问题,缺少参数的方法,那么如何正确地判断出有错误呢?

PS: Hope my question is not too off and hi everyone :) PS:希望我的问题不是太过分了,大家好:)

Carp routines can be used to report errors. 鲤鱼例程可用于报告错误。

use Carp qw{ croak };

sub new {
    my $self        = {};
    $self->{$NAME } = undef;
    $self->{$AGE  } = undef;
    $self->{$PEERS} = [];

    # replace the following with something appropriate
    if ($error_occurred) {
        croak 'Something did not work right';
    }

    return bless, $self;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM