Thanks Jhon,

my search string  may be more than 100 words like ("warnings", "errors",
"Caution","Debug","notice","info"..etc). so that I want to get it from array
and search it in each line
I want to search a list in a line of file.

On Wed, Jan 27, 2010 at 6:28 PM, John W. Krahn <jwkr...@shaw.ca> wrote:

> 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/
>
>
>


-- 
-Mahesh

Reply via email to