madbombX has asked for the wisdom of the Perl Monks concerning the following question:
Thus far you have all been extraordinarily helpful in my experiences with Perl and I have to once again ask for your assistance.
I have some code that I need to run, but I only want to write it once. I know that I can enclose is in subroutines like such:
if ($opt{'c'}) { open CATLOG, "<$MAILLOG"; while (my $line = <CATLOG>) { while_sub($line); } } else { $log = File::Tail->new( name => $MAILLOG, tail => -1); while (defined(my $line=$log->read)) { while_sub($line); } }
For my own coding style and the program flow and readability, I would prefer to do something like is below, however I know that this won't work (syntactically), but I believe it illustrates my goal. I want to just go through the file once (cat it) if $opt{'c'} is set, otherwise I want to tail it (using File::Tail).
if ($opt{'c'}) { open CATLOG, "<$MAILLOG"; while (my $line = <CATLOG>) { } else { $log = File::Tail->new( name => $MAILLOG, tail => -1); while (defined(my $line=$log->read)) { } ...while loop code here... } # End while loop close (CATLOG) if ($opt{'c'});
I am pretty sure that it would have something to do with BLOCK: { } expressions (even though I am not sure how to structure it) or potentially working an eval statement in there. Help. Thanks.
UPDATE:Thanks to all who helped. The key to this was tie. I now have it written as follows:
if ($opt{'c'}) { open MAILLOG_R, "<$MAILLOG" or die("Unable to open mail log: $!\n"); } else { tie *MAILLOG_R, 'File::Tail', (name => $MAILLOG, tail => -1); } while(my $line = <MAILLOG_R>) { ...blah... }
Note: The reason I use MAILLOG_R is because, using another PM, I tie *MAILLOG_W for consistancy.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Looping based on a Conditional
by ikegami (Patriarch) on Jul 20, 2006 at 17:20 UTC | |
|
Re: Looping based on a Conditional
by shmem (Chancellor) on Jul 20, 2006 at 17:36 UTC | |
|
Re: Looping based on a Conditional
by diotalevi (Canon) on Jul 20, 2006 at 17:39 UTC | |
|
Re: Looping based on a Conditional
by friedo (Prior) on Jul 20, 2006 at 17:15 UTC | |
by madbombX (Hermit) on Jul 20, 2006 at 17:28 UTC | |
|
Re: Looping based on a Conditional
by izut (Chaplain) on Jul 20, 2006 at 17:13 UTC | |
|
Re: Looping based on a Conditional
by imp (Priest) on Jul 20, 2006 at 17:40 UTC |