2016-01-20 38 views
0

我的程序读取一个文件,我不想把空行检测空行(仅包含空格)在Perl

​​

但是这个代码同时打印空行

的文件我测试包含:

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 
+2

你可以发布“空行”的转储吗? 'print join'',映射ord,split //,$ ligne'。 – choroba

+0

程序打印10 –

回答

3

我认为这是因为使用\n代码内。只需从代码中删除\n,它应该没问题。

通常人在从文件中读取一行以消除行尾字符之后做chomp

1

原因也是您要添加一个新行,你的字符串的结尾已经有它“$ LIGNE \ n”换行,所以使用格格如下

我想这样做的更好的方法是用下一个(跳到下一个循环迭代),因为它消除了从你的代码中括号:

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

编写一个简单的方法可能是反转的逻辑,只会打印线包含非空白字符。

更新:使用您的样本数据演示:

#!/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 

输出:

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 

这似乎是正确的我。

+2

我认为OP的问题在于他们打印的是“'ligne \ n”'而没有篡改原始换行符,所以输出是双倍行距 – Borodin

+0

好点。我会编辑。 –

+0

问题是如果我添加'其他{打印'ligne“}'这个打印空行,所以它检测到空行,但其他没有做任何事情 –