Search code examples
regexperlprintinglines

Perl print unless regex and line counts


I currently have this working sorting through a zone file for automated deletions..

perl -i -ne 'print unless (/#$DOMAINNAME/ and \$n=7) .. not \$n--' named.conf.ext

(escaping n is required for it to work, I guess else it thinks the main script has a n variable to be passed?)

This call is from within a perl script and I would like to clean it up by not having to call a shell to re-run perl from a perl script to do it, and having the main script do it.

Not a perl expert here as you can likely tell :) I have tried things like

open (DATAIN, "<named.conf.ext");
 open (DATAOUT, "> named.conf.tmp");
 while (<DATAIN>){
  PRINT unless (/#foo.com/ and $n=7) .. not $n-- DATAOUT;
 }
 close DATAOUT;
close DATAIN;

and a few variants, but it complains syntax error at test line 4, near "-- DATAOUT"

I'm sure I'm being spacey at this, and the answer is right in front of me, but 2 days, I think the brain needs a kick start in where.

Thanks


Solution

  • It's normally

    print DATAOUT;
    

    which is short for

    print DATAOUT $_;
    

    so you want

    print DATAOUT unless (/#foo.com/ and $n=7) .. not $n--;
    

    or the longer

    print DATAOUT $_ unless (/#foo.com/ and $n=7) .. not $n--;