Chedi Bechikh
Chedi Bechikh

Reputation: 173

Detect empty line (contain only space) in perl

my program read a file, and i don't want to treat empty line

while (<FICC>) {
my $ligne=$_;
if ($ligne =~ /^\s*$/){}else{
print " $ligne\n";}

but this code also print empty line

the file that i test with contain:

Ms. Ruth Dreifuss Dreifuss Federal Councillor Federal ruth
     
sir christopher warren US Secretary of state secretary of state
     
external economic case federal economic affair conference the Federal Office case
     
US bill clinton bill clinton Mr. Bush
     
Nestle food cs holding swiss Swiss Performance Index Performance

Upvotes: 0

Views: 934

Answers (3)

Dave Cross
Dave Cross

Reputation: 69244

An easier way to write that is probably to invert the logic and only print lines that contain non-whitespace characters.

while (<FICC>) {
  my $ligne = $_;
  if ($ligne =~ /\S/) {
    print " $ligne"; # No need for linefeed here as $ligne already has one
  }
}

Update: Demo using your sample data:

#!/usr/bin/perl

use strict;
use warnings;

while (<DATA>) {
  my $ligne = $_;

  if ($ligne =~ /\S/) {
    print " $ligne";
  }
}

__END__
Ms. Ruth Dreifuss Dreifuss Federal Councillor Federal ruth

sir christopher warren US Secretary of state secretary of state

external economic case federal economic affair conference the Federal Office case

US bill clinton bill clinton Mr. Bush

Nestle food cs holding swiss Swiss Performance Index Performance

Output:

 Ms. Ruth Dreifuss Dreifuss Federal Councillor Federal ruth
 sir christopher warren US Secretary of state secretary of state
 external economic case federal economic affair conference the Federal Office case
 US bill clinton bill clinton Mr. Bush
 Nestle food cs holding swiss Swiss Performance Index Performance

Which seems correct to me.

Upvotes: 3

StanOverflow
StanOverflow

Reputation: 567

The reason is also that you're adding a new line, to the end of your string which already has a newline in it "$ligne\n", so use chomp as below

I think the nicer way of doing this is with next (skip to next loop iteration) as it removes some brackets from your code:

while (<FICC>) {
    my $ligne=chomp $_;
    next if $ligne =~ /^\s*$/;
    print " $ligne\n";
}

Upvotes: 1

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

I think it is because of using the \n within your code. Just remove that \n from your code and it should be fine.

Usually people do chomp after reading a line from a file to remove the end of line character.

Upvotes: 3

Related Questions