2

我开始学习如何使用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;
  • 我想知道,如果可能的话,我应该如何使用示例代码来威胁模块内外的任何错误?

例如:

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

或者

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;
}
  • 如果我在模块中调用任何其他有错误、问题、缺少参数的东西,那么正确的方法是如何判断有错误?

PS:希望我的问题不会太离谱,大家好:)

4

1 回答 1

4

Carp例程可用于报告错误。

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;
}
于 2010-10-08T04:08:44.403 回答