Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Executing script in normal/daemon mode and adding start/stop capability

by ELISHEVA (Prior)
on Oct 07, 2009 at 11:12 UTC ( #799689=note: print w/ replies, xml ) Need Help??


in reply to Executing script in normal/daemon mode and adding start/stop capability

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.


Comment on Re: Executing script in normal/daemon mode and adding start/stop capability
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://799689]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (7)
As of 2014-07-12 11:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (239 votes), past polls