in reply to How to return errors from my object oriented subroutine

I usually do something like this:
sub do_something { my $args = shift; my $result = 0; # or "", or undef, or whatever my @errors = (); # Validate staff push @errors, "Where's the email?" unless ($args->{email}); push @errors, "Bad email" unless ($args->{email} =~ /\@/); # ... unless (@errors) { # Do something here # ... } return $result, @errors; }

This approach provides a convinient way to display errors later on, if need be, while still validating provided data and saving on processing if ugly staff was given.

sub display_status { my @errors = @_; if (@errors) { print "Operation failed due to following errors:\n"; foreach my $error (@errors) { print "\t- $error\n"; } } else { print "Operation succeded\n"; } }

Now, if you need to display only errors you can do:

my ($result,@errors) = do_something(\%args); if (@errors) { display_status(@errors); }

If you need to show to the user an OK message too, then just call display_status(@errors) unconditionally.

my two cents

Leonid Mamtchenkov aka TVSET

Replies are listed 'Best First'.
Re: Re: How to return errors from my object oriented subroutine
by princepawn (Parson) on Aug 20, 2003 at 16:34 UTC
    I would not return an array, but an array ref. First, it is more efficient, second, because an array is variable length, you can never easily tack on extra return values because the second expected value is not filling one slot in the return list. Using an array ref instead allows
    return $results, \@errors, \@thing_I_discovered_I_needed_later;

    Carter's compass: I know I'm on the right track when by deleting something, I'm adding functionality

    The Emacs Code Browser