Can anyone please help me on the below issue?

I have a input log file that will be growing. I need to read this input file and print the last record whenever certain pattern matches (pls remember that input file is dynamic - other files will be writing to it). I'm not able to write to the output file but print it on STDOUT. Code piece is below:

use strict;
use IO::Handle;
open(IN, "posfile.txt"); ## this file will be growing
for (; {
while (<IN>) {
my $line = $_;
my @array = split /\|/;
if (eof) {
open(OUT, ">posoutfile.txt") or die "cant open file\n";
print OUT $_;
#print $_;

Thanks is advance.

Is this on Unix? What I would do is use:

tail -f -n [# of lines] | grep [pattern] >> file.txt

And not use perl at all. If it's on Windows, cygwin can help with that.