develooper Front page | perl.beginners | Postings from April 2012

Re: foreach and next

Thread Previous | Thread Next
From:
Shlomi Fish
Date:
April 8, 2012 02:43
Subject:
Re: foreach and next
Message ID:
20120408124343.71efd6ef@lap.shlomifish.org
Hi Vyacheslav,

On Sun, 08 Apr 2012 06:12:53 +0000
Vyacheslav <agapov.slava@gmail.com> wrote:

> Hello all.
> My english bad and i have a problem.
> 
> I am connected to databases in a cycle foreach and the script die, if 
> one of database is not available.
> 
> #!/usr/bin/perl
> 
> use strict;
> use warnings;
> use DBI;
> use DBD::mysql;
> 
> foreach $db (&hostdb("$project")) {
> 
> my $server = "$db";
> my $dbname = "information_schema";
> my $port = "3306";
> my $dsn = "dbi:mysql:$dbname:$server:$port";
> my $user = "user";
> my $pass = "pass";
> 
> my $dbh = DBI->connect($dsn, $user, $pass) or die "Can't connect to the 
> DB: $DBI::errstr\n";

Your problem is that you are invoking die "..." which throws an exception. See:

https://www.socialtext.net/perl5/exception_handling

Since this exception is not caught (using eval { ... }) it terminates the
entire program. So what you should do instead is handle it gracefully (say
using "next"):

my $dbh = DBI->connect($dsn, $user, $pass);

if (!$dbh)
{
	next DB_HOSTS_LOOP; # And label the loop appropriately.
}

Regards,

	Shlomi Fish

-- 
-----------------------------------------------------------------
Shlomi Fish       http://www.shlomifish.org/
"Humanity" - Parody of Modern Life - http://shlom.in/humanity

Chuck Norris refactors 10 million lines of Perl code before lunch.

Please reply to list if it's a mailing list post - http://shlom.in/reply .

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About