V U Maheswara rao k wrote:
HI ,

Hello,

I have to get only error messages and warnings text form
"/var/log/messages".

I wrote below code for to get only "warnings, error and caution " messages
from a file.
but grep command wont work. because I have to pass scalar variable to
search.

#!/usr/bin/perl
use warnings;
use strict;

open (FH , "< /var/log/messages");

You should *always* verify that the file opened correctly:

open FH, '<', '/var/log/messages' or die "Cannot open '/var/log/messages' $!";


my @search = qw( warnings errors Caution);
my @file = <FH>;

Why are you reading the whole file in at once?

close FH;
foreach (@file)

Instead of the previous three lines use a while loop:

while ( <FH> ) {

   if(grep(/^...@search/,$_)){

grep() works with lists but you only need to compare against a scalar. grep(/^...@search/,$_) should be just $_=~/^...@search/ or simply /^...@search/:

    if ( /^...@search/ ) {

Your regular expression is being interpolated as:

    if ( /^warnings errors Caution/ ) {

So the line must start with the string "warnings errors Caution" but you probably want to match either "warnings" or "errors" or "Caution" so your pattern should be:

    if ( /^(?:warnings|errors|Caution)/ ) {


         print $_;
   }
}
please help me to get only search string. optimised code.




John
--
The programmer is fighting against the two most
destructive forces in the universe: entropy and
human stupidity.               -- Damian Conway

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to