Yup. Now, if you are doing a lot of stuff that requires all this cleanup, you might want to reuse your cleanup code. Here's how:
Code:
sub errorcheck_db_action(&) {
my($func) = @_;
eval {
&$func();
}
if($@) {
if($@ eq "Multiple rows returned") {
whatever_cleanup();
} elsif(...) {
...
} else {
die $@; # if we don't know what kind of exception it is, pass it along
}
}
}
errorcheck_db_action {
do_database_stuff();
};
If you're confused as to what sub foo(&) { ... } does, check
perldoc perlsub for prototypes. Basically, the stuff inside the curlies becomes an anonymous subroutine without the "sub" keyword. It even gets its own @_ and everything, and if you have values outside it, it sees them. (It's a thing computer scientists call closures... it just works.)
All you need to iron out is where you're going to stash your DBI object. If you subclass DBI and use it as a method, you lose the prototype, so calling it would look like $dbi->errorcheck_action(sub { block_of_code; }). The syntax wouldn't be as nice, but it'd work.