carol
carol

Reputation: 171

How do I detect an empty line from input or a file in Perl?

while ($_ ne ' \n') doesn't detect if the input is an empty line and loop indeterminately in while. Why?

Upvotes: 1

Views: 16516

Answers (5)

user918938
user918938

Reputation:

It depends on how you are reading in the file. Probably the newline is being removed. You usually just read in the file as while ( <> ) { ... }.

Upvotes: 0

Dave Cross
Dave Cross

Reputation: 69244

Depends what you mean by "an empty line".

Does the line contain no characters other than the newline?

if ($_ eq "\n") # Note, \n only means newline in a double quoted string.

Or

if (/^$/)

Does the line only contain whitespace characters

if (/^\s*$/)

But that is easier if you invert the logic to say the line doesn't include any non-whitespace characters

if (! /\S/)

One of those should do what you want.

Upvotes: 6

Simson
Simson

Reputation: 3559

Something like this

while(<>){
   if(/^$/){
                print "empty line";
        }else{
                print $_;
    }

}

It will open the file specified as arg0 on command line and print every line except the empty. <> put every read line in $_ which is implicitly used in the if statement.

Upvotes: 0

Filippo Lauria
Filippo Lauria

Reputation: 2064

I used to use this regex to cross-platform match CRLF bytes:

/(\r?\n|\r\n?)+$/

so you can combine it with this one that matches empty lines: /^\s*$/ in this way:

use strict;
use warnings;
 ...
open my $txtF,"$ARGV[0]";
for my $line (<$txtF>) {
  $line =~ s/(\r?\n|\r\n?)+$//; # strips all CRLF bytes at the end
  if ($line !~ /^\s*$/) { # now check if the line is not empty
    # do stuff
     ...
    # $line .= "\n"; if you need
    next;
  }
}
 ...
close $txtF;
 ...

Upvotes: 2

sateesh
sateesh

Reputation: 28673

You can do something like shown below, inside the loop:

if ($_ =~/^$/) {
 ...
}

Upvotes: 1

Related Questions