Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Question regarding handling exceptions in subroutine

by walkingthecow (Friar)
on May 12, 2013 at 08:29 UTC ( #1033176=perlquestion: print w/replies, xml ) Need Help??
walkingthecow has asked for the wisdom of the Perl Monks concerning the following question:

My script runs a command on a Linux system. For example:
while ( my $user = <$fh> ) { chomp $user; my $out = $system->adduser( login => $user ); if ( $out =~ /something/ ) { do this; } }

Now, in my subroutine I want to run useradd $login and grab the output from the system. If the output is an error (e.g., user already exists), I want to return something like, "ERROR: $login already exists\n", or "ERROR: $login is not a valid UNIX username\n"... If it worked, it should return something like, "SUCCESS: $login added to system" Currently I am croaking if it's not a success, but that destroys my while loop.

Basically, what's the best way to return an error message from a subroutine, and a success message if it succeeds?

I've read the following:

While interesting, I know Perl has changed a lot in the past few years, so trying to get an updated opinion on the matter. Thanks!

Replies are listed 'Best First'.
Re: Question regarding handling exceptions in subroutine
by choroba (Chancellor) on May 12, 2013 at 10:05 UTC
    Please, be more specific. You want to return an error or success, but still continue the loop. That is not possible - once you return, the loop is done. Probably, you can return two array references: the first array would contain successful users, the second one the failed users.
    لսႽ ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      The loop is in and calls the subroutine from When I croak in it makes exit, thus breaking the loop in I'd rather have the subroutine in return the error to a variable in Hopefully that clears things up. I'm terrible at explaining things.

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

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1033176]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2016-10-21 17:24 GMT
Find Nodes?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?

    Results (289 votes). Check out past polls.