Esteemed Monks,

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.


In reply to Looping based on a Conditional by madbombX

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.