我开始学习如何使用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;
}
答案 0 :(得分: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;
}