in reply to Re: Question regarding handling exceptions in subroutine
in thread Question regarding handling exceptions in subroutine

The loop is in script.pl and calls the subroutine from Script.pm. When I croak in Script.pm it makes script.pl exit, thus breaking the loop in script.pl. I'd rather have the subroutine in Script.pm return the error to a variable in script.pl. Hopefully that clears things up. I'm terrible at explaining things.
  • Comment on Re^2: Question regarding handling exceptions in subroutine

Replies are listed 'Best First'.
Re^3: Question regarding handling exceptions in subroutine
by moritz (Cardinal) on May 12, 2013 at 10:37 UTC
Re^3: Question regarding handling exceptions in subroutine
by space_monk (Chaplain) on May 12, 2013 at 11:28 UTC

    The obvious answer is to remove the croak (or perhaps change it to a carp/warn).

    You can run a command in backticks to trap both the output and the status code it returns. So you should be able to do something like:

    my $response=`useradd fred ....`; #check the status code (0 = success) if ($? >>8) { # we could not add the user }
    If you spot any bugs in my solutions, it's because I've deliberately left them in as an exercise for the reader! :-)

      Shouldn't it be something like this?

      Update:

      OK, eval...

      my $result; eval { $result = qx($command); }; if ( $? >> 8 != 0 ) { if ($@) { die $@; } else { die qq(Something really weird happened!); } } # do stuff with $result...

      Regards, Karl

      «The Crux of the Biscuit is the Apostrophe»

        Thanks, you're right about the other issues, I was simply in a hurry to outline a way forwardat least that's the excuse I'm using :-)

        Question: Why 'eval' this instead of just running this in backticks? I understand the command can fail, but in those cases it simply returns an error code.

        If you spot any bugs in my solutions, it's because I've deliberately left them in as an exercise for the reader! :-)

      Shouldn't it be:

      my $result = qx($command); if ( $? >> 8 != 0 ) { if ($@) { die $@; } else { die qq(Something really weird happened!); } }

      Regards, Karl

      «The Crux of the Biscuit is the Apostrophe»