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; }

In reply to Re: Write a file if grep finds a pattern? by chrestomanci
in thread Write a file if grep finds a pattern? by matze77

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.