You're almost there.
# MAIN
unless ($result = my_sub() ) {
# Now you use $result if it's not 0
}
# WRAPPER function
sub my_sub {
eval { _my_sub(@_) };
if ($@) {
return $@;
} else {
return '';
}
}
# Actual worker...
sub _my_sub {
# Do your stuff here. If something fails, do a die with a useful error
+ message. Otherwise, return 0.
# For example ...
die "Bad data passed in.\n";
}
You actually do a
die which doesn't end your script - it gets trapped by the
eval and the string you passed
die will be put in $@.
Now, I personally dislike this type of error-handling because 0 is FALSE and non-zero is TRUE. Thus, you have to flip your thinking the way the C libs force you to and say you're calling the function and hope it "fails" for success. (Sorta like a drug screening ...)
Instead, I would something similar. Instead of passing back '' for success, I'd pass back undef instead.
# MAIN
if (defined ($error = my_sub()) ) {
# Now you use $error if it's defined
}
# WRAPPER function
sub my_sub {
eval { _my_sub(@_) };
if ($@) {
return $@;
} else {
return undef;
}
}
# Actual worker...
sub _my_sub {
# Do your stuff here. If something fails, do a die with a useful error
+ message. Otherwise, return 0.
# For example ...
die "Bad data passed in.\n";
}
It seems like a semantic difference, but now your code use TRUE and FALSE the way they intuitively used, to indicate success and failure.
------
We are the carpenters and bricklayers of the Information Age.
Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.