Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Write a file if grep finds a pattern?

by matze77 (Friar)
on Nov 19, 2010 at 08:50 UTC ( #872447=perlquestion: print w/ replies, xml ) Need Help??
matze77 has asked for the wisdom of the Perl Monks concerning the following question:

Hello!
I want to write a file if grep finds a certain pattern "error" in file c:/temp/logbook.log.
I thought i could use the returncode "0", could you help me where to place the "if" construct, my code is broken:

use strict; use warnings; open (my $IN,"<c:/temp/logbook.log") || die "can not open datei: $!"; print grep /error/i, <$IN>; if ($_ ==0){ my $file = '/temp/ok.txt'; # open FILE, '>', $file or die "Kann Datei $file nicht zum Schreiben +oeffnen: $!\n"; # print FILE "ok!\n"; # close FILE; } close $IN;

Thanks
MH

Comment on Write a file if grep finds a pattern?
Download Code
Re: Write a file if grep finds a pattern?
by rovf (Priest) on Nov 19, 2010 at 08:58 UTC
    I thought i could use the returncode "0"
    I don't see you using any return code (other than the one returned by open. But what puzzles me more is that you didn't get Use of uninitialized value $_ in print. AFIK, in your particular program, $_ isn't implicitly set anywhere.


    -- 
    Ronald Fischer <ynnor@mm.st>
Re: Write a file if grep finds a pattern?
by Anonymous Monk on Nov 19, 2010 at 09:04 UTC
    Consider this
    $ perl -MDDS -le" Dump($_); print grep /stuff/, 1,2,3,stuff; Dump($_)" $VAR1 = undef; stuff $VAR1 = undef; $ perl -MDDS -le" Dump($_); warn print grep /stuff/, 1,2,3,stuff; Dump +($_)" $VAR1 = undef; stuff 1 at -e line 1. $VAR1 = undef;
    You want something like
    my $returncode; while(<IN>){ if( /error/i ){ print; $returncode++; } } if ( $returncode ){ BoogieWoogie(); }
      Thanks, that did the trick.
      use strict; use warnings; my $returncode; $returncode = 0; open (my $IN,"<c:/temp/logbook.log") || die "can not open datei: $!"; while(<$IN>){ if( /error/i ){ print; $returncode++; print "$returncode\n"; } } if ( $returncode == 0 ){ my $file = '/temp/ok.txt'; open FILE, '>', $file or die "Kann Datei $file nicht zum Schreiben +oeffnen: $!\n"; print FILE "ok!\n"; close FILE; } close $IN;


      Thanks
      MH

Re: Write a file if grep finds a pattern?
by chrestomanci (Priest) on Nov 19, 2010 at 09:37 UTC

    One tip I can offer is to avoid using the default variable ($_) in scripts unless you know what you are doing. There are lots of case where it does not do what you expect, or has unexpected side effects. It is much better to use explicit named variables in scripts. IMHO, frequent use of the default variable makes outsiders think that perl is a write only language.

    On the other hand, if you are trying to write a perl one liner with perl -e or demonstrate your skills in an obfuscated perl contest then go for it, but in those cases, readability and robustness are less important

    Also, you appear to be mixing up file handles as bare words and as scalars (IN vs $IN).

    Back to your problem, You wrote if ($_ ==0). I think that on that line $_ will contain the last line read from the file, so the if statement will not do what you expect. (I could be wrong though, as I also get confused about how the default variable works in some cases.) Personally I would write something like:

    use strict; use warnings; open (my $IN, '<', 'c:/temp/logbook.log') or die "can not open datei: +$!"; my $error_count = 0; while( my $line = <$IN> ) { if( $line =~ m/error/i ) { print $line; $error_count ++; } } close $IN; if( 0 == $error_count ) { open FILE, '>', $file or die "Kann Datei $file nicht zum Schreiben +oeffnen: $!\n"; print FILE "ok!\n"; close FILE; }
Re: Write a file if grep finds a pattern?
by mjscott2702 (Pilgrim) on Nov 19, 2010 at 09:37 UTC
    You could try something like this:

    use strict; use warnings; open (my $in,"<", "/tmp/logbook.log") or die "can not open datei: $!"; my @errors = grep /error/i, <$in>; my $file = '/tmp/ok.txt'; open my $out, ">", $file or die "Kann Datei $file nicht zum Schreiben +oeffnen: $!\n"; if (@errors) { print $out @errors; } else { print $out "OK!\n"; } close($in); close($out);


    If the logbook.log file has something like this:
    line1 has an error
    line2 does not
    ERROR on line 3
    
    the following output is in the ok.txt file:
    
    line1 has an error
    ERROR on line 3
Re: Write a file if grep finds a pattern?
by JavaFan (Canon) on Nov 19, 2010 at 11:25 UTC
    Can't resist giving a shell solution, as it's shorter than the Perl solutions offered so far:
    if grep -l error /temp/logbook.log > /dev/null then echo 'ok!' > /temp/ok.txt fi
      ?
      if( `grep -l error /temp/logbook.log > /dev/null`) `echo 'ok!' > /temp/ok.txt` }
        Let's say, you're asking the shell to run grep and discard the output, then collect the output, and if you say anything, you ask the shell to put something in a file, all to show your "Perl" program is as long as a shell one?

        It doesn't even work this way.

        But if you want to golf (if you have 'ack', shave off one character):

        grep error c:/temp/logbook.log&&echo 'ok!'>/temp/ok.txt
        Slapping backquotes on it to make it "Perl", still is two characters more.
Re: Write a file if grep finds a pattern?
by CountZero (Bishop) on Nov 21, 2010 at 10:24 UTC
    What about this:
    { open my $IN, '<', 'c:/temp/logbook.log' or die "cannot open datei: + $!"; open my $FILE, '>', 'c:/temp/ok.txt' or die "Kann Datei 'c:/temp/o +k.txt' nicht zum Schreiben oeffnen: $!"; say $FILE 'ok!' if scalar grep /error/, <$IN>; }

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://872447]
Approved by rovf
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (10)
As of 2014-07-22 22:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (129 votes), past polls