# 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. |