in reply to Write a file if grep finds a pattern?
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; }
|
|---|