perl_zen_noob has asked for the wisdom of the Perl Monks concerning the following question:

I'm pretty new to perl. I'm trying to tail a log file (in any way) and match the output with a string to determine the next course of action. I've tried tailing a few ways, but I can't seem to get the tail to match the string that I'm searching for.

Here are the last few lines of the log that I'm tailing (/var/log/ping_10.10.0.100):

02-23-2010 11:20:01 10.10.0.100 is alive! 02-23-2010 11:30:01 10.10.0.100 is alive! 02-23-2010 11:40:01 10.10.0.100 is alive! 02-23-2010 11:50:01 10.10.0.100 is alive!

Here's my closest script:

#!/usr/bin/perl use strict; use warnings; my $tail = system("tail -1 /var/log/ping_10.10.0.100.sj"); #print "$tail\n"; if ($tail =~ m/alive/) { print "match\n"; } else { print "no match\n"; }

Sadly, it only returns a match if I try to match "0". Of course, I'm trying to match the word "alive". What am I doing wrong?

Replies are listed 'Best First'.
Re: Tail a log, then match its string
by toolic (Bishop) on Feb 24, 2010 at 03:14 UTC
    Try to change:
    my $tail = system("tail -1 /var/log/ping_10.10.0.100.sj");
    to:
    my $tail = qx(tail -1 /var/log/ping_10.10.0.100.sj);
    qx captures the output of the tail command into a variable; system does not. system returns the exit status of the command, which is 0 if the command succeeded. That is why you can match 0.

    Please update your node and use code tags around your data and code: see Writeup Formatting Tips

      Thanks for the quick replies. Wow, I'm ashamed to admit that I had been fighting this for 3-4 days. Within minutes, toolic solved it. Thanks a million. I'll sleep well tonight.

      And I promise that all future posts will be formatted better.

Re: Tail a log, then match its string
by Anonymous Monk on Feb 24, 2010 at 05:53 UTC
    Or use a module eg http://search.cpan.org/~mgrabnar/File-Tail-0.99.3/Tail.pm
Re: Tail a log, then match its string
by Anonymous Monk on Feb 24, 2010 at 03:07 UTC
    One thing, you aren't using code tags for your code :)