Your actual code may make this unworkable, but for the specific example you gave, you could do:
sub check_id {
my ( $id )= @_;
my $res;
eval {
my $obj= ObjClass::Obj->new();
$obj->id( $id );
$obj->load_via_id() ;
$res= $obj->id ;
if (! $obj->activated_account) {
DEBUG && warn "invalid user";
return -1;
}
}
if ($@) {
DEBUG && log_error( $@ );
return -1;
}
return $res;
}
That changes the behavior, though. To get your original behavior, change warn to mywarn. I have no idea what mywarn() would do, because it seems like in your example code the string "invalid user" is never used for anything. So I'm unclear as to what it's for.
Slightly more generally, you could allow multiple of these eval blocks in a single routine with (excuse the funny indentation):
sub check_id {
my ( $id )= @_;
my $res;
eval { {
my $obj= ObjClass::Obj->new();
$obj->id( $id );
$obj->load_via_id() ;
if (! $obj->activated_account) {
warn "invalid user"; # or not...
$res = -1;
last;
}
$res= $obj->id ;
} }
if ($@) {
DEBUG && log_error( $@ );
return -1;
}
return $res;
}
I haven't thought that through to what it would mean for chained blocks, partly because I'm not sure whether you mean nested blocks or a series of independent blocks.
Your return values seem a little odd, though. This routine can return three things: undef, -1, or a valid id, where -1 seems to mean either an expected or unexpected error and undef means... well, I don't know. There must be some reason why you're doing $res = $obj->id. Is there some reason why it might not return a valid id, other than the activated_account test failing? If not, then why not just set $res to -1 if activated_account fails? Why throw an exception at all if it isn't really an exceptional case? If there is some subset of cases where an undef return value is meaningful, then it seems like the caller of this function has to do too much work to decipher all the possible things the return value might mean.
-
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.