wusphere has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
I would like to know, how could I evaluate the status of a subroutine. See the subroutine below. If it fails, I would like to capture the status and process something else. All your help is appreciated.

sub verifyRecCount ($,$,$) { my ($recCount) = @_[0]; my ($tlrRecordCount) = @_[1]; my ($verRecordCount) = @_[2]; if ($recCount == $tlrRecordCount) { slog($logfile,"Comparing Record Count: $recCount to $tlrRe +cordCount. (OK!)"); $verRecordCount = 1; } else { slog($logfile,"Comparing Record Count: $recCount to $tlrRe +cordCount. (FAILED!)"); exit 6; } return $verRecordCount; }# verifyRecCount()
Thanks

20040816 Janitored by Corion: Fixed code tag, added formatting

Replies are listed 'Best First'.
Re: Evaluate success or failure of a subroutine
by japhy (Canon) on Aug 16, 2004 at 13:46 UTC
    Don't use exit() to leave a subroutine, it stops your program entirely. Instead, return a specific value, like 0, and set some global error variable if you want.
    _____________________________________________________
    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: Evaluate success or failure of a subroutine
by Zaxo (Archbishop) on Aug 16, 2004 at 13:49 UTC

    If you change exit 6; to die 6, you can call your sub with

    my $result = eval { verifyRecCount($foo, $bar, $baz) }; doSomethingElse() if $@;
    That is perl's version of exception handling for errors.

    The other model is to return undef on error. Then defined can be used on the result to test for success.

    After Compline,
    Zaxo

Re: Evaluate success or failure of a subroutine
by Joost (Canon) on Aug 16, 2004 at 13:49 UTC
Re: Evaluate success or failure of a subroutine
by naChoZ (Curate) on Aug 16, 2004 at 15:19 UTC

    You've already received good responses, but I just thought I'd mention:

    my ($recCount) = @_[0]; my ($tlrRecordCount) = @_[1]; my ($verRecordCount) = @_[2];
    ...can be expressed:
    my ( $recCount, $tlrRecordCount, $verRecordCount ) = @_;

    --
    "A long habit of not thinking a thing wrong, gives it a superficial appearance of being right." -- Thomas Paine
    naChoZ

      wusphere, while I prefer naChoZ's style, if you like the multi-line style, consider using

      my $recCount = $_[0]; my $tlrRecordCount = $_[1]; my $verRecordCount = $_[2];

      since it is much more efficient then taking array slices:

      my ($recCount) = @_[0]; my ($tlrRecordCount) = @_[1]; my ($verRecordCount) = @_[2];

      $array[num] means "get element num from the array @array".

      @array[num] means "create an array consiting of the element num of the array @array".