Reputation: 171
while ($_ ne ' \n')
doesn't detect if the input is an empty line and loop indeterminately in while. Why?
Upvotes: 1
Views: 16516
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
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
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
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
Reputation: 28673
You can do something like shown below, inside the loop:
if ($_ =~/^$/) {
...
}
Upvotes: 1