Does one of these two ways have to be preferred or is it only a matter of taste?
#!/usr/bin/env perl
use warnings;
use strict;
use DBI;
my $db = 'sqlite_db';
#################### A ####################
sub get_database_handle {
my ( $db ) = @_;
my $dbh;
eval {
$dbh = DBI->connect( "DBI:SQLite:$db", '', '', {...} )
or die DBI->errstr;
};
if ( $@ ) {
print $@;
return;
}
return $dbh;
}
DATABASES: while ( 1 ) {
# choose a database from a list of databases
# ...
my $dbh = get_database_handle( $db );
next DATABASES if not defined $dbh;
# ...
# do something with the database
}
#################### B ####################
sub get_database_handle {
my ( $db ) = @_;
my $dbh = DBI->connect( "DBI:SQLite:$db", '', '', {...} )
or die DBI->errstr;
return $dbh;
}
DATABASES: while ( 1 ) {
# choose a database from a list of databases
# ...
my $dbh;
eval { $dbh = get_database_handle( $db ); };
if ( $@ ) {
print $@;
next DATABASES;
}
# ...
# do something with the database
}
Why eval at all? What are you going to do when you can’t get a database handle?
At the very least, the subroutine should either return a database handle or die, so no eval in there.
If you really have something productive to do when there is a database error, then eval outside of the subroutine. Not necessary around just the subroutine, could be even wider scope, as appropriate for your error handling logic.
But if all you want is terminate the program and print an error, just let the exception bubble up.