LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   PERL:how to find a blank line in a file--regular expression (https://www.linuxquestions.org/questions/programming-9/perl-how-to-find-a-blank-line-in-a-file-regular-expression-630956/)

littletransformer 03-27-2008 03:28 AM

PERL:how to find a blank line in a file--regular expression
 
soursefile:
this is the first line
this is the second line

this is the third line
this is the fourth line

I want to tell wether there is a blank line and delete it.
so I write the code as follows:
#!/usr/bin/perl
$filename="d:\\text";
open($in,$filename)||die"can not open source file";
open(OUT,">>d:\\text01")||die"can not create file";
while($str=<$in>)
{
if($str!=~/\s/){print "yes";print OUT $str;}
}
close($in);
close(OUT);

but it didn't work.Do you have any ideas what to do?

exscape 03-27-2008 03:35 AM

if($str!=~/\s/){print "yes";print OUT $str;}
should be
unless($str =~ /^\s*$/){print "yes";print OUT $str;}

That'll match completely empty lines (^$) as well as line consisting of only whitespace.

littletransformer 03-27-2008 07:45 AM

thanks,it did work.but I am still confused about that,what shoud I do if I want to use the if sentense,since if and unless sentense can be represented for each other?

angrybanana 03-27-2008 06:35 PM

Quote:

Originally Posted by littletransformer (Post 3101913)
thanks,it did work.but I am still confused about that,what shoud I do if I want to use the if sentense,since if and unless sentense can be represented for each other?

Code:

if ($str !~ /^\s*$/){print "yes";print OUT $str;}

chrism01 03-27-2008 06:55 PM

Here's how I ignore/skip empty file recs and those starting with a comment in a cfg file
Code:

    # Process cfg file records
    while ( defined ( $cfg_rec = <CONFIG_FILE> ) )
    {
        # Remove unwanted chars
        chomp $cfg_rec;                # newline
        $cfg_rec =~ s/#.*//;            # comments
        $cfg_rec =~ s/^\s+//;          # leading whitespace
        $cfg_rec =~ s/\s+$//;          # trailing whitespace

        next unless length($cfg_rec);  # anything left?
   
    # here you'd print the rec out to the new file if you get this far



All times are GMT -5. The time now is 02:57 AM.