Michael Weber wrote:
> I am trying to write a simple filter that will mark in different
> colors certain words as they pass through.
> 
> For example, if I do a tail -f /var/log/messages I want words I am
> looking for to be in red and other words in yellow with the rest of
> the text unchanged.  (There might be a way to do this already, but
> you can learn a lot by reinventing wheels sometimes!)
> 
> Here's the basic frame of code I'm using:
> 
> #!/usr/bin/perl -w
> 
> use strict;
> 
> my $line;
> 
> while(1) {
>         $line = <STDIN>;
>             # Highlighting code goes here...
>         print $line;
> }
> 
> 
> When I use a command like "cat textfile.txt | ./filter-test.pl" I get
> the text file printed out, just like I want, followed by an infinate
> number of "Use of uninitialized value in print at
> ./filter-test.pl line
> 9, <STDIN> line 185."

That's because after cat finishes, an EOF condition exists on STDIN, so
$line = <STDIN> sets $line to undef.

To end the loop, you can use "last":

   defined($line = <STDIN>) or last;

But it looks like you can just move that into the while condition:

   while ($line = <STDIN>) {
      ...
   }

That loop will end when there is no more input on STDIN.

But why force the input to come from STDIN? The more flexible construct
would
be:

   while ($line = <>) {
      ...
   }

This allows you to optionally specifiy filename(s) as command-line args. If
no files are specified, it automagically reads from stdin.

> 
> But, when I use  the command "tail -f /var/log/messages |
> filter-test.pl", it works fine.

Well, not really. tail -f never ends, so you never see the EOF condition on
STDIN. When you press ^C, the terminal driver sends a SIGINT to both
processes,
which causes them to end.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to