views:

56

answers:

1

I started learning how to make a module in perl with perltoot:

 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 :)

+4  A: 

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;
}
Alan Haggai Alavi
Nice way of doing it, do you have a function to use that with too or you just wrap croak whenever you need to throw an expection at something ? i am really sorry that i can't upvote your answer yet as i dont have enough points but if someone reads this please upvote his answer.
Guapo
Note that perl's exception mechanism is actually uses `die` to throw exceptions and `eval BLOCK` (or nice abstractions on top of that, such as [`Try::Tiny`](http://search.cpan.org/perldoc?Try::Tiny)) to catch them. `croak` is just sort of a wrapper around die. `perldoc -f die` has lots of more details on exceptions in perl.
rafl