in reply to How do I report an error back to the user of my object?

Another option is to have a $self->{ERRORSTR} property that can be obtained via "sub errorstr{}" method.

It should default to the empty string.

Update: On second thoughts, it should also be available as a CLASS method - perhaps setup a private Class variable (our $ERRORSTR), that can be accessed via $ClassName::ERRORSTR
This would be necessary/useful in the event that the "new" method failed to instantiate an object.
I could see coding a method like this:

our $ERRORSTR=""; sub new{ ... on failure, $ERRORSTR="*KAPUT*: Monkeywrench in our NEW method"; } sub OtherMethod{ .. on error, $self->{ERRORSTR}="*KAPUT* I really hate that parameter + you tried to pass to me"; return -1; } sub errorstr{ # Both class, and Instance Method my ($self)=@_; ref $self or return $ERRORSTR; # Class call return defined ($self->{ERRORSTR}) ? $self->{ERRORSTR} : $ERRORSTR; }
Update> Add "ref" to sub errorstr, based on tobylink and polymorpheus's comments below.

             I hope life isn't a big joke, because I don't get it.
                   -SNL

Replies are listed 'Best First'.
Re^2: How do I report an error back to the user of my object?
by tobyink (Canon) on Jun 05, 2012 at 06:21 UTC

    I'd write that as...

    sub errorstr { # Both class, and Instance Method ref($_[0]) ? $_[0]{ERRORSTR} : $ERRORSTR; }

    Yours will die if the user calls ClassName->errorstr.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re^2: How do I report an error back to the user of my object?
by polymorpheus (Novice) on Jun 05, 2012 at 13:15 UTC

    I would highly suggest you do not take an approach like this. Exception based errors (die/eval) are far superior in many respects. If you are not convinced yet, do some research (PBP, Modern Perl). Also look at all the monks! Most have already suggested die() and for good reasons!

    Also, in errorstr() I think I see a bug:
    $self or return $ERRORSTR; # Class call
    I think you meant to do this?
    ref $self or return $ERRORSTR; # Class call
    But more importantly, use exceptions instead!
      Agreed (and fixed). But I would suggest using Carp which has a "confess" method that can provide a stack trace to point out the callers evil ways.

                   I hope life isn't a big joke, because I don't get it.
                         -SNL