To avoid code duplication, use a subroutine.
Also you will find your code easier to read an debug if you use consistent indenting. The block of code controlled by a flow-of-control statement should always be indented inside the flow of control statement. It is also a good idea to be consistent in your choice of cuddled and uncuddled curly braces.
A third bit of advice, $@ can sometimes be set to undef even if there is an error. Even so, eval will always return undefined when there is an error. A much better way to check for errors is the incantation:
eval { # my stuff ... #Note: return *only* exits eval {...} #make sure success "returns" true return 1; } or do { # what you are currently putting inside if ($@) {...} goes here. }
With a subroutine and the above eval incantation, your code (indenting revised):
if($opt_daemon) { # ... intro stuff while (1) { foreach my $opt_mailid (@mail_ids) { my ($log) = Log::Log4perl::get_logger('main'); my $data = get_data('mail_id' => $opt_mailid, 'file_path' => "/spool/emails"); ##connect db MysqlUtils::connect(); eval { MysqlUtils::insert_record($data); }; if($@) { $log->error("unable to insert data"); } } } } else { print STDOUT "Normal mode\n"; my ($log) = Log::Log4perl::get_logger('main'); my $data = get_data('mail_id' => $opt_mailid , 'file_path' => "/spool/emails"); ##connect db MysqlUtils::connect(); eval { MysqlUtils::insert_record($data); }; if($@) { $log->error("unable to insert data"); } }
becomes
sub runMailHandler { my ($opt_mailid) = @_; my ($log) = Log::Log4perl::get_logger('main'); my $data = get_data('mail_id' => $opt_mailid , 'file_path' => "/spool/emails"); ##connect db MysqlUtils::connect(); eval { MysqlUtils::insert_record($data); return 1; } or do { $log->error("unable to insert data"); } } if($opt_daemon) { # intro stuff ... while (1) { runMailHandler($_) foreach @mail_ids; } } else { runMailHandler($opt_mailid); }
Best, beth
Update Added comments about eval handling.
In reply to Re: Executing script in normal/daemon mode and adding start/stop capability
by ELISHEVA
in thread Executing script in normal/daemon mode and adding start/stop capability
by chanakya
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |